Content: tags contextual filter seems to only match the first tag

Question: I have a contextual filter on the field content: tags set to "Match any value," but in practice, it appears that only nodes that match the first tag are displayed. For instance a node with the tags "blue, green" would show only other nodes tagged "blue."
Answer: It usually work better when you add a relationship to the view, where you relate the content to the taxonomy term.
Then you unlock a whole new collection of fields and filters.
Choose to filter by taxonomy - name instead of content - tags.
Comment: I was mistaken. "Taxonomy: name" didn't provide any results, but "Taxonomy term: Term ID" did provide results that matched the first tag, whether or not the default was set to match "any" or "all" taxonomy terms. The "Distinct" box is not checked under "Query settings." I couldn't find an aggregation setting. Thanks for your help.
Comment: Thanks Neograph. I added the relationship like you suggested. It still appears to be using only the first tag of the node providing the filter. However the filter returns nodes that have the tag in any position (1st, 2nd, ... nth).
Comment: Just adding the relationship is not enough. After adding the relationship you have to remove the current filter and create a new filter for taxonomy:name instead of node:tags. Your comment implies you only added the relationship.
Comment: Sorry, you're right about my comment. I followed your advice completely and was left with the results stated.
Comment: Do you have aggregation or distinct query results enabled?
Answer: The setting I was missing was under Advanced=>Contextual Filters=>Taxonomy term: Term ID=>More and check "Allow Multiple Values"


Como bloquear download de arquivos pdf

Question: Eu estou desenvolvendo uma plataforma EDA para um cliente, o mesmo tem várias apostilas em pdf que quer disponibilizar para os assinantes do curso, porém ele vende as apostilas físicas também, sendo assim ele quer evitar que os alunos baixem os pdfs do site, os deixando apenas para leitura, é possível fazer isso com php ?
Comment: Opa. Não sei lhe informar exatamente o que quer, mas já fiz um serviço que para evitar esse tipo de situação, fizemos assim: quando um usuário vai fazer o download do pdf, pegamos o pdf pai e reescrevemos ele com uma mensagem de alerta de privacidade e junto da mensagem o CPF do usuário em todas as páginas. E além disso colocamos senha no .pdf que é geralmente o CPF do usuário, assim inibindo ele de passar esse .pdf para terceiros ou fazer uma distribuição impressa.
Comment: a maneira que você achou bem interessante, vou procurar saber como fazer e aplicar para ver se da certo assim também, obrigado
Answer: http://www.botecodigital.info/php/protegendo-arquivos-de-download-com-login/
Dá uma olhada nesse link, acho que pode ajudar.
index.php
<?php
  session_start();
?>

      <meta charset="UTF-8">
      <title>Teste protegendo download autenticado</title>

    <?php if ( $_SESSION['logado'] == "true" ){ ?>

Você está logado

    logout
    <?php }else{ ?>
    Você não está logado!!!
    login
    <?php } ?>

  Download putty.exe

login.php
<?php
  session_start();

  $_SESSION['logado'] = 'true';

  header('location: index.php');
?>

logout.php
<?php
  session_start();

  unset($_SESSION['logado']);

  header('location: index.php');
?>

download.php
<?php
session_start();

if( $_SESSION['logado'] == 'true' ){

    $download = $_GET['download'];
    if( is_file( '/home/boteco/downloads/'.$download ) ){
        $filename = '/home/boteco/downloads/'.$download;

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $type = finfo_file($finfo, $filename);
        header('Content-type: '.$type);
        header('Content-Disposition: attachment; filename="'.$download.'"');

        readfile($filename);
    }else{
        echo "arquivo nao encontrado";
    }

}else{
    echo "Você não estaa logado. Faça o login para efetuar o download.";
}

?>

Na linha 2 chamamos a função session_start() para podermos ler e gravar informação na sessão.
Na linha 4 testamos se o usuário que acessou esta logado na sessão, se o usuário pode fazer o download.
Na linha 6 pegamos o nome do arquivo que recebemos via parâmetro GET da URL, como vimos no arquivo index.php na linha 18 para fazer o download chamamos download.php?download=putty.exe então queremos baixar o arquivo putty.exe.
Na linha 7 verificamos se o arquivo que recebemos por parâmetro existe e é um arquivo, você deve ter notado que utilizamos o caminho absoluto da pasta de download e concatenamos com o nome do arquivo recebido.
Na linha 8 armazenamos o nome absoluto do arquivo em uma variável para facilitar a manipulação.
Na linha 10 criamos um recurso fileinfo, para ser utilizado para ler o mime-type do arquivo.
Linha 11 lemos o MIME-TYPE do arquivo e armazenamos em uma variável, necessitamos pegar o MIME-TYPE do arquivo pois o nosso script de download possui o MIME-TYPE text/x-php e o comportamento do navegador para este MIME-
TYPE é mostrá-lo e não baixá-lo, se deixarmos o MIME em text/x-php e jogarmos o contudo do arquivo para o navegador, veremos o código binário do programa, ou seja, um monte de caracteres estranhos.
Na linha 12 modificamos o MIME do nosso script para o MIME lido do arquivo.
Na linha 13 forçamos o arquivo ser baixado com o nome recebido por parâmetro, lembrando, se não forçarmos ele irá utilizar o nome do script o que não seria algo legal  .
Na linha 15 utilizamos a função redfile que lê um arquivo e exibe ele na tela, como já modificamos o header do arquivo para um outro MIME e para forçar o download o arquivo será lido do sistema de arquivo e enviado para o usuário.
OBS: Só lembrando, a função finfo_open só está disponível no PHP >= 5.3.0, se você utilizar uma versão anterior pode utilizar mime_content_type mas lembre-se de verificar se ela está disponível na sua hospedagem, na minha por exemplo não está e não estou com vontade de me incomodar com eles, fiquei somente com o teste local.
Comment: Respostas apenas com links são ruins. Tenta colocar um pouco do conteudo do link na sua resposta, pois, se o link quebrar, a sua resposta também quebra. Eis o meu -1 até isso ser consertado
Comment: Por que usar snippets em códigos que não são executáveis no `cliente-side`?
Comment: Sua resposta está muito confusa. Começa com um link, então seguem 4 excertos de código e, no final, o corpo da resposta se refere a linhas individualmente, porém sem dizer de qual excerto elas pertencem. Não há uma ideia geral sendo descrita, então fica difícil para alguém um pouco mais leigo (como eu) entender o que está acontecendo

Como bloquear download de arquivos pdf


Woocommerce adding icon on a single product gallery image

Question: I wanted to ask if there is a hook with which I could add icon on a gallery image. I am using storefront theme. Icon container should be located in woocommerce-product-gallery wrapper.
This is how it should look like
Comment: Hi, did you checked my answer?
Answer: Please override the woocommerce/single-product template file in your activated theme diretory. You can find the code and result in the attached images.
hope this will work for you.
Comment: This is not right way, hook is better way to override code.
Comment: I thought about hook which could do that from functions.php but thanks for answer.
Comment: but I didn't find any hook for this. Please check in this link https://businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/
Answer: you can use the below hook:
woocommerce_product_thumbnails,
with this you can add anything on product image on single pahe for more check below link:
woocommerce_product_thumbnails


Deleting listbox's items using context menu c#

Question: So I have a listbox in my program and I want the user to be able to delete a specific item in it by accessing its context menu and clicking delete. Everything seems to be working fine if I delete its items in order (from top item to the last item). However, I get a debugging error when I don't delete the items in order. I want to know how will I be able to delete an item of my choice.
This is the code that will execute once the user right clicks an item in the listbox:
public void listBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        index = listBox.IndexFromPoint(e.Location);
        {
            if (index == listBox.SelectedIndex)
            {
                contextMenuStrip1.Show();
            }
        }
    }
}

This is the click event handler:
private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
    listBox.Items.Remove(listBox.SelectedItems[index]);
}

This is the error message from the IDE:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: Index was outside the bounds of the array.
Comment: what's the error message
Comment: Do you need a ObservableCollection?
Answer: listBox.SelectedIndex returns collection of selected items. Since user selects only one item, this collection has only one item with index 0. Trying to delete item with non-zero index will cause an error. Use listBox.Items.RemoveAt(index) instead:
private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
    listBox.Items.RemoveAt(index);
}


Atributo de uma struct receber várias structs

Question: É possível um atributo de uma struct receber várias structs?
Por exemplo, preciso que o atributo LPWFSPINFDK lppFDKs; que faz parte da struct _wfs_pin_func_key_detail, receba várias structs _wfs_pin_fdk.
Estou tentando dessa maneira, compila, porém o programa final não reconhece:
    WFSPINFUNCKEYDETAIL PinFunKeyDetail;

    WFSPINFDK ObjPinKey;
    LPWFSPINFDK PinKey;
    PinKey = &ObjPinKey;

    PinKey->ulFDK = WFS_PIN_FK_FDK01;
    PinKey->usXPosition = 5;
    PinKey->usYPosition = 5;

    PinFunKeyDetail.lppFDKs = &PinKey;

STRUCT: _wfs_pin_fdk
typedef struct _wfs_pin_fdk
{
    ULONG               ulFDK;
    USHORT              usXPosition;
    USHORT              usYPosition;
} WFSPINFDK, * LPWFSPINFDK;

STRUCT: _wfs_pin_func_key_detail
typedef struct _wfs_pin_func_key_detail
{
    ULONG               ulFuncMask;
    USHORT              usNumberFDKs;
    LPWFSPINFDK       * lppFDKs; //Aqui recebo as structs
} WFSPINFUNCKEYDETAIL, * LPWFSPINFUNCKEYDETAIL;

Answer: Respondendo: É possível um atributo de uma struct receber várias structs. O atributo a que você se refere, porém, é apenas um ponteiro, e não um contêiner. Ponteiros não podem receber várias structs, apenas endereços destas.
Algo que pode receber várias structs seria um std::vector<_wfs_pin_fdk>.

Pelos trechos postados, LPWFSPINFDK é um tipo definido como ponteiro para _wfs_pin_fdk.
Na classe _wfs_pin_func_key_detail, o atributo lppFDKs é um ponteiro para LPWFSPINFDK.
Ou seja: lppFDKs é um ponteiro para ponteiro de _wfs_pin_fdk.
Talvez você esqueceu de definir usNumberFDKs ? Inferindo pelo nome da variável, ela parece guardar quantos ponteiros para _wfs_pin_fdk são guardados em lppFDKs.
Alterando seu exemplo para que lppFDKs aponte para uma array de vários ponteiros:
WFSPINFUNCKEYDETAIL PinFunKeyDetail;

//três _wfs_pin_fdk
WFSPINFDK PinKeyA;
WFSPINFDK PinKeyB;
WFSPINFDK PinKeyC;

//(..algum código manipulado os _wfs_pin_fdk..)

//endereço dos três _wfs_pin_fdk , em array
LPWFSPINFDK PinKeys[3] = {
    &PinKeyA,
    &PinKeyB,
    &PinKeyC
};

//passa para lppFDKs o endereço da array de LPWFSPINFDK
PinFunKeyDetail.lppFDKs = PinKeys;

//palpite: esse atributo indica quandos elementos são apontados por lppFDKs
PinFunKeyDetail.usNumberFDKs = 3;

Você disse que

o programa final não reconhece

Mas isso é muito vago, não sei a que programa está referindo-se. Aqui está o código online, compilando no Ideone.


Why is $\mathbb{Q}_\infty = \mathbb{R}$?

Question: Why, in the context of p-adic numbers, do we have the convention
$$\mathbb{Q}_\infty = \mathbb{R} \quad$$
?
It must have something to do with the generalization of the Legendre-symbol for $\mathbb{R}$:
$$\left(\frac{\cdot}{\infty}\right) = \mathrm{sgn}(x)\, ,$$
but why does "$\infty$" make sense here?
Comment: No, $p=\infty$ is not a prime number. The absolute value $\mid.\mid_{\infty}$ is the Euclidean one, in contrast to the $p$-adic value.
Answer: The archimedean absolute value is denoted $|\cdot|_\infty$ for notational conveniency, so one can write for instance
$$
\prod_{p\leq\infty}|q|_p=1\qquad\forall q\in\Bbb Q, q\neq0.
$$
Thus, as $\Bbb Q_p$ denotes the completion of $\Bbb Q$ with respect to $|\cdot|_p$, it is more than natural to denote $\Bbb Q_\infty$ the completion of $\Bbb Q$ with respect to $|\cdot|_\infty$.


The absolute uri: http://www.springsource.org/tags/form cannot be resolved in either web.xml or the jar files deployed with this application

Question: Currently, I use a 'Maven' project where I put in my pom.xml the current dependencies to use Spring Framework where org.springframework.version = 3.1.0.RELEASE :
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${org.springframework.version}</version>
</dependency>

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${org.springframework.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

All the jar dependencies are sitting in target/myGoogleAppEngine-0.0.1-SNAPSHOT/WEB-INF/lib. This directory contains :
spring-aop-3.1.0.RELEASE.jar
spring-beans-3.1.0.RELEASE.jar
spring-webmvc-3.1.0.RELEASE.jar
spring-web-3.1.0.RELEASE.jar
spring-security-taglibs-3.1.0.RELEASE.jar
spring-security-web-3.1.0.RELEASE.jar
...

At the beginning of my address.jsp, I've the following line :
<%@ taglib prefix="form" uri="http://www.springsource.org/tags/form" %>

But I've the following error when I execute the address.jsp :
Error 500
org.apache.jasper.JasperException: The absolute uri: http://www.springsource.org/tags/form cannot be resolved in either web.xml or the jar files deployed with this application

Comment: http://forum.spring.io/forum/spring-projects/web/74017-the-absolute-uri-http-www-springframework-org-tags-form-cannot-be-resolved
Answer: If you open up spring-webmvc-3.1.0-RELEASE.jar/META-INF/spring-form.tld the <uri> to use is
<uri>http://www.springframework.org/tags/form</uri>

So you should have
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Comment: In my spring-form.tld, I've this line :http://www.springframework.org/tags/form
Answer: Add this dependency in pom.xml
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>Your Security Version</version>
</dependency>

Comment: Don't think this is the right answer, spring form is in `spring-webmvc` which according to OP is already a dependency.
Comment: They already have that library in their classpath. Also, that library is not required for the taglib they're using.
Comment: Your Security Version what i should give in this? its not working for me, I am trying so long please anyone suggest


PLSQL Cursor For Loop

Question: I am attempting to perform a trend analysis in PLSQL using a for loop nested inside of a cursor for loop. The goal is to return an actor between the years (2000-2013) who have acted in at least 8 movies within a 5 year window.
For example, a desired output would be: Wahlberg, Mark played in 10 movies between 2009 and 2013.
Here is the error I receive:

Here is the code i'm working with so far:
DECLARE
    t movie.yr%TYPE;
    actor_id actor.id%TYPE;
    total INTEGER;
    name actor.name%TYPE;
CURSOR c_actor IS
    select *
    from (select actor.name AS name, count(movie.title) AS total
        from actor, movie, casting
        where movie.id = casting.movie_id
        and actor.id = casting.actor_id
        and movie.yr >= 2000 and movie.yr <=2013
        group by actor.name
        order by count(movie.title) DESC)
    where rownum <= 10;
BEGIN
for v_actor in c_actor
LOOP
    for t in 2000 .. 2009
    LOOP
    select name, total
    into name, total
    from actor, movie
    where movie.yr between t and t+4
    and actor_id = v_actor.actor_id
    and total >= 8
    group by name;
       dbms_output.put_line(name||' played in '||total||' movies between '||t||' and '||t+4);
   END LOOP;
END LOOP;
END;

Answer: It seems you overcomplicated it. This should work:
begin
  for v_actor in (select a.name, count(*) total
                  from actor a join casting c on a.id = c.actor_id
                  join movie m on m.id = c.movie_id
                  where m.yr between 2000 and 2013
                  group by a.name
                  having count(*) >= 8
                 )
  loop
    dbms_output.put_line(v_actor.name ||' acted ' || v_actor.total ||' times');
  end loop;
end;

I think you created a question a couple of hours before (and deleted it), making same mistakes. For example: you created a variable named total, and - at the same time - have it in cursor's select statement. You want to display value fetched by the cursor, not the variable itself, unless cursor fetches into that variable - but that's done when you explicitly open/fetch from the cursor, not within the cursor FOR loop. With it, you use a cursor variable and use it to display those values.
Comment: Thank you for responding, i'm supposed to create a for loop (t in 2000 .. 2009) inside the cursor for loop (v_actor in c_actor)
Answer: you dont get actor_id in your cursor query.
select *
    from
   (
    select a.name AS name, count(m.title) AS total
      from actor a
      join casting c
        on a.id = c.actor_id
      join movie m
        on m.id = c.movie_id
     where m.yr >= 2000
       and m.yr <=2013
     group by actor.name
     order by count(movie.title) desc
   )
   where rownum <= 10;

PLSQL Cursor For Loop


How do I wire a Fishman soundhole pickup with the pickup in the soundhole and a vol (+ tone maybe) control on the guitar?

Question: Fishman Blackstack Soundhole Pick Up - Double Stacked Humbucker
I have contacted Fishman to ask what vol pot and or tone pot I would use with this humbucker. I want to mount the pots on the guitar, and they said that any humbucker circuit would do and probably a 500k pot. (Actually it depends somewhat on the impedances of the pickup coils, but Fishman sent me a Seymour Duncan diagram!)
I found a circuit for a Fishman Neo-D single coil which showed a 20K pot volume but Fishman advised to use a 250k pot!
So which equipment do I need, and, more importantly, how do I wire it?
Comment: I'm confused about this question. Fishman told you to use a 500k Ohm pot for your Fishman pickup, right? If so, how does that not answer your question?
Comment: @Aaron yes, but it seems Fishman provided also a wiring diagram to the OP, so it's unclear what else is there to answer.
Comment: Hi Kevin. Welcome to the site. I've taken the liberty of rewriting your question to conform to site rules. Asking how to accomplish a task is encouraged, but requests for resources are considered off topic. If you feel I've misrepresented your intentions, please let me know, and I'll remove my changes. (You may also do so yourself by click on the "edited (time) ago" link and then clicking the "rollback" link.)
Comment: @ToddWilcox I think this is my fault when I edited the question. I believe the underlying issue is how to do the wiring. I've re-edited, but you might double-check me by looking at the question as originally written.
Answer: I have wired a few acoustic guitars for pickups over the years, probably in search of my own Beatles J160E setup.
I would recommend the 250K pots to you.
Either that, or mount the Fishman Blackstack as is is designed to be mounted (without volume and tone controls), and adjust your tone on the amp or mixer.
For volume control, there are many quality volume pedals.
I recommend the Ernie Ball JPJR Volume Pedal with built in (easy to see) tuner onboard.
Great item.
Good luck with this project!
Comment: It should be noted that a volume pedal should also use a 250kΩ (or other in similar range) pot, rather than 25kΩ.
Comment: I may have erred in editing the original question. I believe the core issue was the wiring. I've edited the question to reflect. FYI in case that changes your answer.
Answer: Pickup and pot essentially form a sort of low pass filter. The higher the resistance is on the pot the higher the cut point will be (as the increased resistance of the coil at higher frequency is less significant).
So generally you'll have that a higher resistance on the pots will result in more overtones being preserved in your signal, while a lower resistance pot will sound "warmer" by taking way such overtones.
Some things to keep in mind: Humbuckers do cause high frequency loss by themselves, so often they are paired with higher resistance potentiometers. As acoustic guitar will necessarily have some dampening on the strings, which affects high frequencies more than low frequencies. So you should expect less high frequency output in the first place.
Also if you add a tone pot circuit you are increasing this high frequency loss. With tone and volume pot each 500kΩ at "pass through" this will thus look like 500kΩ + 500kΩ in parallel to ground, which results in a resistance of 1 / (1/500 + 1/500) kΩ = 500/2 kΩ = 250kΩ. Thus if you plan to use a volume + tone circuit it is reasonable to use twice the resistance you'd go for else.
Also the tone pot will allow you to add a low pass at your liking, so you might want to go for brighter to have the option.
So it makes sense that the single coil diagram as 250kΩ, while for the humbucker you might use 500kΩ. When adding tone you might even think about getting 1000kΩ (or 1 MΩ), especially if the pickup is already rather dark on the acoustic guitar.
If you want to you can test this out during the installation: Simply get yourself a pair of resistors at 250kΩ, 500kΩ and 1MΩ (these are very cheap, also you can probably ask any electronics repair workshop for some spare resistors (if not you can also just buy 250kΩ resistors and put them in series to get the higher values. Or just buy 1MΩ and put them in parallel to get lower values. Or whatever). Then bridge two resistors to ground (maybe add a capacitor for one to make it really realistic, if you leave out the capacitor you could also just use single resistors at 125kΩ, 250kΩ, 500kΩ). This should then simulate the behaviour with both pots turned all the way up without having to buy multiple more expensive capacitors. If this sounds too bright or harsh for you, go for a lower resistance, if it is too dark go higher.
Now: What do you need, and how do you wire it? You need the pickup. I'm assuming you know which cable of your pickup is hot and which is ground. You need two pots, probably 500kΩ, maybe also 1MΩ, depending on whether you like the sound. Make sure these pots scales logarithmically and not linearly, because else you'd get the most action in the lowest portion of the pot (our hearing is not linear!). Get a small capacitor of a size of your liking (10-22nF, the higher the capacity the lower the cut frequency, so more treble cut). In fact, get multiple capacitors, then you can try some options. You need a socket. And you need wire. If you get wire in two colors you can color code ground and hot phase.
The socket has two connectors, one that goes to the tip and one that goes to the shaft of the jack. The shaft will be ground!
So first thing: The ground of the socket should be connected to the ground of the pickup, the case of each potentiometer and the third pin of the volume potentiometer. The second pin of the tone pot should be connected to ground through the capacitor.
The hot cable of the pickup should be connected in parallel to the first pin of both volume and tone pot. The second pin of the volume pot should be connected to the tip connector of the socket.
This is something like the usual way of how to wire these things, but there are alternatives.
You will also need to think about where you are going to mount the socket and the pots. This should be done in a place you can reach through the soundhole, and if you have potentiometers in a place you can reach well. You will need a drill for installing these. Assemble the circuit outside of the guitar and then try to install everything through the soundhole.
Comment: Thanks for this very comprehensive and informative answer - giving an insight into why both Fishman and Baggs like their pickups to go straight through to the external preamp - Im modifying a new Martin SC13e and being the animal i am i have fitted it with a ToneWoodAmp. Yesterday that was, a very anxious business but the sound is amazing being a mix of the straight acoustic tone of the guitar (quite loud as its a Martin) and the TWA output, both sounds coming through the soundhole and the rest of the guitar body and the mix varied by the piezo volume of the built in preamp. Thanks once again
Comment: @Kevin Nice! Btw the sound does not really come from the sound hole but mostly from the top. The top can be seen as a membrane, transferring vibrations to the air. That's the reason by semi-acoustics with plywood tops offer significantly less sound than one with a good fir or cedar top.


Use same struct on all files from a project

Question: I use an instance of a struct in all the files of my project by declaring it within each of the header files.
My question is: is there an easier/automatic method of doing it?
well here is an example:
well, i have a project called: my_project
that contains: main.c func1.c func2.c func3.c.
on main file i read txt file and save the data on struct vector:
for(i=0;i<MAX;i++){
  fscanf(f,"%s",&s[i].nome);
  fscanf(f,"%d",&s[i].id);
  fscanf(f,"%d",&s[i].quantidade);
  fscanf(f,"%d",&s[i].lim_min);
  fscanf(f,"%f",&s[i].consumo_med);
}

and what i want is use the struct vector in func2.c and func3.c
ehst is the best way to do it?
Comment: Please edit your question with this code. Very difficult to read in the comments.
Comment: You'll have to add more details about what you're doing.
Comment: Does my edit say what you wanted to say?
Comment: well, i have a project called: my_project that contains: main.c func1.c func2.c func3.c.
on main file i read txt file and save the data on struct vector:
for(i=0;i<MAX;i++){

  fscanf(f,"%s",&s[i].nome);
  fscanf(f,"%d",&s[i].id);
         fscanf(f,"%d",&s[i].quantidade);
  fscanf(f,"%d",&s[i].lim_min);
  fscanf(f,"%f",&s[i].consumo_med);

 }
and what i want is use the vector in func2.c and func3.c
Comment: well i hope i made myself clear after editing the question.
Answer: You can define struct vector in a header, perhaps called vector.h, and then include vector.h in each of your source files (or in a header that is already included in each of your source files). This is a common way to do it. This has the benefit that the text defining struct vector appears in only one place, vector.h (which avoids errors that occur when the definition is edited in one source file but not another). And it is essentially the only way to do it, since C does not provide any way to import definitions other than #include.
Answer: I assume you have function declarations in your funcXYZ.c files which you're including in main.c? You might just code your functions to take an appropriate struct as an argument, then use those functions with the struct you've created in main.
If for whatever reason you've got things the other way around, i.e. you're including main.c in funcXYZ.c, then you might use an extern.


Using SonarQube and an alternate IP addresses on Windows gets a bind error

Question: I have a sonarqube 5.1.2 server that is working OK when bound to the primary IP address on my Windows server.
However, I want to bind sonarqube to an alternate IP address on a Windows server and get a problem (or all IP addresses on the server)
In the sonar.properties I have set the alternate address

sonar.web.host=10.10.9.51

This fails with the error

2015.08.18 15:13:06 ERROR web[o.a.c.h.Http11NioProtocol] Failed to initialize end point associated with ProtocolHandler
  ["http-nio-10.10.9.51-9000"] java.net.BindException: Cannot assign
  requested address: bind

If I set the value to my primary IP address the server works.
If I don't set the value, or use 0.0.0.0, the primary IP address works but
the alternate does not.

I assume I am missing some other configuration file that allow binding to any secondary IP addresses on my server.
Any ideas where it might be set?
A clarification

10.10.1.93 is the PCs default IP address.  Sonarqube binds to this OK if use the sonar.web.host=10.10.1.93 or sonar.web.host=0.0.0.0 or
just don't set sonar.web.host.
10.10.9.51 is an secondary IP address on the server, which is bound OK and I can ping it. However if I set sonar.web.host=10.10.9.51 I get the error shown above
Comment: you say you set sonar.web.host to 10.10.1.93, but error log states it tries and fails to bind to 10.10.9.51. What's 10.10.9.51? quick googling, maybe [this thead](http://stackoverflow.com/questions/8965155/cannot-assign-requested-address-jvm-bind) could help you troobleshoot
Comment: Sorry I should have been clearer 10.10.1.93 is the PCs default IP address. sonarqube binds to this OK if use the sonar.web.host=10.10.1.93 or sonar.web.host=0.0.0.0 or just don't set sonar.web.host. 10.10.9.51 is an secondary IP address on the server, which is bound OK and I can ping it. However if I set sonar.web.host=10.10.9.51 I get the error shown
Comment: pinging 10.10.9.51 doesn't prove port 9000 is open on this IP. Maybe you should check your firewall configuration.
Comment: I tried disabling the firewall fully, had no effect. But this is as expected as it  the connection is within the OS not the via a network connections
Comment: I installed the IIS feature on WIndows and it has the same issue, only sees the primary IP address not the alternates. So looks to be an OS issue. I will keep digging
Answer: Found the issue, the secondary IP address I was trying to use had been used on another machine in the network. Hence the ping worked.
Windows let me assign the IP address as secondary IP address on an adapter, but it never it seems actually bound due to it already being in use. When I checked the Windows System event I did find an error
The system detected an address conflict for IP address 10.10.9.51 with the system having network hardware address 00-15-5D-01-3E-02. Network operations on this system may be disrupted as a result.
Note I did not get the 'IP address conflict' dialog I would have seen if there are a clash on the primary IP address
Once I used an unused IP address, it bound OK for both IIS and the Apache/SonarQube stack.


Scope of Oracle transactions when used from ADO.NET and involving triggers?

Question: I am told by someone that when calling Oracle from ADO.net, when calling multiple inserts in a loop, where each insert causes a trigger to fire that includes within it's PL-Sql a Commit statement, that it is impossible to stop that commit from actually commiting the transaction.
i.e., I want my ADO.Net code to begin a transaction before the loop starts, and, when the loop exits, only commit all the inserts if and only if every insert in the loop was successful.  My source is telling me that the way Oracle works, if these triggers include COmmit statements, then this is impossible..
As this seems to be an very common requirement, and I know it is possible in SQL Server, this does not seem right to me.
Is this correct?
Comment: wait, What, exactly, is possible in SQL Server? Autonomous Txns? Committing in triggers?
Comment: In SQL Server,  every Begin Transaction increments a counter, which can be accessed using a built-in transaction scoped variable called @@TranCount.  Then Every Commit Transactiopn statement decrements it, and the DB only actually commits when @TranCount = 0...
Comment: From SQL Server Docs:
The BEGIN TRANSACTION statement increments @@TRANCOUNT by 1. ROLLBACK TRANSACTION decrements @@TRANCOUNT to 0, except for ROLLBACK TRANSACTION savepoint_name, which does not affect @@TRANCOUNT. COMMIT TRANSACTION or COMMIT WORK decrement @@TRANCOUNT by 1.
Answer: Your informant is wrong, if he is talking about Oracle database triggers:
1) You cannot put a COMMIT in an Oracle trigger that is not autonomous:
<code>SQL> create trigger this_wont_work
  2  after insert on emp
  3  begin
  4    commit;
  5  end;
  6  /

Trigger created.

SQL> insert into emp (empno) values (123)
  2  /
insert into emp (empno) values (123)
            *
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at "TONY.THIS_WONT_WORK", line 2
ORA-04088: error during execution of trigger 'TONY.THIS_WONT_WORK'
</code>
2) If the trigger is autonomous (i.e. has PRAGMA AUTONOMOUS_TRANSACTION in its declaration section) then it can only commit any changes it (the trigger) makes.
There is no danger whatsoever of a trigger committing work you did outside of that trigger.
Note: the use of autonomous transactions in triggers is dangerous except for certain cases, because actions performed by the autonomous trigger will be committed even if the triggering statement is rolled back.  This can easily lead to data corruption if mis-used.
Comment: Yes, I discovered that.  So again, what I want to do, is inhibit the trigger commit until my ADO.Net Client code externally tells the database to commit.  Then I want the database to commit all pending ops since I began the transaction at the beginning of the loop, including all trigger operatiuons
Comment: Charles, what you want is exactly what will happen, unless the triggers are autonomous.  If they are autonomous, then you have no control over when they are committed, and there's presumably a reason somebody did it that way.
Comment: So does your trigger include a COMMIT and a PRAGMA AUTONOMOUS_TRANSACTION?  If so, why since you don't want it to?!
Comment: You can't stop or delay an autonomous transaction... it is, after all, autonomous. It's meant to happen regardless of the calling txn.
Comment: Tony, I'd edit this if I could but you don't mean Oracle Database Triggers, you mean TABLE triggers. I think Database triggers can include commit.
Comment: Tony, on further thought, his source may actually be saying the same as you:  IF the triggers contain COMMITs, THEN they must be autonomous, and THEREFORE they are independent of his transaction.  The question becomes, is this the correct business logic?  If not, why were they implemented this way?
Comment: @Mark:  All triggers are "database triggers".  Per documentation:  "Use the CREATE TRIGGER statement to create and enable a database trigger".  DDL and event triggers can be ON DATABASE, which I think is what you are referring to.  These would be "database DDL" or "database event" triggers.
Comment: I'm not referring to the denotation, but to the connotation. "Database Trigger" is Connoted to mean DDL and Event triggers. The answer is more clear with the change not withstanding an entry in documentation.
Comment: What sticks out in this thread for me is Dave Costas comment that "IF the triggers contain COMMITs, THEN they must be autonomous.."  if this is so, then I'm screwed, unless I can change the code in these triggers... and to answer another question, there is NO reason for Commits to be in there!
Comment: Yes, I'm afraid that if you can't change those triggers then they will autonomously commit their own work, as their developer specifically designed them to do.  If this is incorrect then the triggers have a bug and must be fixed!
Comment: ...   I know that inexperienced developers often throw an autonomous transaction into their triggers because it magically "solves" a "table is mutating" error - but only at the expense of unwanted and usually data-corrupting behaviour.


Host a PHP website a Amazon webservice EC2

Question: How i can host my php website at EC2. I have brand new account at amazon web serive. Some one let me know about the setup of configure this.
Thanks,
Pradeep
Comment: should be a serverfault question. You may try Google, (many) answers is already there.
Answer: As Dan mentioned, there is no difference between a server on Amazon EC2 and any other server. I suppose you are looking for a way to get started.
Start from this article - How To: Getting Started with Amazon EC2
You'll now have a running server with root access. You can now do a default server installation. For example, assuming you'll be installing Ubuntu, read this article.
Search google for any specific problems or features (such as need for static IP) and if everything else fails, ask here.
Hope this helps you to get started.
Answer: There is no difference between hosting a site on EC2 and hosting one on a server anywhere else. Install Apache and PHP. On a CentOS server (there are many CentOS images in the AMI library), "yum install httpd", "yum install php", set up your virtual host and upload your site. That's it.


constant y, how much X is meaningful

Question: This is a repeated measure analysis. The dependent variable is a binary Tuberculosis (TB), Yes/No. I have several independent variables(X) like age, BMI, number of family members, income and others, mix of continuous and discrete.
Once the patient develops TB (Y=1), there is no going back. The patient has reached the final absorbing state. My question is, does collecting more observations, independent variables(X) like age, BMI, number of family members, income and others, matter after the patient has reached the final stage, TB=Yes (Y=1), while analyzing the association between Y and X ? Thanks in advance.
Comment: What exactly is your data? Could you describe it in greater detail? You have data collected over time for patients and want to predict when the particular patient would develop the disease?
Comment: @Tim, binary Y,  continuous or discrete X.
Answer: So this is regression with a categorical dependent variable, or binary logistic regression. We want to know how changes in X are associated with the probability of Y. For example, we want to know how changes in age (X) are related to the probability of developing TB (Y). Thus, any observations made after data collected to examine the relationship between age (X) and TB (Y), BMI (X) and TB (Y), income (X) and TB (Y) (etc.) changes the intent of the initial research question. Rather, conceptually we are now looking at how changes in X after developing TB (or not developing TB), contribute to the probability of Y (TB health).
Beyond this, Bayesian approaches allow us to update the regression model with new data (bayesian prior), however I don't think this is applicable here.
Comment: you are absolutely right.  I realized the mistake in my thinking. Thanks.

constant y, how much X is meaningful


Why does java complain about raw types in my variable declaration?

Question: public class Table<Key extends Comparable<Key>, Value> {

/*
* The purpose of entry is to glue together a key and a value
*
* The class that we use for Key has to implement comparable
* */
private class Entry<Key extends Comparable<Key>, Value> implements Comparable<Entry>
{
    Key key;
    Value value;

    public Entry(Key k, Value v)
    {
        key = k;
        value = v;
    }

    public int compareTo(Entry<Key,Value> entry)
    {
        return key.compareTo(entry.key);
    }
}

private BST<Table.Entry<Key, Value>> tree = new BST<Table.Entry<Key, Value>>();

//must supply public methods for the three operations

public Value lookUp(Key key)
{
    Entry<Key, Value> e = new Entry<Key, Value>(key, null);

    return tree.search(e).value;
}

public boolean insert(Key k, Value v)
{
    return tree.insert(new Entry<Key, Value>(k, v));
}

public boolean delete(Key k)
{
    //we haven't written a delete method for bst yet.
    return tree.delete(new Entry(k, null));
}
}

The above is a class declaration for a table abstract data type that my professor was going over in class. I've been trying to figure out why does Java give me the following error message

Type arguments given on raw type

When I declare my variable here
private BST<Table.Entry<Key, Value>> tree = new BST<Table.Entry<Key, Value>>();

What are raw types in java? We've discussed writing generic classes. Is it related to that?
Comment: It would be a lot easier to read this if you followed the convention of giving type parameters 1-character names (`K`, `V`).  Without that it's difficult to spot where you're referencing a real class and where you're using a parameter.
Comment: You haven't shown us what actually matters: the definition of the class `BST`.
Comment: @MarkPeters: Great! Bring back single-character identifiers - just what we need to improve code readability.
Comment: @AdrianPronk: There is no "bring back."  Whether you agree with it or not, it's already the extremely well established [Java convention](http://docs.oracle.com/javase/tutorial/java/generics/types.html).  Following conventions enhances readability in this case over using a descriptive name (which appears to suggest that it's not a type parameter but rather a class name).
Answer: Your table class requires generic parameters, but you are referencing it as a raw type here:

private BST
 tree = new BST
();

You need to supply generic parameters for it, as so:
private BST<Table<Key, Value>.Entry<Key, Value>> tree =
    new BST<Table<Key, Value>.Entry<Key, Value>>();

And as others have pointed out, its standard to define generic parameters as one letter characters, so K instead of Key, and V instead of Value. It makes it substantially easier to read and understand your code, and helps avoid confusion with real type names.
Comment: Thanks. That worked. But I still don't really understand why you have to do it that way? Why do I specifically have to call Table.Entry and not just use Entry? Shouldn't anything that is in Entry be available to table since Entry is an inner class of Table?
Comment: @j.jerrod.taylor - Absolutely. You can actually remove the `Table` portion entirely, all its doing is providing scope thats not needed.
Answer: Entry is a raw type, while Entry<Key, Value> is not. o, in your code, the snippet :
public boolean delete(Key k)
{
    //we haven't written a delete method for bst yet.
    return tree.delete(new Entry(k, null));
}

is including a raw type.
Comment: You know, you can flag the question as duplicated instead of giving a very simple explanation contrasted by the answer in the possible duplicated link.


Doubt in the Proof of the Theorem on the Undecidability of First-Order Logic

Question: I am studying Ebbinghauss's book Mathematical Logic and I wanted your help in checking that a given condition that the author says it holds really holds. The theorem is about undecidability of first-order logic.
The theorem is:

4.1 Theorem on the Undecidability of First Order Language The set
  $\{ \phi \in L_{0}^{S_{\infty}} \ | \vDash  \phi \} $ of valid $S_{\infty}$-sentences is not $R$-decidable.

Proof (only the relevant parts for the condition I am trying to check):

We work with the alphabet $\mathcal{A} = \{ | \}$ and we consider $\square$ the empty word.
Let $P$ be a program with instructions $\alpha_0, \ldots, \alpha_k$. We say that $(L, m_0, \ldots, m_n)$ is the configuration of P after $s$ steps if $P$, started with $\square$, runs for at least $s$ steps and after this $s$ steps, instruction $L$ is to be executed next, with the numbers $m_0, \ldots, m_n$ in the registers $R_0, \ldots, R_n$. In particular, $(0, 0, \ldots, 0)$ is the initial configuration of $P$.
Choose symbols $R$ (($n$ + 3)-ary), $<$ (binary), $f$ (unary), and $c \in S_{\infty}$ and set $S = \{R, <, f, c\}$. To each program $P$, we associate an $S$-structure $\mathcal{A}_p$ according to whether $P$ halts or not:

Case P doesn't halt, i.e., $P: \square \to \infty$. Set $A_{P} = \mathbb{N}$, and interpret $<$ by the usual ordering on $\mathbb{N}$, $c$ by 0, $R$ by $\{(s, L, m_0, \ldots, m_n) \ | \ (L, m_0, \ldots, m_n) \text{ is the configuration of $P$ after $s$ steps}\}$ and $f$ by the successor function.
Case P halts, i.e., $P: \square \to \text{halt}$. Let $s_P$ be the number of steps carried out by $P$ until it arrives at the halt instruction. Set $e = \text{max}\{k, s_P\}$ and $A_{p} = \{0, \ldots, e\}$ and interpret $<$ by the usual ordering on $A_{p}$ and $c$ by 0.

Next the author provides an $S$-sentence $\psi_P$ that will describe, in a suitable way, the operations of $P$ on $\square$. In reading $\psi_{P}$ I am trying to check that the following holds:

(a) - $\mathcal{A_P} \vDash \psi_P$
(b) - If $\mathcal{A}$ is an $S$-structure with $\mathcal{A} \vDash \psi_P$ and $(L, m_0, \ldots, m_n)$ is the configuration of $P$ after $s$ steps, then the elements $0^\mathcal{A}, 1^\mathcal{A}, \ldots,  s^\mathcal{A}$ are pairwise distinct and $\mathcal{A} \vDash RsLm_0,\ldots, m_n$

where we set $\psi_P$ to be:

$\psi_P = \psi_0 \land R0,\ldots,0 \land \psi_{\alpha_0} \land \ldots \land \psi_{\alpha_{k-1}}$
The sentence $\psi_0$ says that $<$ is an ordering whose first element is $c$, that $x < fx$ holds for every $x$ and that $fx$ is the immediate successor of $x$ in case $x$ is not the last element:

$\psi_0 = \ $ " $<$ is an ordering" $\land \forall x (c < x \lor c \equiv x) \land \forall x (x < f x \lor x \equiv fx) \land \forall x(\exists y \ x < y \to (x < fx \land \forall z (x < z \to (fx < z \ \lor fx \equiv z))))$

For $\alpha = \alpha_0, \ldots, \alpha_{k-1}$, the sentence $\psi_{\alpha}$ describes the operation corresponding to instruction $\alpha$. $\psi_{\alpha}$ is defined as follows:
If $\alpha$ is an add instruction, say $L \text{ LET } R_i = R_i + \{ | \}$:

$\psi_{\alpha} = \forall x \forall y_0 \ldots \forall y_n(R x L y_0 \ldots y_n \to (x < fx \land R fx L+1 y_0 \ldots y_{i-1} fy_i y_{i+1} \ldots y_n)) $

If $\alpha$ is the instruction $L \text{ LET } R_i = R_i - \{ | \}$:

$\psi_{\alpha} = \forall x \forall y_0 \ldots \forall y_n(R x L y_0 \ldots y_n \to  (x < fx \land ((y_i \equiv 0 \land R fx L+1 y_0 \ldots y_n) \lor \\ \hspace{15mm} (\lnot y_i \equiv 0 \land \exists u (f u \equiv y_i \land R fx L+1 y_0 \ldots y_{i-1} u y_{i+1} \ldots y_{n})))))$

If $\alpha$ is the instruction $L \text{ IF } R_i = \square \text{ THEN } L' \text{ ELSE } L_0$:

$\psi_{\alpha} = \forall x \forall y_0 \ldots \forall y_n(R x L y_0 \ldots y_n \to  (x < fx \land ((y_i \equiv 0 \land R fx L' y_0 \ldots y_n) \lor \\ \hspace{15mm} (\lnot y_i \equiv 0 \land R fx L_0 y_0 \ldots y_n))))$

Finally for $\alpha = L \text{ PRINT }$ let:

$\psi_{\alpha} = \forall x \forall y_0 \ldots \forall y_n(R x L y_0 \ldots y_n \to  (x < fx \ \land \ R fx L+1 y_0 \ldots y_n))$
Answer: 2.a. $\mathcal{A_P} \vDash \psi_P$
Notice that $\mathcal{A_P} \vDash \psi_0$, in both cases. This is because, as commented, $\psi_0$ says that $<$ is an ordering whose first element is $c$ (indeed, we interpret $<$ by the usual ordering - whether we are in $\mathbb{N}$ or in $A_P$ - and we interpret $c$ as 0), that $x \le fx$ holds for every $x$ and that every $fx$ is the immediate successor of $x$ in case $x$ is not the last element (this holds when we interpret $fx$ as the successor of $x$ and this also holds when $P$ halts and $x$ is equal to $e$ - in this case we have $x = fx$).
Notice that $\mathcal{A_P} \vDash R0\ldots0$. That's because $(0, \ldots, 0)$ is the configuration of $P$ after 0 steps and, therefore, $(0, \ldots, 0) \in R^{A_P}$.
Finally, for the sentences that describe the operation corresponding to instruction $\alpha$. Notice that the formula $\psi_{\alpha}$, when interpreted under $\mathcal{A_P}$, corresponds precisely to instruction $\alpha$ and we will have $\mathcal{A_P} \vDash \psi_{\alpha}$ in any of the cases below:

If $\alpha$ is an add instruction, $\psi_{\alpha}$ says (when interpreted under $\mathcal{A_p}$) that if you are in the configuration $(L, y_0, \ldots, y_n)$ after $x$ steps, then we are not in the last instruction and after $x+1$ steps we are now in the configuration $(L+1, y_0, \ldots, y_{i-1}, fy_i, y_{i+1}, \ldots, y_n)$. Therefore, in this case, $\mathcal{A_P} \vDash \psi_{\alpha}$.
If $\alpha$ is the instruction $L \text{ LET } R_i = R_i - |$,  $\psi_{\alpha}$ says (when interpreted under $\mathcal{A_P}$) that if you are in the configuration $(L, y_0, \ldots, y_n)$ after $x$ steps, then we are not in the last instruction(i.e. $x \le fx$) and we have either:

register $y_i$ is empty and in this case after step $x+1$ we are in configuration $(L+1, y_0, \ldots, y_n)$ - the values on all the registers are the same in relation to the previous configuration.

or register $y_i$ is not empty and in this case, there exists some
element $u$, which is the antecessor of $y_i$ such that after $x+1$
steps we are in configuration $(L+1, y_0, \ldots, y_{i-1}, u,
y_{i+1} \ldots y_{n})$.
Therefore, in any case, $\mathcal{A_P} \vDash \psi_{\alpha}$.

If $\alpha$ is the instruction $L \text{ IF } R_{i} = \square \text{ THEN } L' \text{ ELSE } L_{0}$, then $\mathcal{A_P}$ interprets $\psi_{\alpha}$ as saying that if you are in the configuration $(L, y_0, \ldots, y_n)$ after $x$ steps, then you are not in the last instruction (i.e. $x \le fx$) and:

There is the empty word in register $R_i$ and after $x+1$ steps we are in configuration $(L', y_0, \ldots, y_n)$.
or the word in register $R_i$ is not empty and after $x+1$ steps we are in configuration $(L_0, y_0, \ldots, y_n)$.

If $\alpha$ is a print instruction, $\psi_{\alpha}$ says (when interpreted under $\mathcal{A_p}$) that if you are in the configuration $(L, y_0, \ldots, y_n)$ after $x$ steps, then we are not in the last instruction and after $x+1$ steps we are now in the configuration $(L+1, y_0, \ldots, y_n)$.

This concludes the proof of item 2.a.
2.b. If $\mathcal{A}$ is an $S$-structure with $\mathcal{A} \vDash \psi_P$ and $(L, m_0, \ldots, m_n)$ is the configuration of $P$ after $s$ steps, then the elements $0^\mathcal{A}, 1^\mathcal{A}, \ldots,  s^\mathcal{A}$ are pairwise distinct and $\mathcal{A} \vDash RsLm_0,\ldots, m_n$
Following the book suggestion, we prove by induction on $s$.
For $s = 0$, there is only the element 0 (so all the elements are pairwise distinct) and $(0, 0, \ldots, 0)$ is the configuration of $P$ after 0 steps. Since $\mathcal{A} \vDash \psi_{P}$ we also have $\mathcal{A} \vDash R 0 \ldots 0$.
For $s+1$, let $(L, m_0, \ldots, m_n)$ be the configuration of $P$ after $s$ steps. By inductive hypothesis, we have $\mathcal{A} \vDash R s L m_0, \ldots, m_n$ and we must prove $\mathcal{A} \vDash R s+1 L' m'_0, \ldots m'_n$ where $(L', m'_0, \ldots, m'_n)$ is the configuration of $P$ after $s+1$ steps. We must also prove that $0, \ldots, s+1$ are pairwise distinct.
Let's start by proving that $0, \ldots, s+1$ are pairwise distinct. We do that by proving that $0 < \ldots < s+1$ and this require us to strengthen the induction hypothesis slightly. Notice that $\mathcal{A} \vDash \psi_{\alpha}$. Then, for every instruction at label $L$ we atribute to variable $x$ the value $s$ and we attribute to the variables $y_0, \ldots, y_n$ the values $m_0, \ldots, m_n$. Then, in all of the cases, we can use that $\mathcal{A} \vDash R s L m_0 \ldots m_n$ (this holds by inductive hypothesis) to conclude that $s < fs \equiv s+1$. This, together with the fact that $0 < \ldots < s$ (this is our strengthened inductive hypothesis and can be verified to hold in the base case) lets us conclude that $0 < \ldots < s+1$. Therefore, we conclude that $0, \ldots, s+1$ are pairwise distinct.
Let's prove that $\mathcal{A} \vDash R s+1 L' m'_0, \ldots m'_n$. Notice  that $\mathcal{A} \vDash \psi_{\alpha}$. Then, by instantiating variables $x$ and $y_0, \ldots, y_n$ as described in the preceding paragraph, and using the fact that $\mathcal{A} \vDash R s L m_0 \ldots m_n$ (this holds by inductive hypothesis) we conclude (examine the structure of the formula $\psi_{\alpha}$ for every instruction - add, subs, jump and print) that $\mathcal{A} \vDash R s+1 L' m'_0, \ldots m'_n$ where $(L', m'_0, \ldots, m'_n)$ is precisely the configuration of $P$ after $s+1$ steps.


What are examples of statistical experiments that allow the calculation of the golden ratio?

Question: There are some very simple experiences that can be done by a kid at home, whose result allows one to statistically approach famous numbers such as $\pi$ or $e$.
An example where $\pi$ shows up is perhaps the most famous one of its kind. In Buffon's needle problem, we draw strips on the floor and drop a needle. The probability that the needle will lie across a line between two strips involves $\pi$. Repeating the process many times allows us to approach $\pi$ with accuracy, were we willing to repeat the experience a sufficient amount of times.
An example where $e$ appears consists in drawing a random sample of size $n$ with replacement from a population of size $n$. The probability of a member of the population not being chosen is $p=(1-1/n)^n$. If $n \to \infty$ then $p \to 1/e$.
My question is, what are examples of experiments that would allow one to statistically approach the value of the golden ratio $\Phi = (1+\sqrt{5})/2 = 1.618033...$? Or in other words, how to approach $\Phi$ by Monte Carlo simulation.
(A condition is that the experience cannot be finely tuned to obtain the result. For example, if we draw a contour on the floor and divide it into two parts using somehow the golden ratio and then we randomly throw stones at it, we can obviously recover the golden ratio by counting the number of stones that landed in each part. I ask for examples in which the result arises in a more unexpected manner.)
Comment: @Aksakal That is a very strange remark, because the Golden Ratio *is* a number, [known since antiquity](https://en.wikipedia.org/wiki/Golden_ratio).  Is there perhaps some alternative meaning of "golden ratio" to which you are referring?
Comment: For estimating $e,$ see our thread at https://stats.stackexchange.com/questions/193990/.  For estimating *any* quadratic, notice that quantiles of a triangular distribution are quadratics. The method (easily and fairly efficiently) generalizes to estimating any real algebraic number.
Comment: @whuber: Perhaps you should post a question-and-answer on how to estimate "any real algebraic number" by Monte Carlo methods.  Quadratics are simple with my [algorithm for continued fractions](https://peteroupc.github.io/bernoulli.html#Continued_Fractions), but arbitrary algebraics might be a different matter.
Comment: @Peter That's not a suitable generalization.  Any distribution with a pdf $f$ that is a polynomial function on some interval has a cdf $F$ that is a polynomial function of one degree higher. Thus quantiles of $F$ (within a suitable range) are obtained by inverting this polynomial function: that is, by finding roots. One can simulate from $F$ by rejection based on $f,$ which does not require root finding.
Comment: There's nothing Golden about this ratio. It doesn't appear in any physical phenomena of importance, and even in arts is just a made up notion that it represents harmony. It doesn't. Only a tiny part of western art mythologized this trivial ratio.
Comment: @whuber: Perhaps this is because I don't see how quantiles of a triangular distribution lead to a method to estimate any "real algebraic number", without directly calculating those quantiles.
Comment: @whuber:Then perhaps what you were suggesting is to take a fixed-size sample from $F$ (such as a triangular distribution) and compute a quantile on the sample to estimate a quadratic number (since the triangular CDF is quadratic).  See your answer's second algorithm.  I was expecting something more like a _sequential estimator_ of a real number, that takes fair coin flips and has a randomized stopping time, but doesn't directly compute the number; see [another question](https://stats.stackexchange.com/questions/249364).
Comment: because golden ratio is not a constant itself, it is not interesting to think about it in this way.
Comment: I am surprised that nobody shared ViHart's videos on this. [link](https://www.youtube.com/watch?v=ahXIMUkSXX0), [link](https://www.youtube.com/watch?v=lOIP_Z_-0Hs), [link](https://www.youtube.com/watch?v=14-NdQwKz9w).
Comment: @whuber, I meant that it's an expression over other uninteresting numbers like square root of 5. it's not the fundamental constant like $\pi$
Comment: @Aksakal $\pi$ is often defined as the area of a unit disk.  But in which geometry? With $L^p$ metrics one obtains different values of $\pi$--so in just what sense is $\pi$ "constant"?!
Comment: $\pi$ is a physical constants, e.g. it shows up in heisenberg uncertainty principle alongside with Planck constant. Are you trolling?
Comment: @Aksakal Heisenberg's uncertainty principle reads $\Delta x \Delta p \geq \frac{1}{2}\hbar$. You can write it also differently with $\Delta x \Delta p \geq \frac{1}{4\pi}h$ but that doesn't make the *mathematical* constant $\pi$ a *physical* constant.
Comment: @Aksakal π appears in quantum mechanics because its wave-based description of particles and oscillatory phenomena implies periodicity. Thus, Whuber's answer still applies. When you say about $\phi$ that "It doesn't appear in any physical phenomena of importance, and even in arts is just a made up notion that it represents harmony", why do you assume that we don't know that already?
Comment: @Aksakal No trolling intended. Because your initial comments view $\varphi$ as one of a set of related numbers (although *which* set evidently is not an objective matter), it seemed worthwhile pointing out that $\pi$ itself can likewise be viewed as one of a set of *naturally* related numbers.  The point is that "constant" is not an objective term here.  Also, elsewhere in this thread I have pointed out $\varphi$ occupies a *unique* place in number theory. Wouldn't that fact be more relevant to this discussion than the meaning of any physical quantity?
Comment: @SextusEmpiricus, I knew someone would bring up the units of measure, like S.I. vs SGS. the point is that as long as you're in Euclidian world, some constant like $\pi$ will keep popping up. Golden ratio is a legit ratio, like 1/2 or 2/5, i.e. you may encounter it here and there, but none more often that $\sqrt 7 / 3$, for instance. I'm saying there's absolutely nothing special or interesting about it compared to constants like $\pi$, that are physical in every sense. take a water mellon and a measuring tape to convince yourself.
 the Golden ratio is Kardashians of all ratios.
Comment: @Aksakal $\Phi$ appears in self-replication problems in a similar way in which $e$ appears in exponential growth. It's just one possible value out of an infinite family and is not special with respect to its peers. You claimed that "it is not interesting to think about it in this way". Leaving aside that what is interesting or not is very relative, the point is that estimating $\Phi$ statistically brings up very different kind of approaches from those used to estimate $\pi$ or $e$ (see my question), and that's what makes this interesting, not whether we aim for $\Phi$ or for $1.89253$.
Comment: @kastellane, actually, $\phi$ is inserted into self replication, it's not naturally in it like $e$, in my opinion.
Comment: @Aksakal but the point is the following: how could we ask for the estimation of any of $\Phi$'s irrational peers? Let's say $1.89253...$ is one of those. Would it make sense to simply ask for statistically approaching $1.89253...$? Obviously not. Now, if I ask about $\Phi$, it immediately defines a family of algorithms, and that's the point of using $\Phi$ here. Look at the answers, if they had changed a detail in the algorithm, they would not get $\Phi$, nonetheless, all the answers smell of self-replication and self-referencing. Whether $\Phi$ is special or not is just not the point at all.
Comment: Kastellane, I am curious about what aspect of my answer has any echo ("smells") of self-replication or self-referencing.
Comment: @Whuber you are using Monte Carlo to solve the quadratic equation which is originated in e.g. the branching process proposed by Silverfish's answer. Actually, to be more precise, all the other answers are openly based on self-referencing or self-replicating approaches. Yours is the only one that echoes by using the equation as a starting point.
Comment: @kastellane you can get pretty much any number (ratio) using the proposed approaches. somehow I dont find them interesting for this reason. there's nothing fundamental about getting an arbitrary ratio in multiple trials. like tweak these procedures and get $\sqrt 3$, big deal
Comment: @Aksakal to this regard I cannot add anything else beyond what I said in my comment on Mar 17 at 20:06
Answer: Because you are looking for "unexpected" solutions, permit me to offer one before explaining it.
This is working R code to estimate $\varphi=(1+\sqrt{5})/2$ from iid uniform values and relatively simple (algebraic) calculations:
u <- runif(1e6)
v <- runif(length(u))
median((v/u)[u^2 + v^2 <= 1 & u <= 2*v])

1.61998

This procedure, which was inspired by the geometric nature of Buffon's needle experiment, can likewise be illustrated geometrically.  It samples the blue portion of the unit square lying above the line of slope 1/2, u <= 2*v, enclosed within the unit circle u^2 + v^2 <= 1.  The median slope of the sampled points estimates $\varphi,$ as simple trigonometric calculations will affirm.  Thus, you throw darts at the square dartboard and after you're tired of that, sweep counterclockwise through the points landing in the blue sector until you have encountered half of them: the slope you have attained estimates $\varphi.$  Since approximately $7\pi/40 \approx 55\%$ of the points will fall in the blue sector, this rejection sampling method is reasonably efficient.

There are many equivalent ways to run this experiment, some of which are a little more efficient, such as
z <- qt(runif(1e6, 1/2, pt(2,1)), 1)
p <- median(z)
(1 + p + 1/(7*p)) * 7/8

1.61731

This method generates the slopes directly from a Cauchy (Student t) distribution and uses the relationship $\varphi = 1/\varphi$ to generate two inversely related estimates; a suitably weighted linear combination of them has lower variance (and therefore greater precision) than either estimate alone.  (The weights are approximate, chosen empirically.)

Finally, I confess there is a "tuning parameter" in this setup (as there must be): by varying the magic value $x=2$ in the condition u <= 2*v you can estimate the quadratic number $(1 + \sqrt{1 + x^2})/x.$ A quick demonstration is based on a half-angle formula for the tangent.  Let $0\lt \theta\lt \pi/2$ be the angular measure of the blue sector.  With $x=\tan\theta,$
$$x = \tan\theta= \frac{2 \tan(\theta/2)}{\tan^2(\theta/2) - 1}.$$
Geometrically, this sampling procedure estimates the reciprocal slope of half the sector's angle, $1/\phi = \cot(\theta/2)$ (or, reversing the roles of u, and v, it estimates $\phi = \tan(\theta/2)$).  Thus, in algebraic terms it finds a solution of the equation
$$x = \frac{2\phi}{\phi^2-1}$$
which is equivalent to
$$\phi^2 + \frac{2}{x}\phi - 1 = 0$$
and the claim follows from the Quadratic Formula.
Comment: I was reading this answer and thought "this looks like a whuber answer", and lo: it was.  Where does one find relationships like this?  Is there a book or paper you read about it in?
Comment: @EngrStudent That's an interesting thought--thank you for acquainting me with this concept of "Matthew effect."  I think we must be careful with its use, because that term appears to refer to distinct phenomena.  In [social science](https://en.wikipedia.org/wiki/Matthew_effect#Sociology_of_science), for instance, it refers to better-known scientists getting undeserved credit just because they are better known.  I think you have in mind an alternative meaning in which the more you know and think about something, the more able you are to advance your knowledge: "luck comes to the prepared."
Comment: (continued)...  At the outset, this one just "smelled" of continued fractions (for some reason I can't fully describe), so I was pleased when Peter O. jumped in with such an elegant solution.  I can say more, actually: $\varphi$ plays a role in the number-theoretic analysis of approximating irrational numbers with rational numbers. Continued fractions lie at the heart of that analysis and $\varphi$ shows up as a kind of extreme or limiting example. It is also at the heart of Fibonacci numbers, which serve as a model of linear recursive relations, and those appear in Markov chains, *etc.*
Comment: @Engr About the only way I know of answering questions like this is to have studied many other questions and (if only vaguely) recall seeing a quadratic (or $\varphi$ or whatever is the issue) in the answer, then to hunt for such questions here or on the Web or in books on the shelf.  Presently I am convinced that over the next several months I will encounter questions in which $\varphi$ (or some quadratic) emerges as the answer to a probability question: and I will then hunt for this thread and point out that related question.
Comment: Then it is the Matthew effect applied to wisdom/insight?  This motivates both study, and exploration in areas where others have not yet dwelt.
Comment: It is simpler to estimate $\phi$ from just the first variable!: `1/mean(u^2+u<1)`
Answer:
There's only one Mr Tripletoddletrouble. In fact, unless he has
a son to pass his surname down to, he'll be the last
Mr Tripletoddletrouble. Social mores of his time and place sadly
disallow even such an exquisite surname to survive by passing through the
female line.
Mr Tripletoddletrouble has a rare and mathematically convenient
genetic condition, which any future generations of
Tripletoddletroubles will inherit: if he fathers any sons at all,
and there's a 50% chance he will, it will be one set of triplets.
So at every step of the family tree we see, equally likely, either three sons or none.
The bad news for
onomatologists is
this leaves a 50% chance of a wonderful name becoming extinct among the
next generation. The good news is that every Mr
Tripletoddletrouble has, on average, 1.5 sons — since this is
safely above one, the expected population of Tripletoddletroubles enjoys
exponential growth, and there is a positive probability their surname
will survive forever.
What's the probability that the Tripletoddletrouble surname will, eventually, become extinct?

Here's a quick R simulation.
set.seed(123)

nsims <- 1e5
ngens <- 20

simulate_extinction <- function(ngens) {
  nsurvivors <- c(1, rep(NA, ngens - 1))
  for (gen in seq_len(ngens - 1)) {
    nsurvivors[gen + 1] <- 3 * rbinom(1, nsurvivors[gen], 0.5)
  }
  extinct <- (!is.na(nsurvivors) & nsurvivors == 0) # rbinom gives NA if population huge
  return(extinct)
}

pextinct <- rowMeans(replicate(n = nsims, simulate_extinction(ngens)))

plot(pextinct, xlab = "Generation number", ylab = "Probability of extinction")
abline(h = (sqrt(5) - 1)/2, col = "red")
sprintf("Estimated probability of extinction = %f", pextinct[ngens])

The red line in the plot is at
$$\varphi - 1 = \varphi^{-1} = \frac{\sqrt{5} - 1}{2} \approx 0.618034 $$

[1] "Estimated probability of extinction = 0.618150"
This is a question about branching processes. Indeed, one of the earliest investigations into their stochastic behaviour originated in Victorian concerns about the extinction of unusual surnames. The resulting Galton-Watson process paper is available online:

Galton, F., & Watson, H. W. (1875). "On the probability of the extinction of families". Journal of the Royal Anthropological Institute, 4, 138–144.

"Either 3 or 0 offspring, equally likely" is arguably the simplest branching process with non-trivial probability of extinction. We need at least two outcomes if chance is to play a role, including zero offspring for extinction to be possible. "Either 1 or 0 offspring" is clearly doomed: with no branches budding off, the family line becomes extinct the first time there are no sons. "Either 2 or 0 offspring, equally likely" gives a mean of exactly one offspring to replace each individual. When fate balances on this knife-edge, it turns out extinction is certain in the long run, even if the family tree successfully buds a few times. We could tweak the offspring distribution to produce a range of desired extinction probabilities, but only by introducing unequal probabilities or more than two outcomes. This set-up doesn't feel artificially "tuned" to shoe-horn in the golden ratio.
Let's find the probability of ultimate extinction, $\theta$, algebraically. Intuitively, this probability splits into two parts: either the original Mr Tripletoddletrouble has no sons and his line becomes extinct immediately, or he successfully has three sons, but each of their three lines eventually becomes extinct. Since a son is in the same position as the original Mr Tripletoddletrouble, their lines also each have extinction probability $\theta$. Since we are concerned only with direct male descendants, each line's fate is independent of the others. Given that there are three sons, the probability the surname becomes extinct is therefore $\theta^3$.

From the tree diagram, we see the probability of extinction $\theta$ must obey the equation
$$\theta = \frac{1}{2} + \frac{1}{2}\theta^3 \tag{1}$$
which we can solve (and will, shortly). First let's tie this into some wider theory of branching processes. The number of offspring of any individual is a random variable with probability distribution $p_0 = p_3 = 0.5$ and $p_n = 0$ otherwise, so its probability generating function is:
$$\Pi(s) =  \sum_n p_n s^n = \frac{1}{2} + \frac{1}{2} s^3 $$
Looks familiar? No coincidence. More later. By evaluating the derivative of the pgf at $s=1$, we get the mean number of offspring. This number $R_0 = \Pi'(1)$ is important in population ecology and human demography, where it's called the net reproduction rate (it's usually defined as the mean number of daughters produced by each female, rather than sons by each male — maternity is easier to track than paternity, and in many species females can reproduce by parthenogenesis), while in epidemiology it's the basic reproduction number (mean number of infections directly generated by one infected individual, in a fully susceptible population). If $\Pi'(1) \leq 1$ then ultimate extinction is certain. If $\Pi'(1) \gt 1$ the probability of extinction is below one. We have
$$\Pi'(s) = \frac{3s^2}{2} \implies \Pi'(1) = 1.5 > 1$$
so the surname has positive probability of survival. How many Tripletoddletroubles survive in each generation? Take one individual as "generation zero", and let $Z_n$ be the number of descendants after $n$ generations. $Z_n$ is a random variable whose probability distribution can be read off from the coefficients of its pgf $\Pi_{n}(s)$, which we find by iteratively applying $\Pi$, the offspring pgf, $n$ times:
$$\Pi_{n}(s) = \Pi(\dots\Pi(\Pi(s))\dots) $$
Why? $Z_{n}$ is the sum of the offspring of the $Z_{n-1}$ survivors in the previous generation. The numbers of offspring from each survivor are independent, identically distributed (iid) random variables with pgf $\Pi$, and the number of them we are adding up has pgf $\Pi_{n-1}$, so by the rule for the pgf of the sum of a random number of iid variables (proof in this answer), $Z_n$ has pgf $\Pi_{n}(s) = \Pi_{n-1}(\Pi(s))$. For example, after two generations
$$\Pi_2(s) = \Pi(\Pi(s)) = \frac{1}{2} + \frac{1}{2} \left(\frac{1}{2} + \frac{s^3}{2} \right)^3 = \frac{9}{16} + \frac{3s^3}{16} + \frac{3s^6}{16} + \frac{s^9}{16} $$
so there's a $\frac{1}{16}$ chance of nine descendants but $\Pi_2(0) = \frac{9}{16}$ chance that extinction has already occurred. $\mathbb{E}(Z_2)$, the expected number of descendants after two generations, is found by $\Pi'_2(1) = 2.25$. It's no coincidence this equals $1.5^2$.
The mean and variance of the number of offspring from a single individual are $\mu = \Pi'(1)$ and $\sigma^2 = \Pi''(1) + \mu - \mu^2$. You can prove by induction that $\mathbb{E}(Z_n) = \mu^n$. Now it's obvious why ultimate extinction is certain when $\mu < 1$. With $\mu = 1.5$ we see exponential growth on average, despite our high chance of early extinction. Essentially, chains of surname transmission tend to either fizzle out or blow up, and $\mu = 1.5$ guarantees enough chance of blowing up that extinction is not inevitable. Good news for the Tripletoddletroubles; bad news if we switch context from surnames to infectious diseases with $R_0 > 1$. The way chains of infection can randomly either "go big or go home", rather than follow a deterministic rule like "each case infects exactly two susceptibles", relates to the epidemiological idea of overdispersion due to clustering or super-spreading events. The variance of the number of descendants after $n$ generations can be considerable, as $Z_n$ might be enormous or zero. Again by induction, we find:
$$\operatorname{Var}(Z_n) =
\begin{cases}
\frac{\mu^{n-1} \sigma^2 \left(\mu^n - 1\right)}{\mu - 1},  & \mu \neq 1 \\[2ex]
n \sigma^2, & \mu = 1
\end{cases}$$
In general, the probability of ultimate extinction is the smallest positive solution, $\theta^{*}$, of the equation $\theta = \Pi(\theta)$. That's exactly equation $(1)$ we derived above! But how did we know which solution to take? The probability of extinction by generation $n$ is $\Pi_n(0)$, since that's the constant or $s^0$ term of the pgf of $Z_n$, hence represents $\Pr(Z_n = 0)$. The probability of ultimate extinction must be $\lim_{n \to \infty} \Pi_n(0)$ which we can find using a cobweb plot of $y=\Pi(x)$ and $y=x$ for $0 \le x \le 1$. Since $\Pi(0) = p_0$, the probability an individual has no offspring, we can assume the y-intercept is between $0 \lt \Pi(0) \le 1$ (if $p_0 = 0$ then extinction is clearly impossible). So $y = \Pi(x)$ starts above $y=x$, and the first time it intersects $y=x$ must be from above. Since $\Pi(x)$ and its derivatives have only non-negative coefficients, its graph is increasing and convex on $0 \le x \le 1$. This means it can intersect $y=x$ at most twice in this interval: once from above, then again from below. $\Pi(1) = \sum p_n = 1$ so the graphs certainly intersect at $(1,1)$.
This intersection's nature depends on the slope $\Pi'(1)$, which represents the mean number of offspring $\mu$ (biologically, $R_0$). If $\Pi'(1) > 1$ it must be steeper than $y=x$ so $y = \Pi(x)$ is hitting the line from below, in which case there must have been an earlier intersection in $0 \lt x \lt 1$. If $\Pi'(1) < 1$ it's shallower so hitting from above, and there's no earlier root. If $\Pi'(1) = 1$ the two curves just touch at $(1,1)$, but $y = \Pi(x)$ must have been shallower before (its average slope over $0 \le x \le 1$ is $1 - p_0$ so below one), hence approaches the line from above and there can be no earlier root. This is why if $\mu=1$ but $p_0 > 0$, ultimate extinction has probability one.
To find $\lim_{n \to \infty} \Pi_n(0)$ graphically, read off horizontally from the y-intercept at $y = \Pi(0)$ to the $y=x$ line, where now $x = \Pi(0)$. Then read off vertically to the $y = \Pi(x)$ graph, where now $y = \Pi(\Pi(x)) = \Pi_2(x)$. Read off horizontally to the line so $x = \Pi_2(x)$. Read off vertically to the curve so $y = \Pi(\Pi_2(x)) = \Pi_3(x)$. Note that all horizontal readings are rightwards and vertical readings are upwards, since $y = \Pi(x)$ is increasing so each vertical positions is above the previous one. This procedure must converge to the first (i.e. smallest positive $x$) intersection point $x = \Pi(x)$, where $y = \Pi(x)$ hits $y = x$ from above. We illustrate the three cases $\mu = 1.5$ ($p_0 = p_3 = \frac{1}{2}$), $\mu = 1$ ($p_0 = \frac{2}{3}, p_3 = \frac{1}{3}$) and $\mu = 0.5$ ($p_0 = \frac{5}{6}, p_3 = \frac{1}{6}$). The dotted blue line is the tangent to $y = \Pi(x)$ at $(1, 1)$, and shows the role of its slope $\Pi'(1) = \mu$ in determining whether there was an earlier intersection.

We need the smallest positive solution $\theta*$ of $(1)$. Moving $\theta$ to the right-hand side and doubling to clear out the fractions, we obtain:
$$0 = \theta^3 - 2 \theta + 1 = (\theta - 1)(\theta^2 + \theta - 1)$$
The solutions are $-\varphi < \varphi^{-1} < 1$ so the smallest positive solution is $\theta^{*} = \varphi^{-1}$.

 Time to reveal the "fiddle". This link to the golden ratio isn't a result
 I recall seeing before,
 but I reverse-engineered it by thinking about the required factorisation of
 the final equation. Since
 $\Pi(1) = \sum p_n = 1$, we always have $\theta = 1$ as a root of
 $\theta = \Pi(\theta)$, so $(\theta - 1)$ must appear as a factor once we
 set one side to zero. I also knew what quadratic I wanted to see.
 After that I worked back to try to form a valid pgf. Negative
 coefficients are disallowed; positive coefficients just
 needed normalising so they sum to unity. I hoped
 that the resulting probability distribution for the offspring would be
 a "nice" one — which I think it is!

R code for cobweb plot
ngens <- 100
par(mfrow=c(1, 3), pty = "s", xaxs = "i", yaxs = "i")

for(p0 in c(1/2, 2/3, 5/6)) {
  pgf <- function(x) {p0 + (1-p0)*x^3}
  mu <- p0*0 + (1-p0)*3
  plot(pgf, xlim = c(0,1), ylim = c(0,1), xlab = "", ylab = "",
       main = paste0("Mean offspring = ", mu))
  segments(0, 0, 1, 1)
  abline(1 - mu, mu, col = "blue", lty = "dotted")
  pextinct <- c(0, rep(NA, ngens))
  for (n in seq_len(ngens)) {
    pextinct[n + 1] <- pgf(pextinct[n])
    segments(pextinct[n], pextinct[n], pextinct[n], pextinct[n + 1], col = "red")
    segments(pextinct[n], pextinct[n + 1], pextinct[n + 1], pextinct[n + 1], col = "red")
  }
  print(pextinct)
}

Comment: That is interesting.  The probability generating function can also be seen as a production in a context-free grammar, so that it can mean: "1/2 chance of stopping; 1/2 chance of producing three more productions" (see, for example, "Calibrating generative models...", Icard, 2020).
Comment: One reference to the probability generating function you found is: Olmedo, F, Kaminski, B.L, et al., "[Reasoning about recursive probabilistic programs](https://arxiv.org/abs/1603.02922)", In IEEE Symposium on LICS, 2016.  This was referenced by the Icard paper.
Comment: Are there more realistic contexts for using a binary model like this? For either surnames or diseases, I would start with a Poisson model with a mean of 1.5 transmissions instead — but then the probability $\theta$ of extinction satisfies $\theta=e^{1.5(\theta-1)}$, with a non-algebraic solution.
Comment: @PeterO. What I find particularly interesting is that there is a recursive halving process, as you've commented and I've tried to bring out in my answer by including a tree diagram. But because of the complication of *all three* subsequent branches becoming extinct, it's not "obvious" (at least to me!) how this relates either to the recursive halving in [your answer](https://stats.stackexchange.com/a/514058/22228), or the classic geometric approaches to the golden ratio
Comment: @MattF. I tried thinking but couldn't find anything satisfyingly realistic, so resorted to this tall tale! Perhaps a "bet one dollar at a time, treble-or-bust, equally likely" gambling game? But that's simply creating a set of game rules to mimic the mathematics we want to see, rather than anything that smells of "real life" as we experience in the wild. I found Peter O's comment v interesting, but again, that's an abstract rather than "realistic" context. (For what it's worth, epidemiologists seem to prefer the negative binomial model but that doesn't helps us all that much with the PGF!)
Answer: There is a recursive algorithm that succeeds (outputs heads) with probability $1/\Phi$. It takes advantage of the fact that the continued fraction representation of $\Phi$ has all ones.
The algorithm follows:
Procedure OnePhi(): Returns 1 with probability $1/\Phi.$

Do the following steps repeatedly, until the algorithm returns a number:

Set C = RandomBit() (the flip of a fair coin that shows 1 or 0 with equal probability).
If C = 1, return 1 and stop.
Set D = OnePhi().
If D = 1, return 0 and stop.

The expected number of flips used by the algorithm, $\mathbb{E}[N]$, is $2\Phi$ as shown below, taking note that all the flips are independent:

Each iteration stops the algorithm with probability $p = \frac{1}{2} + (1-\frac{1}{2}) * (1/\Phi)$ (1/2 for step 2 and $1/\Phi$ for step 4).
Thus, the expected number of iterations is $\mathbb{E}[T] = 1/p$ by a well-known rejection sampling argument, since the algorithm doesn't depend on iteration counts.
Each iteration has $1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}$ coin flips on average, so the whole algorithm has $\mathbb{E}[N] = (1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}) * \mathbb{E}[T]$ coin flips on average. This equation has the solution $\mathbb{E}[N] = 1 + \sqrt{5} = 2\Phi$.

And on average, because the coin is fair, half of these flips ($\Phi$) show 1 and half show 0.
The following Python code shows this:
import random

def onephi(flips):
 # Flips stores counts on the number of times
 # the coin was flipped and the number of tails.
 # Flips is not essential to the algorithm and
 # can be omitted.
 done=-1
 while done==-1:
   flips[0]+=1
   if random.random()<0.5:
     done=1
   else:
     flips[1]+=1
     if onephi(flips)==1: done=0
 return done

flips=[0,0]
c=0
runs=10000000
for _ in range(runs):
  c+=onephi(flips)
print("Expected coin flips: %f" % (flips[0]/runs))
print("Expected coin flips showing heads: %f" % (flips[1]/runs))
print("Estimated probability: %f" % (c/runs))

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/120949/discussion-on-answer-by-peter-o-what-are-examples-of-statistical-experiments-th).
Comment: I made some modifications that I think make the code easier to follow. I sent it in the chat, but I put it here too so people interested in it can access it directly: https://ibb.co/yYxs0Rq
Answer: Here's a quick one. It's related to the branching process from Silverfish's answer.
Run a random walk, starting from height 0, say. At each step, either move up by 2 or move down by 1, with probability 1/2 each.
Count the times at which the current height is below the maximum height so far.
The proportion of such times converges to $\phi$.
import random
t=0; height=0; max=0; nonRecords=0
N=10**7
while(t<N):
    height+=random.choice([-1,2])
       # increment by -1 or 2 with probability 1/2 each
    if height<max: nonRecords+=1
    if height>max: max=height
    t+=1;
print(nonRecords/t)
print((5**(0.5)-1)/2)

0.6182664
0.6180339887498949
Comment: +1. For those using `R`, here is a very fast implementation: `x <- cumsum(sample(c(-1,2), 1e7, replace=TRUE)); (mean(cummax(x) > x))`
Comment: @whuber nice! $\,$
Answer:
Fibonacci numbers and Markov chains
I remember a question in which the Fibonacci numbers occurred. While computing the waiting time for the probability of flipping '1-0-0' the probabilities of the state '1' and the state '1-0' are Fibonacci numbers (divided by some power of 2).
We can simulate this in several ways
Example 1

Generate random binary numbers of length $n$
Eliminate the numbers with double 1's
Count the fraction of the numbers with a single '1' at the end among the remaining ones

Example code
library(binaryLogic)
set.seed(1)
### string length
n <- 20
### simulation
n_sim <- 10^4

### Step 1 generate random binary numbers (including zero)
x_dec <- sample(0:(2^n-1),n_sim,replace=TRUE)
x_bin <- as.binary(x_dec)
### Step 2 find subselection without double one's
sel <- sapply(x_bin, FUN = function(bx) sum(shiftLeft(as.binary(bx),1) & as.binary(bx))<1)
### Step 3 compute the ratio of odd and even numbers
sum(x_dec[sel] %% 2 == 0)/sum(sel)
### returns 0.6045198

Example 2
This example shows a bit better the similarity with a Markov Chain. Ratio's like these may occur a lot in practice.
Requirements:

1 vase/urn
1 fair coin
a lot of red and blue marbles (or any other tokens to express a binary option)

Algorithm:

Start with some marbles in the vase.

Draw a marble and remove it

Flip twice a coin. For each tails: put a marble of the opposite colour into the vase (opposite to the colour of the removed marble. For each heads: if the removed marble was red, then put a red marble into the vase.

Repeat 2 and 3 untill you are fed up with it.

Count the ratio of red and blue marbles

Example code
### initiate
### we start with some red and blue marbles
set.seed(1)
red  <- 5
blue <- 5

### perform step 2 and 3 a lot of times
for (i in 1:10^4) {
  ### sample from the vase
  x <- sample(c("red","blue"),1, prob = c(red,blue))
  ### coin flips
  coinflips <- rbinom(2,1,0.5)

  ### add and remove marbles
  if (x == "blue") {
    blue <- blue - 1
    red <- red + sum(coinflips)
  }
  if (x == "red") {
    blue <- blue + sum(coinflips)
    red  <- red - 1 + sum(coinflips == 0)
  }
}

### returns 0.6057246
blue/red


Criando Thread dinamicamente com Spring-boot

Question: Bom dia terráqueos,
Existe a possibilidade de fazer o spring-boot criar thread quando necessária e também matar a mesma ?
Comment: Qual seria o cenário?
Answer: Coloque a anotação @EnableAsync na sua Application.java e dê um extends na classe AsyncConfigurerSupport.
Com isso será possível criar um ThreadPoolTaskExecutor, segue exemplo abaixo.
 @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("GithubLookup-");
        executor.initialize();
        return executor;
    }

Segue link do guia do próprio Spring Boot:
https://spring.io/guides/gs/async-method/


AWS ECS CannotStartContainerError: Error response from daemon

Question: I'm trying to start a task with a container with the following command:
/bin/sh -c "export KAFKA_LISTENERS=\"PLAINTEXT://$$(hostname -i):9092\" && start-kafka.sh"

But I'm getting this error when the container tries to start and I have no idea of what might be causing it:
CannotStartContainerError: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"/bin/sh -c \\\"export KAFKA_LISTENERS=\\\\\\\"PLAINTEXT://$$(hostname -i):9092\\\\\\\" && start-kafka.sh\\

The weird thing is that the error only happens in AWS, if I create a docker compose file and run it locally everythig works fine.
Any ideas?
Thank you!
Answer: After banging my head against the wall for a few days I finally figured it out. It seems AWS console cuts the error message at 255 characters, so I wasn't seeing the full error message. The isse was that when setting the command for the container, AWS will parse it into an array-style CMD. So /bin/bash -c "echo hello!" gets turned into ["/bin/bash -c \"echo hello!\""], which doesn't work. The correct format would be ["/bin/bash, "-c", "echo hello!"]. To accomplish this you just need to separate your command by commas in the AWS Console, so it becomes/bin/bash,-c,echo hello!.


Looping over the map function in protractor

Question: I have an angular application where I have a timeline with list event dates and the respective event description. This is the Html source code.

Historical Timeline

{{timeline.eventDate}}

{{timeline.description}}

Now I am basically trying to make use protractor to ensure that the correct event date matches the event description. So i decided to use a map function. The issue is I would have a variable x which would tell me how many events there are . For example there can be 2 events, 6 events, etc. Events are dynamically
generated dynamically as you can tell by looking at html code also. Here is the code for my test I wrote.
it('FOO TEST', function(){

    var x = 0;
    while(x<4){
   var timeline = element.all(by.css('#timeline')).map(function (timeline) {
       return {
          date: timeline.element(by.css('#eventDate'+x)).getText(),
          events: timeline.element(by.css('#eventDescription'+x)).getText()
     }

   });
      x++
  }

   timeline.then(function (Value) {
    console.log(Value);
  });

});

The issue is that for some reason in command line it only prints the last event out of 5 events. It does not print other events. I am definitely doing something wrong. I am brand new to promises so any suggestion here is appreciated. And yes i want to do like a individual test for each event in the timeline.
Answer: The problem is in the timeline locator: #timeline matches the timeline container while you need the inner repetative timeline blocks. Here is how you can match them:
var timeline = element.all(by.repeater('timeline in formattedTimelineData')).map(function (timeline) {
    return {
        date: timeline.element(by.binding('timeline.eventDate')).getText(),
        events: timeline.element(by.binding('timeline.description')).getText()
    }
});

timeline.then(function (timeline) {
    console.log(timeline);
});

You can then loop over items like this:
timeline.then(function (timeline) {
    for (var i = 0; i < timeline.length; ++i) {
        // do smth with timeline[i]
    }
});

Or, you can assert the complete timeline variable which is a promise and can be implicitly resolved by expect into an array of objects, for instance:
expect(timeline).toEqual([
    {
        date: "First date",
        events: "Nothing happened"
    },
    {
        date: "Second date",
        events: "First base"
    },
    {
        date: "Third date",
        events: "Second base"
    },
]);

Comment: This would get all the events and dates?
Comment: Yes it does. I upvoted and definitely accepting your answer as It works yes but now the thing is what if i wanted do some kind of loop that looped through each index and did this check is it possible? I know the solution you posted is definitely a "better" approach but i was just curious if i wanted to achieve it by looping as i attempted how would i do it? If you can add it under your answer how to do that it would be awesome !
Comment: The point is so that i could have kind of an individual test for each event and its description if possible. it('event 1 test'), it('event 2 test') and so on.
Comment: @Dinero `each()` might also be related to the use case. I don't think you can dynamically create `it()` blocks..
Comment: hmm so is there any way to check each one individually? maybe make a describe dynamically for each event?
Comment: I have another protractor question maybe you can help http://stackoverflow.com/questions/31455952/configure-saucelabs-for-jenkins
Answer: I recommend against putting logic in your test - http://googletesting.blogspot.com/2014/07/testing-on-toilet-dont-put-logic-in.html.
A while loop is logic.
You should know ahead of time how many events will be in your timeline.  In the example case 4.  Then your specs should look like
element.all(by.css("#timeline")).then(function(events){
    expect(events.count).toEqual(4);
    expect(events[0].someThing()).toEqual(expectedValue0);
    expect(events[1].someThing()).toEqual(expectedValue1);
...
    expect(events[3].someThing()).toEqual(expectedValue3);
 })

Comment: I posted a new question that you might be able to help me out on http://stackoverflow.com/questions/31080298/using-page-object-pattern-correctly-in-protractor
Answer: The repeater in my case has a lot of elements. I dont want to repeat through all elementsas my protractor spec times out while looping through so many elements. How can I just restrict the loop to run only for 1st 10 elements of the repeater? I have tried many things but I am just not able to get this working. How to loop only through first 10 elements of a repeater when using map()
The timeline variable in above example returns data for all elements in the repeater. How can i get the timeline variable to just have data for first 10 elements of the repeater as the looping through 1000 of entries of the repeater is time consuming that causes my protractor spec to timeout.


In WCF Service, I need to send the DataMember based on the condition. How to do that?

Question: For example:
Public class TEST
{
      [DataMember]
       public string EMPName
       {
        get; set;
        }
}

I need EMPName to be the part of the object which is the output response, but based on some condition and I need to write that condition in the service function I am calling.
e.g: If the EMPName contains 'Jolie' then only keep it the part of the output object otherwise don't send it with the output object.
Answer: Use ShouldSerialize property in your TESTclass.
Include the line below in your TESTclass:
public bool ShouldSerializeEMPName() { return EMPName.Contains("Jolie"); }

Hope it helps


Getting fatal error when trying to install Umami test site

Question: I'm using Windows 10. I have installed composer and PHP.
I run the command composer create-project drupal/recommended-project mysite to create a recommended project. That works with no errors. Then I try to run the command php web/core/scripts/drupal quick-start demo_umami to install a sample Drupal site using the Umami Maganize demo:
C:\drupal\mysite>php web/core/scripts/drupal quick-start demo_umami
 9/17 [==============>-------------]
Install site
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480
bytes) in C:\drupal\mysite\web\core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php on
line 274

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
in C:\drupal\mysite\web\core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php on line
274

C:\drupal\mysite>

It makes no sense that I'm trying to allocate only 20480 bytes and that's causing it to throw a FatalError. How do I fix this?
Comment: That's trying to allocate 20480 bytes ontop of what's already allocated to the php task
Comment: Well I raised the memory_limit in php.ini from 128M to 2G and tried it again, and it works.
Comment: Unfortunately that's a bit like using a sledgehammer to crack a nut. For this very narrow requirement, it appears to have done the job. But at what hidden cost to the underlying structure of your nut-bashing table
Answer: In php.ini, increase the memory_limit from 128MB to 2G:
; Maximum amount of memory a script may consume
; https://php.net/memory-limit
;memory_limit = 128M
memory_limit = 2G


Other distribution for random effects than Normal

Question: In frequentist statistics, we always assume that the distribution of the random effects is Normal due to the fact that it makes computations more easy. In Bayesian statistics, we can easily change this assumption and use different distributions. In my Bayesian analysis, I want to test whether other distributions are more appropriate. I already fitted a t-distribution and a log-normal distribution. But I was wondering what other distributions can be considered? I was thinking about an exponential distribution, but then my random effects can only be positive. Which distributions can I use or are most often used next to the Normal distribution?
Comment: It is not true that, "In frequentist statistics, we always assume that the distribution of the random effects is Normal due to the fact that it makes computations more easy." The normality assumption is often made--sometimes even in cases where this is unwarranted. However, many other families of distributions are used in frequentist inference. I show one example in my Answer.
Answer: Suppose $n=100$ independent observations $X_1, X_2, \dots, X_{100}$ are taken from an exponential distribution and we wish to find a 95% confidence interval (CI) for the population mean $\mu,$ where $E(X_i) = \mu.$
Then one can show that $\frac{\bar X}{\mu} \sim \mathsf{Gamma}(\mathrm{shape}=n, \mathsf{rate}=n).$ Then if $L$ and $U$ cut 2.5%, respectively, from the lower and upper tails of $\mathsf{Gamma}(n,n),$ we have
$$P\left(L \le \frac{\bar X}{\mu}\le U\right)
= P\left(\frac{\bar X}{U} \le \mu \le \frac{\bar X}{L}\right) = 0.95,$$
so that a 95% CI for $\mu$ is of the form
$\left(\frac{\bar X}{U},\, \frac{\bar X}{L}\right).$
In R, the exponential distribution is parameterized by the rate $\lambda = 1/\mu.$ In particular, suppose we have a vector x of observations from
$\mathsf{Exp}(\lambda = 0.02),$ which has $\mu = 50.$
set.seed(2020)
x = rexp(100, 0.02)
summary(x)
    Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
 0.04116  13.32663  37.43140  52.98382  68.58117 293.37596

Then a 95% CI for $\mu$ based on these $n=100$ observations is $(43.96,65.12).$ Notice that $\bar X$ is not exactly at the center of this CI.
(This is one of the 'lucky' 95% of situations in which the CI covers $\mu.$)
mean(x)/qgamma(c(.975,.025), 100, 100)
[1] 43.95941 65.11949

Falsely assuming normality. If we had made the incorrect assumption that the data in x were normal, then
we might have tried to use a t CI as an interval estimate of $\mu,$ to get $(41.75, 64,21),$ as below: This interval also happens to include $\mu=50,$
but it is based on a false assumption, so we cannot expect that such an interval will
cover $\mu$ in 95% of situations--not even when the number of observations is as large as $n=100$ so that $\bar X$ itself may be roughly normally distributed, in view of the Central Limit Theorem.
t.test(x)$conf.int
[1] 41.75369 64.21395
attr(,"conf.level")
[1] 0.95

Note: The following simulation in R illustrates that for $n=20$ the
correct gamma CI covers $\mu=50$ in almost exactly 95% of
the 100,000 iterations, whereas the incorrect t CI covers $\mu$ in
only about 92% of them.
set.seed(2020)
m= 10^5;  n = 20
x = rexp(m*n, .02)
DTA = matrix(x, nrow=m) # m x n matrix each row a sample
a = rowMeans(DTA)       # 100,000 sample means
s = apply(DTA, 1, sd)   # 100,000 sample SDs

LCL.g = a/qgamma(.975,n,n)
UCL.g = a/qgamma(.025,n,n)
COV.g = (LCL.g < 50) & (UCL.g > 50)
mean(COV.g)
[1] 0.95003

LCL.t = a+qt(.025,n-1)*s/sqrt(n)
UCL.t = a+qt(.975,n-1)*s/sqrt(n)
COV.t = (LCL.t < 50) & (UCL.t > 50)
mean(COV.t)
[1]  0.91857