Widget in info window with multiple markers

Question: I'm trying to create a map with lots of markers and info windows using the Google Maps API. I can get a map to display lots of markers and info windows either with the locations in the script or loading them from a file.
What i want to do is put this code:

into the info window so the marker will be at the location and when clicked the info window shows the tide time.
I can't find any way of getting this to work within the info window. Can anyone help? Thanks
Answer: I'm sorry, I don't fully understand what you are saying. What do you mean exactly by this "What i want to do is put this code into the info window so the marker will be at the location and when clicked the info window shows the tide time."?
First of all, you do not need code inside an info window to give the marker a location. That is one of the markers standard attributes.
Second, I am almost certain you cannot have an event(code) inside your info window. What you can do is when a user clicks the marker, the map will zoom in or out. And you can have another event on that marker later.
Maybe this will help your answer (taken from Google Maps API documentation)
"The InfoWindow's content may contain either a string of text, a snippet of HTML, or a DOM element itself. "
Answer: you need to add html to the infowindow..
See the documentation
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

var contentString = '
'+
    '
'+
    '
'+
    '
Uluru
'+
    '
'+
    '
Uluru, also referred to as Ayers Rock, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335 km (208 mi) '+
    'south west of the nearest large town, Alice Springs; 450 km '+
    '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.
'+
    '
Attribution: Uluru, '+
    'http://en.wikipedia.org/w/index.php?title=Uluru (last visited June 22, 2009).
'+
    '
'+
    '
';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

Edit
After further inspection of your code and your site i believe you're asking how to inject times and dates through a single file.
My suggestion is to use a JSON returned object from your server side code, iterate through the json object and use a template for the popup.
If you are curious you can reference something we do similar at http://demo.mapitusa.com you can easily browse the source code and find the js files that are required and see a working example.


Loop automatically skips my type = input.nextInt() part

Question: I'm working on a final project for java and I need to make a project that gets a bunch of details about a loan. Then I'm supposed to put 5 loans in an array then get the details then display all the details but for some reason in my loop in automatically gives an invalid type error. The error is this:
Please enter the prime interest rate
30
Please enter a loan type.
Choose either Business or Personal. If you don't type it like that you'll get an error.
You've entered an invalid type. Please restart and try again.
CreateLoan.java
package Construction;

import java.util.Scanner;
import Construction.Loan;

//Gotta fix an issue where it automatically gives an invalid loan type.
public class CreateLoan {

    public static void main(String[] args) {
        int x = 0;
        int primeRate;
        String type;
        Scanner input = new Scanner(System.in);
        Loan[] loans = new Loan[5];
        System.out.println("Please enter the prime interest rate");
        primeRate = input.nextInt();
        primeRate = primeRate/100;

        for(x = 0; x < 6; ++x) {
            System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
            type = input.nextLine();
            if (type.equalsIgnoreCase("Business")) {
                System.out.println("What is the account number on the loan?");
                int ln = input.nextInt();
                System.out.println("What is the last name on the account?");
                String last = input.nextLine();
                System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
                int la = input.nextInt();
                System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
                int term = input.nextInt();
                loans[x] = new BusinessLoan(ln, last, la, term);
            }
            else if (type.equalsIgnoreCase("Personal")) {
                System.out.println("What is the account number on the loan?");
                int ln = input.nextInt();
                System.out.println("What is the last name on the account?");
                String last = input.nextLine();
                System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
                int la = input.nextInt();
                System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
                int term = input.nextInt();
                loans[x] = new PersonalLoan(ln, last, la, term);
            } else {
                System.out.println("You've entered an invalid type. Please restart and try again.");
                System.exit(0);
            }
            Loan.displayAll();
        }
    }
}

Loan.java
package Construction;

public class Loan implements LoanConstant{
    public static int loanNumber;
    public static String lastName;
    public static int loanAmount;
    public static int interestRate;
    public static int term;
    public int primeRate;

    public int getLoanNumber() { return loanNumber; }
    public void setLoanNumber(int n) { n = loanNumber; }

    public String getLastName() { return lastName; }
    public void setLastName(String s) { s = lastName; }

    public int getLoanAmount() { return loanAmount; }
    public void setLoanAmount(int n) {
        n = loanAmount;
        if (loanAmount > MAX_LOAN_AMOUNT)
            loanAmount = MAX_LOAN_AMOUNT;
        }

    public int getTerm() { return term; }
    public void setTerm(int n) {
        n = term;
        if (term == 1) {
            term = SHORT_TERM;
        } else if (term == 3) {
            term = MEDIUM_TERM;
        } else if(term == 5) {
            term = LONG_TERM;
        } else
            term = SHORT_TERM;
    }

    public int getInterestRate() { return interestRate; }
    public void setInterestRate(int i) { i = interestRate; }

    public Loan(int ln, String last, int la, int term) {
        setLoanNumber(ln);
        setLastName(last);
        setLoanAmount(la);
        setTerm(term);
    }

    public static void displayAll() {
        System.out.println("The Company's Name is " + COMPANY_NAME);
        System.out.println("The loan number is " + loanNumber);
        System.out.println("The last name on the loan is " + lastName);
        System.out.println("The loan amount is " + loanAmount);
        System.out.println("The interest rate on the loan is " + interestRate);
        System.out.println("The term on the account is " + term);
    }
}

PersonalLoan.java
package Construction;

public class PersonalLoan extends Loan{

    public PersonalLoan(int ln, String last, int la, int term) {
        super(ln, last, la, term);
        interestRate = (int)((primeRate * 0.02) + primeRate);
        setInterestRate(interestRate);
    }
}

BusinessLoan.java
package Construction;

public class BusinessLoan extends Loan{

    public BusinessLoan(int ln, String last, int la, int term) {
        super(ln, last, la, term);
        interestRate = (int)((primeRate * 0.01) + primeRate);
        setInterestRate(interestRate);
    }

}

Comment: Its not. I need to know how to get those details 5 times in a loop. Thats what my project says but when I do it it automatically goes to the else clause of saying its an invalid type
Comment: when u dont enter any thin in your `type` then is will execute else part,where you write `System.exit(0);` ....please remove that line and try to execute.
Comment: Then it just continues on having everything as 0. After that then I get that skipping next line thing but as it stands that first loop through bugs and causes everything to be 0 because I cant enter a type.
Comment: Your `nextInt()` leaves `end of line` character(s) in the keyboard buffer. Your `nextLine()` picks them up. Read the question I pointed to.
Comment: I got it to work. You were right. It was the skipping thing. Sorry about that >.<
Comment: use BufferedReader or use next() method of Scanner, then parse the String to Integer, You won't get this issue.
Answer: update your line to:
    type = input.next();

Answer: When enter prime loan you hit enter after inputing the loan, this enter adds a line break character to the buffer.
nextint will get you the next int for your prime interest and then when u read using readLine the line that readline method reads is till a linebreak character whih got inserted in buffer when u press enter, thats why it is automatically giving invalid type.
To solve this :
 Scanner input = new Scanner(System.in);
    System.out.println("Please enter the prime interest rate");
      primeRate = input.nextInt();
      primeRate = primeRate/100;
      type=input.nextLine();  //clears the buffer
      for(x = 0; x < 6; ++x)
      {
            System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
  type = input.nextLine();


Arzela-Ascoli Theorem: pointwise boundedness at one point

Question: $f_n$ forms a sequence of equicontinuous functions in $C^0$, and domain is $[a,b]$. For $p$ belongs to $[a,b]$, we have $f_n(p)$ to be a bounded sequence in $R$. Prove $f_n$ to be uniformly bounded.
What I can do is to use connectedness of $[a,b]$ (chain connected) and pointwise bounded at one point to prove pointwise boundedness at every point. Then use pointwise boundedness and compactness of $[a,b]$ to show uniformly bounded.
But is there any method that we can avoid the use of chain connected to show $f_n$ is pointwise bounded at every point (i.e. only using equicontinuous and compactness of the domain). We can have another condition for the Arzela-Ascoli theorem to be true, if we can avoid the use of connectedness. (Clearly, one condition is that pointwise bounded at every point, but I am wondering if we can extend it to pointwise bounded at one single point, given the compact domain).
Thanks!
Here is the question, and part b asks a weaker condition. So is boundedness at one point enough or we need pointwise bounded for all points?

And the chain-connected argument comes from a previous question:
Answer: Take the statement for equicontinuity instantiated with $\varepsilon=1$. This creates an open cover of $[a,b]$. Compactness allows you to extract a finite subcover. Then $|f_n(x)|=|f_n(p)-f_n(p)+f_n(x)| \leq |f_n(p)|+|f_n(x)-f_n(p)|$. But $|f_n(x)-f_n(p)| \leq N$ where $N$ is the number of elements in our subcover, and $|f_n(p)|$ is bounded by hypothesis.
This is the standard trick used to prove things like the Heine-Cantor theorem. I'm not sure if this is actually what you meant by "chain connectedness", though.
Edit: Yeah, this is pretty much the chain-connectedness argument, just expanded out in this special case.
Comment: @12345 It doesn't follow just from compactness. What happens is that you get a finite subcover, then chain connectedness lets you "jump" from one open set in the cover to the next, each time increasing $|f_n|$ by at most $1$. Since there are only finitely many sets in the cover and you also have chain connectedness, you can reach any other point in $[a,b]$ in this manner and obtain a bound. As I said, just compactness is not sufficient.
Comment: I have added a picture for the chain connected part
Comment: So if the domain is just a general compact set, we do not have such argument?
Comment: And answer to part b question 18 is just pointwise bounded at all points?
Comment: @12345 It couldn't be with just a general compact set, because in that case you could have boundedness in one connected component and unboundedness in the other. As for part b, I assume the best you can do is a decomposition into chain-connected components.
Comment: Hi, can you show in detail how you got |fn(x)−fn(p)|≤N with compact?
Comment: @12345 You probably can't do it. I was using the fact that we're dealing with $[a,b]$ in particular. If you had, say, a union of two compact intervals, the argument could break down, because the $\delta$ could be so small that $p$ can't "communicate" with the other connected component.
Comment: But how to show that with [a,b] by its compactness? I am a bit confused now, since I only used the chain connected property.Thx!


Why can't some functions be integrated?

Question: There are some functions (such as xtan(x)dx [without limits]) which can't be integrated, why? How can one understand which function is integrable or not?
Comment: A function is Riemann integrable if and only if the set of its discontinuities over the region of integration is of Lebesgue measure zero... By the way, $x\tan(x)dx$  is not a function; $x\tan(x)$ is. Also that $x\tan(x)$ is integrable on some regions, for example $[0,1]$.
Comment: The distinction between differentiation and integration can already be seen if you focus not on "is it integrable or not?" but "is it a rational function or not?".  The derivative of every rational function is a rational function, but the antiderivative of a rational function *need not* be a rational function, such as the functions $1/x$ or $1/(x^2+1)$.
Answer: Why doesn't every function have an antiderivative?
Finding the indefinite integral of a function $f$, is the same as finding a function $F$ whose derivative is $f$. As explained here, this requires $f$ to be continuous.
If $f$ is discontinuous, then there may be some value $x$ such that $f(x)$ is undefined. When this happens, it means that $F'(x)$ does not exist, i.e. $F$ is not differentiable at $x$.
There are ways around this, however. For example, you can remove discontinuities or restrict the domain of $f$ so that it is continuous. There are increasingly obscure methods which can be used to integrate discontinuous functions, but I don't know much about them.
Stretching the definition of "integration" to its utmost extreme, I wouldn't be surprised if every function can be integrated.
Why can't every antiderivative be expressed in terms of elementary functions?
The integral of $x\tan(x)$ (ignoring discontinuities) is:
$$\frac{i}{2}(\text{Li}_2(-e^{2 i x}) + x (x + 2 i \ln(1 + e^{2 i x}))) + c$$
Where $i$ is the imaginary unit, and $\text{Li}_2$ is the polylogarithm of order 2. This is a special function, and cannot be expressed in terms of elementary functions.
The reason that antiderivatives cannot always be expressed in terms of elementary functions is that the set of elementary functions is not closed under limits in general. The specific fact that the integral of an elementary function is not always an elementary function is known as Liouville's Theorem.

Why can't some functions be integrated?


Javascript - Esconder filhos do radiobutton quando selecione outro radio do mesmo grupo

Question: Tenho um grupo de Radio Button, alguns deles tem outros inputs como filhos, se checar o Input Pai eles devem aparecer, se for desmarcado eles devem desaparecer.
Como no HTML abaixo:

    27.3 Presença de agentes específicos na citologia oncótica?
    <input type="hidden" title="" id="7329_2338" name="hidden_2338">

      <input type="radio" title="" id="7330_2370" name="radio_2370"  value="0">
      Não

      <input type="radio" title="" id="7331_2370" name="radio_2370"  value="1">
      Sim

        27.3.1 Agente 1
        <input type="text" title="" id="7331_2371" name="text_2371"  class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

        27.3.2 Agente 2
        <input type="text" title="" id="7332_2371" name="text_2371"  class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

        27.3.3 Agente 3
        <input type="text" title="" id="7333_2371" name="text_2371"  class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

      <input type="radio" title="" id="7334_2370" name="radio_2370" value="2">
      Exame não realizado

        27.3.1 Agente 1
        <input type="text" title="" id="7331_2371" name="text_2371"  class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

        27.3.2 Agente 2
        <input type="text" title="" id="7332_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

        27.3.3 Agente 3
        <input type="text" title="" id="7333_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

      <input type="radio" title="" id="7405_2370" name="radio_2370" value="3">
      Não se aplica

Na imagem acima está correto, porém se selecionar um input que também tenha filhos, deve fechar todos os outros, assim como abaixo.

O mesmo deve acontecer caso selecione um Radio Button que não tem filhos, fechar todos os inputs filhos do grupo. Assim como na imagem abaixo.

Eu fiz esse código mas não tive sucesso...
O problema maior é que deve ser dinâmico, deve funcionar em todos os radiobuttons, por isso usei o evento de click.
$('input[type="radio"]').on("change", function() {
  var element = $(this);
  var pais = element
    .parent()
    .parent()
    .parent(); // SUBIR ATÉ A DIV SUPERIOR DO GRUPO
  var filhos = pais.children(".linha-opcao-resposta"); // CAPTURAR AS DIVS FILHAS
  var netos = element
    .parent()
    .parent()
    .children(".linha-opcao-resposta"); // CAPTURAR OS INPUTS FILHOS DO RADIO BUTTON

  if (netos.length > 0) {
    for (let i = 0; i < netos.length; i++) {
      netos[i].style.display = "block";
    }
  } else {
    for (let i = 0; i < filhos.length; i++) {
      netos = filhos[i].children();
      alert(netos.length);
      for (let j = 0; j < netos.length; j++) {
        netos[j].children(".linha-opcao-resposta").style.display = "none";
      }
    }
  }
});

Comment: Começarei recomendando que estude CSS urgentemente. Estilos *inline* são péssimos para dar manutenção, além de deixar o código poluído.
Comment: Eu tenho noção plena do CSS mas na atual situação do código, não tenho condição de aplicar CSS dessa forma... é meio necessário o *inline*, essa aplicação é VB.NET e esse código roda via WebBrowserForm, daí fica um pouco mais complicado eu diria.
Answer: EDIT
Como vc falou que tem que ser dinâmico sem precisar usar ID, fiz um modelo com CSS. Tive que mexer pouca coisa no estrutura do HTML, apenas coloquei os campos que vão aparecer dentro da div "pai", assim eu faço uma regra CSS quando o radio:button está :checked
Veja o exemplo como ficou:

input[type="radio"] ~ div {
    display: none;
}
input[type="radio"]:checked ~ div {
    display: block;
}

        27.3 Presença de agentes específicos na citologia oncótica?
        <input type="hidden" title="" id="7329_2338" name="hidden_2338">

            <input type="radio" title="" id="7330_2370" name="radio_2370" value="0">
            Não

            <input type="radio" title="" id="7331_2370" name="radio_2370" value="1">
            Sim

                    27.3.1 Agente 1
                    <input type="text" title="" id="7331_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.2 Agente 2
                    <input type="text" title="" id="7332_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.3 Agente 3
                    <input type="text" title="" id="7333_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

            <input type="radio" title="" id="7334_2370" name="radio_2370" value="2">
            Exame não realizado

                    27.3.1 Agente 1
                    <input type="text" title="" id="7331_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.2 Agente 2
                    <input type="text" title="" id="7332_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.3 Agente 3
                    <input type="text" title="" id="7333_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

            <input type="radio" title="" id="7405_2370" name="radio_2370" value="3">
            Não se aplica

Se vc quiser usar com jQuery
Cara eu não entendo muito de JS, mas com jQuery fiz esse modelinho bem simples, talvez não seja a melhor forma de escrever o JS, e pode ser que alguém vai saber te responder com um código mais enxuto e que faz a mesma coisa.
Mas aqui tem um exemplo que pode funcionar pra vc, sem precisar de usar ID

$(document).ready(function(){
   $("input[type='radio']").click(function(){
      $('.divOculto')
      .removeClass("show");
      $(this)
      .closest('div')
      .find('.divOculto')
      .addClass("show");
   });
});
.divOculto {
    display: none;
}
.show {
    display: block;
}

        27.3 Presença de agentes específicos na citologia oncótica?
        <input type="hidden" title="" id="7329_2338" name="hidden_2338">

            <input type="radio" title="" id="7330_2370" name="radio_2370" value="0">
            Não

            <input type="radio" title="" id="7331_2370" name="radio_2370" value="1">
            Sim

                    27.3.1 Agente 1
                    <input type="text" title="" id="7331_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.2 Agente 2
                    <input type="text" title="" id="7332_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.3 Agente 3
                    <input type="text" title="" id="7333_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

            <input type="radio" title="" id="7334_2370" name="radio_2370" value="2">
            Exame não realizado

                    27.3.1 Agente 1
                    <input type="text" title="" id="7331_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.2 Agente 2
                    <input type="text" title="" id="7332_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

                    27.3.3 Agente 3
                    <input type="text" title="" id="7333_2371" name="text_2371" class="rfdRoundedCorners rfdDecorated rfdInputDisabled">

            <input type="radio" title="" id="7405_2370" name="radio_2370" value="3">
            Não se aplica

Comment: ótimo, o problema é que deve ser dinâmico, deve funcionar em todos os radiobuttons da aplicacao, entao nao posso usar id's unicos dessa forma. Eu pensei em fazer um **for** para varrer o grupo
Comment: @CarlitoMurta estou bolando uma forma de fazer com CSS, acho que vai facilitar.
Comment: @CarlitoMurta fiz uma opção só com CSS da uma olhada no **EDIT** que fiz na minha resposta
Comment: Utilizei sua sugestão, voce usou alguma framework ou preprocessador css? nao funcionou pra mim
Comment: @CarlitoMurta não precisa de nenhum processador de CSS, repare que eu tb mudei o HTML como expliquei na resposta. Tive que colocar os inputs que vão aparecer dentro da div pai. Repare que editei novamente a resposta e coloquei uma opção de jQuery bem mais simples, e que não depende de ID para funcionar! Qualquer dúvida fala aqui que tento te explicar. Só o JS que sou meio limitado... mas qq coisa no CSS é só perguntar
Comment: deu tudo certinho depois de modificar o html!, valeu cara, me salvou! e com 7 linhas de CSS hahaha
Comment: @CarlitoMurta boa garoto, boa sorte com o projeto


Mutiple options get selected in RadioGroup

Question: I have made a Radio Group with some Linear Layouts (having TextViews and RadioButtons in them) in it. I am able to select more than one options is this group which I don't want. How do I remove this thing?
<code>     <RadioGroup
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:id="@+id/rg">

                       <LinearLayout
                           android:layout_width="match_parent"
                           android:layout_height="wrap_content"
                           android:id="@+id/ll1"
                           android:orientation="horizontal">

                           <RadioButton
                               android:layout_width="fill_parent"
                               android:layout_height="wrap_content"
                               android:layout_marginTop="10dp"
                               android:text="Option1"
                               android:textColor="#ffffff"
                               android:textSize="15sp"
                               android:layout_weight="0.5"
                               android:checked="false"
                               android:id="@+id/rbOption1" />

                           <TextView
                               android:layout_width="fill_parent"
                               android:layout_height="match_parent"
                               android:layout_weight="1.5"
                               android:id="@+id/oc1" />

                       </LinearLayout>

                       <LinearLayout
                           android:layout_width="match_parent"
                           android:layout_height="wrap_content"
                           android:id="@+id/ll2"
                           android:orientation="horizontal">

                           <RadioButton
                               android:layout_width="fill_parent"
                               android:layout_height="fill_parent"
                               android:id="@+id/rbOption2"
                               android:layout_marginTop="10dp"
                               android:text="Option2"
                               android:textColor="#ffffff"
                               android:textSize="15sp"
                               android:layout_weight="0.5"/>

                           <TextView
                               android:layout_width="fill_parent"
                               android:layout_height="fill_parent"
                               android:layout_weight="1.5"
                               android:id="@+id/oc2" />

                       </LinearLayout>
</RadioGroup>
</code>
Comment: does [this](http://stackoverflow.com/a/16811546/5647037) solve it for you?
Answer: Unfortunately, RadioGroup works only when RadioButtons are its direct children. You'll have to either implement the behavior yourself or redesign the layout.


Mechanics of and intuition behind probabiliity

Question: Suppose in a given experiment that an event $E$ will occur with probability $p$; if the experiment is staged only once, then we know from the previous statement that the probability that the event $E$ occurs is given by $p$.
Now, say we stage the experiment $n$ times (where $n \to \infty$ and experiments are independent); intuitively (and mathematically, too, I guess), because the probability is constant across "stagings" of the experiment, I have deduced (perhaps erroneously) that the probability (before any staging has taken place) of the event $E$ occurring once across $n$ stagings is also given by $p$.
However, this seems to conflict with the frequentist definition of probability, paraphrased by the following:
Given  $p = \frac{x}{y}$, as $n \to \infty$, it should be expected that, on average, event $E$ will occur $x$ times per every $y$ iterations of the experiment.
Consider an example:
A man with a deck of cards (52 in total, with 13 of each suit) provides you with the following (unrealistic) proposition:
You have $n$ chances (i.e. $n$ draws with replacement and reshuffling, where $n \to\ \infty$) to randomly select any card from the the suit of spades. If you're successful, you acquire the man's life savings; however, if you're unsuccessful, he acquires yours.*
*(In order to eliminate complex scenarios, assume both life savings are equal and that you are risk neutral (i.e. indifferent to risk).)
The first interpretation above suggests that the probability of selecting any card from the suit of spades across $n$ draws remains at $p = \frac{13}{52} = \frac{1}{4}$; this implies that the chance if this event occurring is significantly less than the chance of this event not occurring ($\frac{1}{4} < \frac{3}{4}$); hence you should not take this bet.
The second interpretation suggets that because $n \to \infty$, we should expect the event to occur, on average, once every $4$ times; you have $n$ chances (where $n \to \infty \implies n >> 4$). We should take this bet as the event will (almost?) definitely happen many times across $n$ draws.
It should also be noted that the first interpretation suggests that the event may never occur (in fact, it is more likely that it won't occur!), whilst the second interpretation suggests that as $n \to \infty$, the event will occur infinitely many times!
I suppose my first question should be: In the scenario above (replacement, independence, etc.), is my reasoning that the probability $p$ of event $E$ occurring across $n$ stagings constant, and, hence, equivalent the probability of the event occurring across one staging of the experiment correct?
Secondly, assuming the answer to the previous question is affirmative, is the perceived conflict presented in the above scenario founded on sound principles? If so, how should we progress in the presence of this conflict?
Answer: The intuition you express in your second paragraph

Now, say we stage the experiment n times (where n→∞ and experiments
  are independent); intuitively (and mathematically, too, I guess),
  because the probability is constant across "stagings" of the
  experiment, I have deduced (perhaps erroneously) that the probability
  (before any staging has taken place) of the event E occurring across n
  stagings is also given by p.

is, indeed, erroneous. That is the probability of the event occurring on any one staging. The probability of it occurring at least once does tend to 1. For probability p with k stagings, the probability is $(1-p)^k$.
Comment: Perhaps "infinity" should read "one"?
Comment: Indeed it should, I will correct that.
Answer: You won't go very far with this typical textbook interpretation of probability, because it is circular: if the probability of an event is a real number that is likely to be close to the fraction of occurrences of the event in a very long series of repetitions of some experiment, how can we possibly interpret what likely means without resorting to some previous definition of probability? You have two ways to explore this question: 1) Look for interpretations of probability based on concepts such as algorithmic complexity; in this case, be prepared to deal with very subtle problems in the Foundations of Mathematics; you probably can't enter this field of research without a solid background in Mathematical Logic; 2) Do it the Bayesian way, either with a construction like the one in DeGroot's Optimal Statistical Decision, or with a Dutch Book argument, as described in Schervish's Theory of Statistics. This other question may be helpful.


Custom adapter button onClick() does not change button text?

Question: I have a custom array adapter for my Android project. I have added a button to my layout and on click of that button, I would like to have it change the text on the button and also the test TextView, however, with my current code, it does not do that....why is this? Am I missing something? Here is my code:
Adapter:
public class JobAdapter extends ArrayAdapter<Job> {
    private final Context context;
    private final ArrayList<Job> jobs;
    private final int layoutResourceId;
    private ExpandableTextView desc = null;
    private Button expand = null;
    private TextView test = null;
    private boolean isExpanded = false;

    public JobAdapter(Context context, int layoutResourceId, ArrayList<Job> jobs) {
        super(context, layoutResourceId, jobs);
        this.context = context;
        this.jobs = jobs;
        this.layoutResourceId = layoutResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder = null;
        String pay, hrs;
        final Bundle fragmentParams = new Bundle();

        //LayoutInflater inflater = (LayoutInflater) context.getSystemService((Activity.LAYOUT_INFLATER_SERVICE));
        LayoutInflater inflater = LayoutInflater.from(context);

        if (view == null) {
            view = inflater.inflate(layoutResourceId, parent, false);

            holder = new ViewHolder();
            desc = (ExpandableTextView)view.findViewById(R.id.tv_JobDesc);
            test = (TextView) view.findViewById(R.id.test);
            expand = (Button) view.findViewById(R.id.btn_descExpand);

            view.setTag(holder);
        } else {
            holder = (ViewHolder)view.getTag();
        }

        Job j = jobs.get(position);

        test.setText("testing1");

        //when user clicks the expand/collapse button, expand or collapse the description field
        expand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                expand.setText("test");
                desc.toggle();
                test.setText("testing2");

            }
        });

        return view;
    }

    static class ViewHolder
    {
        TextView title;
        TextView payrate;
        TextView dateRange;
        TextView workinghrs;
        TextView location;
        TextView companyname;
        ExpandableTextView desc;
        TextView experience;
        TextView equipment, test;
        Button apply, dismiss, expand;
    }
}

Layout:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/test"
        android:background="@color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="@color/laborswipe_darkgray"
        android:textAlignment="center"
        android:text="ABC Company"
        android:layout_gravity="center_horizontal|left"
        android:paddingLeft="10dp" />

    <at.blogc.android.views.ExpandableTextView
        android:id="@+id/tv_JobDesc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdfaa
        \n aaaaaaaaa
        \n aaaaaaa
        \n aaaaaaa
        \n aaaaaaaaaaa
        \n aaaaaaaaa
        \n aaaaaaaaaa
        \n aaaaaaaaa
        \n aaaaaaaa"
        android:maxLines="2"
        android:ellipsize="end"
        app:animation_duration="1000"/>

    <Button
        android:id="@+id/btn_descExpand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="expand"/>

</LinearLayout>

Any ideas why the onClick() does not change either the textview text or the button text? I can't figure out what I am doing wrong.
Printing a log message when the button is clicked works, I just can't edit the properties of the controls in the layout at all from the button click.
Thanks!
EDIT:
Current onCLick code:
holder.expand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.expand.setText("testing");

                holder.desc.setMaxLines(15);
                holder.test.setText("testing2");

            }
        });

Comment: what is displayed on button "expand" or "text" ?
Comment: By default the button displays "expand" then when it is clicked I want it to display "test".
Comment: comment this // View view = convertView; and run your code again
Answer: I think variables desc,expand, text should be holder variables not adapter variables. In current situation You are overriding them on every getView method run, so only last row will be clickable ( it will override all previous views in variables ).
Comment: Thanks! I have tried to make them holder variables but I get the "Variable 'holder' is accessed from inner class, must be declared final." If I declare the variables as final in the holder, then I cannot assign values to them...is there a way I can get around this?
Comment: Why You holder is static? Change it to normal class and add public to parameters.
Comment: @user2573690 helped?
Comment: Yeah, that seems to allow me to change the text. One more question, from that same onClick, if I try to setMaxLines() for the textview, that does not work after the public change.
Comment: Public change has no right to be source of this problem. Copy current onclick code.
Comment: Added the onClick() code to the original post. Thanks for the help!
Comment: It seems right code, for sure holder.desc is right view? Maybe problem on findViewById?
Comment: And next thing, are You sure ExpandableTextView has such method, and it working as You aspect?
Comment: I tried to change the ExpandableTextView to a regular TextView and call the setMaxLines() method but it still does not expand the textview, I have about 8 lines of text in it, so it should expand..
Comment: @user2573690 i think this is another problem, this question has little related with current problem with TextView


Nonparametric ANOVA with interaction?

Question: Is there any nonparametric version of ANOVA able to deal with multiple factors AND evaluate their interaction(s)?
If the interactions are really impossible to evaluate, is there any generalization of the Friedman test to more than two factors?
Answer: One problem is that distribution-free procedures typically rely on being unaffected by monotonic transformation to preserve their distribution-free property.
On the other hand, interaction is affected by exactly that - monotonic transformation can convert no interaction to interaction, or strong positive interaction to strong negative - or any other combination.

Here's an example done in R:
y=c(2.2239, 3.9927, 3.6603, 1.9891, 2.512, 3.1115, 2.3917, 2.8291, 3.7057, 1.987,
   2.6568, 3.9810, 2.1337, 2.1669, 3.3876, 2.9638, 2.9076, 4.377, 2.1319, 3.5533,
   3.8489, 1.9695, 3.271, 4.0011, 3.1308, 4.0777, 4.9145, 3.5395, 4.3199, 5.0562,
   2.6234, 4.5491, 5.2568, 3.1569, 3.3236, 5.3585, 3.1803, 4.3212, 5.5523, 2.6577,
   3.7098, 4.4573, 3.2331, 4.0703, 4.5332, 2.5392, 4.2835, 4.9115, 4.6319, 5.3323,
   5.6393, 4.222, 5.5367, 5.5239, 3.8044, 5.6456, 5.2564, 4.8723, 4.9721, 6.1518,
   4.6626, 5.1306, 6.1608, 4.012, 4.6824, 6.1099, 4.4195, 4.9327, 6.0989, 3.6916,
   5.8146, 5.6579)

xa = rep(1:3,24)
xb = rep(1:3,each=24)

(Note that here xa and xb are numeric, not factors, but you can get the same issue with factors.)
summary(lm(y~xa*xb))
summary(lm(log(y)~xa*xb))
summary(lm(exp(y)~xa*xb))

The interaction line from each summary is:
            Estimate   Std. Error  t value   Pr(>|t|)
xa:xb       4.882e-06   7.217e-02   0.000    1.000           (original)
xa:xb       -0.05499    0.02028    -2.712    0.00846         (log-scale)
xa:xb        60.322     9.713       6.210    3.63e-08        (exp-scale)

Note that the interaction changed from 0 to significant negative (at the 1% level) to
significant positive (at any sensible level). Larger samples could achieve whatever significance level was desired. Since each of the results can be obtained from any of the others by a simple monotonic transform, we see that taking ranks could destroy the interaction on the scale you have - it might reverse it or make it 0 or give you interaction where there was none.
That doesn't mean distribution-free analysis isn't possible, it's just not as straightforward as it might seem. In particular, you'll want to avoid any transformation of that data that may impact the interaction.

You can perhaps do something with permutation tests, for example, which are distribution free while not playing with the scale of the data.
A common suggestion I have seen is to consider ordinal logistic regression, which generalizes the Kruskal-Wallis type approach, and can handle factorial designs. I don't know that it necessarily avoids this issue though -- I haven't worked through it.
There are other possibilities, some quite simple, but better advice really comes down to why you think you need a specifically nonparametric procedure.

Edit: see also here and here, which says something similar.
Comment: Ordinal regression for continuous or ordinal $Y$ generalizes the concept of rank methods, through the use of semiparametric models.  Though one never really knows on what scale interaction should be analyzed, interaction tests from e.g. the proportional odds model are worth a look.  The R `rms` package's `orm` function makes it efficient to do ordinal regression on continuous $Y$ by efficiently handling thousands of intercepts.

Nonparametric ANOVA with interaction?


Django - reload only body page using block not refresh whole page

Question: base.html

        {% include 'HEADER.html' %}

        {% include 'SIDEBAR.html' %}

        {% block content %}
        {% endblock %}

        {% include 'FOOTER.html' %}

        {% block extrajavascript %}
        {% endblock %}

HEADER.html:

    Resource Monitor

            Toggle navigation

Home (current)

 PC information

??? ???

???? ???

???? ????

SDWT ????

??? ?? ??

??? ?? ID? ??

Agent ????

                Email ?? ??

??? ??

??? ??

When I click header tab menu, I want to reload only
 {% block content %}
{% endblock %}
 not whole pages.. but now It reloaded the whole page..
There are formbox in my side bar and there are some values which user input. so I don't want to loose my user input by refresh whole page. Is there any solution..?
Answer: You need javascript AJAX api to get the content and change the html content using javascript DOM api if you need "without reload" function.

Django or any application server or http webserver works in a
  request-response way, when a response is returned to the browser, the
  server has no control to the client.
Comment: Thanks! I do return json at wiew.py and reload only div using ajax,


Why is the statement in finally block still executed?

Question: public class ADaemon implements Runnable {
@Override
public void run() {
    try {
        System.out.println("Starting ADaemon");
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        System.out.println("Exiting via InterruptedException");
    } finally {
        System.out.println("This should always run?");
    }
}

public static void main(String... args) {
    Thread t = new Thread(new ADaemon());
    t.setDaemon(true);
    t.start();
}}

result
Starting ADaemon
Exiting via InterruptedException
This should always run?

I tried to the code sample from "Thinking in Java" 4th edition, but it did't get the result as described in the book, the finally block is still being executed, why is that so? BTW I am using oracle jdk 10.0.1.
-------------update----------
It seems there is something run with my maven-runner plugin, I disabled it and it just get the same result as described in the book.
Comment: As far as I know, `finally` is supposed to run even if there is an exception.
Comment: it's surprising to see that an interrupted exception was thrown here. i can't reproduce this in java 8, it behaves as Bruce says. is this openjdk?
Comment: ***Because*** it's in a `finally` block. That's what they're for.
Comment: @Jai but in the book, it said as you set the thread to daemon, the finally block may not be executed.
Comment: @NathanHughes it's oracle jdk 10.0.1.
Comment: The book actually said "You should be aware that daemon threads will terminate their run( ) methods without executing finally clauses" to describe the case. The previous one is my paraphrase.
Comment: The book actually said "You should be aware that daemon threads will terminate their run( ) methods without executing finally clauses" to describe the case. The previous one is my paraphrase.
Answer: You say that the book says:

"the finally block may not be executed".

(Emphasis added.)
That is not the same as saying:

"the finally block will not be executed".

I think that the book is implying that it is unspecified (and possibly JVM specific) whether daemon thread gets an interrupt (or something) when the application exits.
Certainly, if the daemon thread caught and ignored the "interrupted" exception as follows, then I would expect that the finally to never be executed.
public class ADaemon implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("Starting ADaemon");
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    System.out.println("Caught InterruptedException");
                }
            }
        } finally {
            System.out.println("This should always run?");
        }
    }

    public static void main(String... args) {
        Thread t = new Thread(new ADaemon());
        t.setDaemon(true);
        t.start();
    }
}

I would expect similar behavior if the daemon thread was not executing interruptible code.
Comment: If that's what the book says, it is (technically) incomplete / inaccurate, since the actual behavior *may* depend on what the daemon thread will do in response to an interrupt.  (Lesson: books can be wrong.  Only trust what the specifications say.)
Comment: The book originally said "You should be aware that daemon threads will terminate their run( ) methods without executing finally clauses" to describe the case, my expression may be a little ambiguous here. But I think the book is trying to say, if the the last non-daemon thread terminates, then it will end all the daemon thread regardless whether their finally block is executed.
Comment: Thanks, but have u got any further readings about what the daemon thread will do in reponse to an interrupt?
Comment: The `Thread` javadocs would be a good place to start.  (The behavior is the same as for a non-daemon thread.)
Comment: Thx. BTW it seems jdk 8 and jdk 10 have different results, so perhaps it has some relations with version change.
Answer: This should always run? Yes. Unless the JVM actually halts the finally block is guaranteed to be entered. Something like
System.exit(-1);

in the catch block will prevent that. If that is what you want. It will also stop the JVM! The book is warning you that if all other threads are completed, the daemon thread may never be scheduled before the JVM terminates. You are directly calling start(). Consider using
SwingUtilities.invokeLater(t);

It probably won't run unless you remove t.setDaemon(true);
Comment: But in the book, it said "Daemon threads will terminate their run() methods without executing finally clauses", the result in the book is actually "Staring Adaemon" without executing the finally. Why is my code execution result different from the one in the book?
Comment: The result now is "Starting ADaemon
This should always run?", it didn't catch the exception, but finally block is still being executed.
Comment: @AlanLian The JVM ends normally when all non-daemon threads have ended. At that time, the JVM will exit, without waiting for daemon threads to end, so the call stack of daemon threads are not unwound and therefore `finally` blocks on the stack are not executed. However that is when the JVM ends, if the code in the daemon thread returns, then of course `finally` blocks are exeucted, because they have to, in order for the call stack to unwind.
Comment: @Andreas could explain the detailed difference between the daemon threads return and those don't? I can't get the difference here
Comment: @Alan: it's just that it may be a race condition whether the daemon thread finishes normally or the jvm dies.  but your 1sec sleep time seems like it gives plenty of time for the main thread to terminate.
Answer: The finally block is a powerful (and dangerous if used incorrectly) tool which will almost always run after the try or catch block completes (despite some small cases which are highlighted above).
Look at this example:
try{
  throw new Exception();
}catch(Exception e){
return;
}finally{
System.out.println("Shouldn't run?");
}

If this was in a method, the finally block would still be executed (never do this as it is a bad practise). It is designed to perform any cleanup despite the result of the operation you did such as closing streams (which can now be done automatically through paranthesis in the statement 'try').
Comment: Actually I am asking why there is a difference between my result, and the result in the book. Thanks for answer anyway.
Comment: That's what I'm trying to state, it will run in most cases, even in your situation
Comment: But as Nathan Hughes said in the comment, this sample in jdk 8 produce the result same as Bruce says, why is mine different?
Comment: @AlanLian The obvious answer is that Oracle has changed something between Java 8 and Java 10.
Comment: @Powerlord u are right. But I want to know what change causes the difference.


add multiple columns programmatically from individual criteria/rules

Question: I would like to add multiple columns programmatically to a dataframe using pre-defined rules. As an example, I would like to add 3 columns to the below dataframe, based on whether or not they satisfy the three rules indicated in code below:
     #define dataframe
df1 = pd.DataFrame({"time1": [0, 1, 1, 0, 0],
                    "time2": [1, 0, 0, 0, 1],
                    "time3": [0, 0, 0, 1, 0],
                    "outcome": [1, 0, 0, 1, 0]})

     #define "rules" for adding subsequent columns
rule_1 = (df1["time1"] == 1)
rule_2 = (df1["time2"] == 1)
rule_3 = (df1["time3"] == 1)

     #add new columns based on whether or not above rules are satisfied
df1["rule_1"] = np.where(rule_1, 1, 0)
df1["rule_2"] = np.where(rule_2, 1, 0)
df1["rule_3"] = np.where(rule_3, 1, 0)

As you can see my approach gets tedious when I need to add 10s of columns - each based on a different "rule" - to a test dataframe.
Is there a way to do this more easily without defining each column manually along with its individual np.where clause?  I tried doing something like this, but pandas does not accept this.
 rules = [rule_1, rule_2, rule_3]
 for rule in rules:
     df1[rule] = np.where(rule, 1, 0)

Any ideas on how to make my approach more programmatically efficient?
Comment: The main problem is that in your loop, `rule` is a `pd.Series` not a string which is why you can't use it as a column name
Answer: The solution you provided doesn't work because you are using the rule element as the new dataframe column for the rule. I would solve it like this:
rules = [rule_1, rule_2, rule_3]
for i, rule in enumerate(rules):
    df1[f'rule_{i+1}'] = np.where(rule, 1, 0)

Comment: Awesome, universal solution - that would work regardless of the way I am naming my columns or rules! Thank you Juan!
Comment: `[f'rule_{i+1}' for i in range(100)]`?
Comment: Any way I can programmatically add rule_1, rule_2, rule_3....rule_100 into a list of rules?
Answer: Leverage pythons f strings in a for loop. They are good at this
#Create a list by filtering the time columns
cols=list(df1.filter(regex='time', axis=1).columns)

#Iterate through the list of columns imposing your conditions using np.where
for col in cols:
     df1[f'{col}_new'] = df1[f'{col}'].apply(lambda x:np.where(x==1,1,0))

Answer: I might be oversimplifying your rules, but something like:
rules = [
    ('item1', 1),
    ('item2', 1),
    ('item3', 1),
]

for i, (col, val) in enumerate(rules):
    df[f"rule_{i + 1}"] = np.where(df[col] == val, 1, 0)

Answer: If all of your rules check the same thing, maybe this could be helpful: unstack the relevant columns and check the condition on the Series and convert back to DataFrame with unstack:
df1[['rule1','rule2','rule3']] = df1[['time1','time2','time3']].unstack().eq(1).astype(int).swaplevel().unstack()

Output:
   time1  time2  time3  outcome  rule1  rule2  rule3
0      0      1      0        1      0      1      0
1      1      0      0        0      1      0      0
2      1      0      0        0      1      0      0
3      0      0      1        1      0      0      1
4      0      1      0        0      0      1      0


Segmentation fault (core dump) in c

Question: I have a code which will read a csv file and save the data in the buffer. But i am getting segmentation fault core dump as the status error.
The contents of csv files  are
<code>TimeStamp   BlockSeqNum SeqNum  X-axis  Y-axis  Z-axis
4294967295  0   0   27  20  -4
4294967295  0   1   48  11  -13
4294967295  0   2   45  0   -7
4294967295  0   3   38  -9  -2
4294967295  0   4   34  -42 -28
4294967295  0   5   -29 35  -35
4294967295  0   6   -3  -46 0
4294967295  0   7   0   2   -10
4294967295  0   8   6   113 -32
4294967295  0   9   -4  20  27
4294967295  0   10  -14 -15 -19
4294967295  0   11  23  51  -19
4294967295  0   12  10  34  1
4294967295  0   13  -7  -2  15
4294967295  0   14  13  -5  -30
4294967295  0   15  -24 30  51
4294967295  0   16  -18 39  -45
</code>
My code to read the and parse the file is
<code>#include<stdio.h>
#include<stdlib.h>

struct pattern_buffer {    //structure to store the contents of csv files
    unsigned int x[1024];
    unsigned int y[1024];
    unsigned int z[1024];

}Data_buffer;

int main(void)
{
    char buffer[1024];

    char *record,*line;
    int x1=0,y1=0,z1=0,linecount=0; //linecount is used to check weather 1024 rows have been read or not

    int n=0;

    FILE *fstream = fopen("files.csv","r");
    if(fstream == NULL)             //check file
    {
        printf("\n inside .so \n unable to open csv files \n");
        return 0;
    }
    printf("\n Sensor values are \n");

    line=fgets(buffer,sizeof(buffer),fstream);  //skip first line (weather it will skip the first line

    while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL   &&  linecount<1024)
    {
        record=strtok(line,",");  //skip first column
        while(record!= NULL)
        {
            //record=strtok(NULL,",");   //skip second column
            record=strtok(NULL,",");     //skip third column
            record=strtok(NULL,",");      //get x axis
            Data_buffer.x[x1++]=atoi(record);
            record=strtok(NULL,",");         //get y axis
            Data_buffer.y[y1++]=atoi(record);
            //record=strtok(NULL,",");        //get z axis
            Data_buffer.z[z1++]=atoi(record);

        }
        linecount++;
    }
    return -1;
}
</code>
So please specify me weather my logic is correct for skipping first line and reading the csv values .
Comment: Note: there are no comma's in your CSV example. And `-4`is not a valid value for an `unsigned int`.
Comment: No actually it is a  copy of a csv file . it has commas ,  not displayed
Comment: i have used now signed int but still not able to get out put, Same error
Comment: Why don't you use `struct pattern_buffer {
    unsigned int x;
    unsigned int y;
    unsigned int z;
}Data_buffer[1024];` ; keeping the related `{x,y,z}` together?
Answer: Sorry , i have found the solution for this problem .
i  have not included  in the header file so strtok was not able to parse the token for me. i have checked the value of record while debugging but the record value was zero . so when i researched a lot i came to know that i have not included  which was causing me error .

Segmentation fault (core dump) in c


Interpreting lower order effects not contributing to the interaction terms, when the interaction is significant (C in a regression of A + B + C + A*B)

Question: In a regression including 3 variables, and the interaction of 2 of those variables:

Variable A
Variable B
Variable C
Variable A * Variable B,

where the interaction of Variable A * Variable B is significant, should the regression coefficient for C be interpreted?

Under the tradition that if the interaction term A*B if significant,
the main effects/conditional effects of A and B should not be
interpreted, does this logic of not interpreting the main effects
apply to any variables in the model not present in the interaction
term?
Or should the coefficient for Variable C be interpreted since it was
not included in the interaction term?

If so, how should C be interpreted, if significant? What is the meaning of it?

How does the presence of C effect the way A*B should be interpreted?
Answer: The answer to your question 2 is that it has the same interpretation as usual. That is to say that it implies that the levels of C are different. Assuming there is no AC and BC interaction that difference is maintained irrespective of the levels of A or B or their combination.
As for your question 3 the answer is no, subject to the same proviso about that being the only interaction.
I think that covers your question 1 as well in passing.
Comment: Thank you very much for your explanation, Professor Dewey.
 I'm afraid I'm new to interactions and am unsure what it means that there are "levels" of C or of A or B? Would it be possible to please elaborate -- it would be greatly appreciated!!
Comment: In terms of interpreting C as usual, do I refrain from interpreting the results for A and B, and then interpret C's coefficient as for every 1-unit increase in C, a beta-increase in Y is expected, after controlling all associated covariates (would this include A, B, and A*B as held constant)?
Then, in interpreting the interaction, do I just do so as with any 2-way interaction, or is there a special protocol for when including a third variable not present in the interaction?
Comment: Yes, and yes there is nothing special to do.


How to programmatically associate a taxonomy term to a field

Question: I'm trying to import user profiles data from a JSON file. Several fields are entity reference to vocabularies.
I'm able to create a new taxonomy term entity in the universities vocabulary bundle using the following code:
$term = Term::create([
  'name' => "University of Bologna",
  'vid' => 'universities',
])->save();

Now I have to link this newly created term to a field contained in Profile Type. I'm testing the following code.
    $values = array(
        'type' => 'profile_type',
        'uid' => 3043,
    );
    $profileStorage = \Drupal::entityTypeManager()->getStorage('profile');
    $profileEntity = $profileStorage->create($values);
    $profileEntity->field_entry_university->appendItem($term);
    $profileEntity->save();

However, this approach doesn't work. How can I fix it?
Answer: appendItem takes an array.
Try $profileEntity->field_entry_university->appendItem(['target_id' => $term->id());
Comment: Is `$profileEntity->save()` called?
Comment: I've edited the code accordingly: it adds the term to the vocabulary, but it doesn't link it to the field.
Answer: EntityInterface::save() returns the status of the save operation, not the entity:
$term = Term::create([
  'name' => "University of Bologna",
  'vid' => 'universities',
])->save();

$term is always 1.
So first assign the newly created entity to $term and then save it:
$term = Term::create([
  'name' => "University of Bologna",
  'vid' => 'universities',
]);
$term->save();

Adding the entity should be no problem then:
$profileEntity->field_entry_university->appendItem($term);

It doesn't matter whether you add the target entity or the target ID.


Colocar botão lado a lado

Question: Olá queria ter um botão de voltar e outro para ir para a análise, quando vou ver ao site eles aparecem sempre em um a baixo e outro em cima.
O meu código é:

<input type="button" name="botao-voltar" value="Voltar">

<input type="button" name="botao-analise" value="Análise">

E eu não como meter lado a lado.
Comment: Remova a tag `` pois ela quebra em parágrafos, ou use css para formatar a largura do parágrafo, mas não é o ideal. Pode trocar o `input` por `button`.
Comment: Ok eu já percebi o que tinha errado. Tinha no primeiro botão começar o paragrafo e acabar no segundo.
Comment: E onde entra o PHP na história?
Comment: @Catarina Silvestre, você já resolveu o problema?
Comment: @Lucas sim já consegui. Obrigado na mesma.
Answer: Tens alguns problemas com o teu código atual:
Elementos dentro da tag de link:
O elemento <button/> não pode estar dentro do elemento  pelo que pode ser lido na documentação em: HTML5 Spec Document from W3C:

Content model: Transparent, but there must be no interactive content descendant.
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).

Que traduzido:

Modelo de conteúdo: transparente, mas não deve haver conteúdos interactivos descendente.
O elemento pode ser envolvido em torno de parágrafos inteiros, listas, tabelas, e assim por diante, até mesmo seções inteiras, desde que não exista conteúdo interativo dentro do mesmo (por exemplo, botões ou outros links).

Fecho das tags
Os elementos
 não estão fechados, motivo pelo qual o teu código não gera o HTML da forma pretendida.
Solução
Podes colocar ambas as hiperligações dentro de um paragrafo e formatar com CSS para obteres o aspeto desejado:

a{
    display:inline-block;
    text-decoration:none;
    padding:6px 4px;
    border:1px solid #ccc;
    background-color:#f2f2f2;
    color:#333;
    font:15px arial, sans-serif;
}
a:hover{
    border-color:#aaa;
}

        voltar

        análise

Answer: Não se aplica uma tag <input> dentro de uma tag  e nesse caso só é necessário por os botões em uma tabela:

        <input type="button" name="botao-voltar" value="Voltar">

       <input type="button" name="botao-analise" value="Análise">

Comment: quem votou contra, dê uma dica melhor, tbm quero aprender.. eu faria assim
Comment: Uma dica(não fui eu que votei), use o conceito tableless. Use tabela para apenas dados.
Answer: Utilize o bootstrap
Basta adicionar seu css e as respectivas classes nos seus componentes.

    <meta charset="utf-8">
    <title>JS Bin</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

    Voltar
    Análise

Live demo
Comment: Acredito que não seja a melhor opção adicionar + de 100kb de CSS só para resolver esse problema
Comment: O bootstrap tem inúmeras funcionalidades que podem ser utilizadas em todo o seu web site, caso queira somente o botão como no caso do exemplo acima, pode customizar somente para o que precisa. Incluindo somente o componente do botão terá apenas 12Kb a mais.
[Customizar meu bootstrap](http://getbootstrap.com/customize/?id=122588e4a82f95f81525)

Colocar botão lado a lado


Is it possible generate a hash of result set using django orm?

Question: I need something like this: How to generate a hash of the result set in Postgress?
Is it possible using django orm?
Does anyone have any reference?
Comment: You can create a custom DB function using the [***`Func` expression***](https://docs.djangoproject.com/en/dev/ref/models/expressions/)
Answer: In the case of Django's User model it will be like below:
<code>from django.contrib.auth.models import User
from django.db.models import Concat, Func, CharField

User.objects.annotate(
    hash=Func(
        Concat('first_name', 'last_name', output_field=CharField()),
        function='md5',
    )
)
</code>
Comment: I think I understand. But... How can I get the hash?
Comment: Let's say that we assigned it to a variable called result. Then it would be `result[0].hash` for the first item.


Tie notes across multiple voices

Question: I'm aware this is an FAQ but I've tried a bunch of commonly-suggested workarounds (\repeatTie, \laissezVibrer, hiding noteheads and/or stems) without success.  What is the easiest way of tying the notes at the end of bar 1 to the beginning of bar 2?
\version "2.18.2"

\score {
  \new Staff {
    \time 4/4
    \clef bass
    \relative c' {
    <bes d f>8. e16 d8
    8
    2
      <<
       { d2 cis2 } \\ { 1 }
      >>
    }
  }
}

Answer: Tricky problem!
This is a very hacked solution, but it's at least a solution:
\version "2.18.2"

\score {
  \new Staff {
    \time 4/4
    \clef bass
    \relative c' {
    <bes d f>8. e16 d8
      <<
        {
          s8 s2 |
          1 |
        }
        \\
        {
          \stemDown
          8 2 |
          \stemUp
          \override NoteColumn.force-hshift = 1.5
          d2 cis2 |
        }
        \\
        {
          \override NoteColumn.force-hshift = 0
          \stemDown
          s8 <a_~ e'^~>2 |
          \override NoteColumn.force-hshift = 0.5
          q1 |
        }
      >>
    }
  }
}

There are probably a few tweaks to clean this up, but unfortunately I'm not in a spot to make those tweaks right now. Hopefully this helps!
Comment: Hacky or not, I'll take it! (I'd played with `force-hshift` but it did nothing at all in my experiments. My first thought on seeing your code, "ah, there shouldn't be a # before the number", turns out not to be why.)
Answer: Ties only work inside a Voice, << ... \\ ... >> implicitly starts two voices named "1" and "2".  The proper way is to just let your main Voice continue:
\version "2.18.2"

\score {
  \new Staff {
    \time 4/4
    \clef bass
    \relative c' {
      <bes d f>8. e16 d8
      8
      2
      <<
        \new Voice { \voiceOne d2 cis2 }
        { \voiceTwo 1 \oneVoice }
      >>
    }
  }
}

Here \voiceOne and \voiceTwo switch to two-voice stem/tie/slur directions while \oneVoice reverts the main voice settings back to the normal settings for a single voice that let those directions depend on the pitch.
However, while this expresses your original intent, it may lead to confusing output in other situations (like transposing this one octave down) since then stem directions in the second voice will flip at the moment the first voice comes in.  So you actually want to have the voices split before that so that the tied over second voice notes don't change character in the middle.  That would be
\version "2.18.2"

\score {
  \new Staff {
    \time 4/4
    \clef bass
    \relative c' {
      <bes d f>8. e16 d8
      << { s8 s2 d2 cis2 } \\
         { 8
           2
           1 }
      >>
    }
  }
}

s is a symbol for skipping the typesetting of music for the given duration.  Of course you could still use the first version (if you like this better) perfectly well and just move its \voiceTwo command from inside of the << ... >> construct forward to the point where you want the visuals to change:
\version "2.18.2"

\score {
  \new Staff {
    \time 4/4
    \clef bass
    \relative c' {
      <bes d f>8. e16 d8
      \voiceTwo
      8
      2
      <<
        \new Voice { \voiceOne d2 cis2 }
        { 1 }
      >>
      \oneVoice
    }
  }
}

Note that I also moved \oneVoice out of the << ... >> construct here
for purely cosmetic reasons so that it pairs better with \voiceTwo.
Also note that << ... >> does not start any new Voice on its own:
it is when \\ is used in its middle that multiple voices get
started.  Otherwise new voices get started only with explicit \new Voice.
Comment: The problem here is that there are only two ties instead of three.

Tie notes across multiple voices


Substituir espaço por nova linha com powershell

Question: Como é possível rodar um arquivo .bat que execute o powershell para substituir espaços por nova linha?
Atualmente tenho este cenário no arquivo run.bat:
set id=1
powershell "(gc %id%_01.txt) -replace '[a-zA-Z]','' | Out-File -encoding ASCII %id%_01.txt"

E este conteúdo no arquivo 1_01.txt
Nome Qualquer
15000 qualquer 14999

O resultado desejado é
15000

14999

Tentei modificar o comando com base em alguns exemplos que vi.
powershell "(gc %id%_01.txt) -replace '[a-zA-Z]','' -replace ' ','`r`n' | Out-File -encoding ASCII %id%_01.txt"

Mas a saída fica errada:
`r`n
15000`r`n`r`n14999

Answer: Conforme consta neste comentário, as aspas simples consideram o texto de forma literal, para fazer o que você quer, utilize aspas duplas:
set id=1
powershell "(gc %id%_01.txt) -replace '[a-zA-Z]','' -replace ' ',"""`r`n""" | Out-File -encoding ASCII %id%_01.txt"

Você pode evitar quebras de linhas desnecessárias no começo do arquivo desta maneira:
set id=1
powershell "(gc %id%_01.txt | Select-Object -Skip 1) -replace '[a-zA-Z]','' -replace ' ',"""`r`n""" | Out-File -encoding ASCII %id%_01.txt"

Referência para Select-Object.
Comment: obrigado, também deu certo desta forma -replace ' ',\"`r`n\"


Return only records where there is a difference in field data

Question: Return only records where there is a difference in FTE or Position title field.
I have a table of employee data with fields employee#, job#, start date FTE and Position. For each employee and job I only want to return records where there is a change in FTE or Position
Record,Employee#,Job#,Start Date,   FTE,Position
1,     1000,    01, 01/01/2011, 100,    A
2,     1000,    01, 01/06/2011, 100,    A
3,     1000,    01, 01/07/2011, 80,     B
4,     1000,    01, 01/08/2011, 80,     C
5,     1000,    01, 01/10/2011, 80,     C
6,     1000,    02, 01/01/2011, 20,     A
7,     1000,    02, 01/05/2011, 20,     A
8,     1000,    02, 01/08/2011, 20,     B

The query should return records 1, 3,4,6,8. (These are the only records were FTE and Position are different from the previous row)
Comment: Record 1 has no previus records, so the first record should be included?
Answer: This looks like a typical self-join scenario: you need to query your table again and see if there's an earlier record with a different FTE or position.
Something like this (no I did not try this):
select later.*
from
  my_table as later,
  my_table as earlier -- same table again
where
  later.employee = earlier.employee -- the self-join
  and
  later.date > earlier.date -- lest we see changes twice
  and
  later.FTE != earlier.FTE -- the change
;

Answer: Depends on what database you are using. If youre using Oracle the the following should do the trick:
SELECT *
FROM (
  SELECT
    record
  , employee#
  , job#
  , start_date
  , fte
  , LAG(fte) OVER (ORDER BY record) previous_row_fte
  , position
  , LAG(position) OVER (ORDER BY record) previous_row_position
  FROM scott.stack_overflow_employee
)
WHERE fte != previous_row_fte
OR position != previous_row_position
OR previous_row_fte IS NULL
OR previous_row_position IS NULL

In the sub-query you can see the use of the Oracle analytical function LAG - A good article on this can be found here. This function is ordering the rows by 'record' and then selecting the previous rows fte or position. In the outer query the WHERE clause is specifying conditions to only return the row if the current fte is not equal to the previous rows fte or the same with position. In addition, due to the way oracle treats NULL values, additional conditions in the WHERE clause also return the row if either value are NULL.
Whilst I have provided a solution, I must question why you are doing this, if given more information there is probably a better way to satisfy your solution, returning every row where there is a change seems like it might be leading on to bigger things. If you can provide more information as to what you are doing then maybe a better solution can be reached.


How to use ggplot2 to plot many regression lines?

Question: I am trying plot 50 simulated regression lines. I can do the plot in base R, but I'm struggling to do it with ggplot2
Simulated data:
library(tidyverse)
set.seed(5)
priors <- tibble(a = rnorm(n = 50, mean = 0, sd = 1),
                 bN = rnorm(n = 50, mean = 0, sd = 1))

Desired output using base R:
plot( NULL , xlim=c(-2,2) , ylim=c(-2,2) )
for(i in 1:50) curve(priors$a[i] + priors$bN[i]*x,
                     from = -2, to = 2, add = TRUE)

How can I do the same thing using ggplot2?
Answer:
priors %>%
    ggplot() +
    geom_abline(aes(intercept =  a, slope = bN)) +
    xlim(-2,2) +
    ylim(-2,2) +
    theme_classic()

Comment: huh, didn't realize `geom_abline` was vectorized~
Answer: geom_abline() adds a line with specified intercept and slope.
gg0 <- ggplot() + scale_x_continuous(limits=c(-2,2)) +
                  scale_y_continuous(limits=c(-2,2))
gg <- gg0
for (i in 1:50) {
    gg <- gg + geom_abline(intercept=priors$a[i],slope = priors$bN[i])
}
print(gg)


parallel instances of Robocopy not getting CPU time

Question: I'm trying to copy large directories from 3 sites. I noticed that robocopy was using < 25% of my CPU, I figured I can spawn 2 more instances in parallel to copy the other 2 sites.
However, I am finding that it seems that the first instance is getting all the CPU and the overall CPU usage is still at 25%. How can I get it to improve overall performance?
I am running with the following options:
<code>Options : *.* /NS /NC /NDL /NFL /S /E /DCOPY:T /COPY:DT /PURGE /MIR /NP /XX /MT:4 /R:5 /W:30
</code>
Comment: [1] what does this have to do with powershell? [*grin*] [2] the `MT` option _defaults_ to `8`. you have set it to `4`. why? [3] the `MT` option is about _multi-threading_, not about multiple processes. if you want multiple _processes_ you will need to use something like the `start` command to fork off a new process OR something like the PoSh `*-Job` or `*-Process` cmdlets.
Comment: I call robocopy from powershell, just in case it matters. I set mt to 4 as I intend to run 3 instances of robocopy and was concerned about too many parallel io calls. I currently am running from 3 separate windows (eventually from 3 scheduled tasks)
Comment: thank you for the info about PoSh and the MT setting ... you likely otta add that AND the script you are using to make the calls to your Question. so, are you getting 25% cpu use with running 3 instances of RC? that seems wrong ...
Answer: Had a similar case, running 2 Robocopy instances. here is what I observed.

My Disk/Ethernet reach their capacity before CPU reaches its own one.
After adding /MT:32, it runs a lot faster than without this option. (default MT:8)

I also turned off anti-virus' file protection, otherwise it consumes more CPU but slows down the copy process.


How to Find TCP Retransmissions while sniffing packets in C

Question: I've written a simple source file that can read pcap files using the libpcap library in C. I can parse the packets one by one and analyze them up to a point. I want to be able to deduce whether a TCP packet I parsed is a TCP retransmission or not. After searching extensively the web, I've concluded that in order to so, I need to track the traffic behaviour and this means also analyzing previously received packets.
What I actually want to achieve is, to do on a basic level, what the tcp.analysis.retransmission filter does in wireshark.
This is an MRE that reads a pcap file and analyzes the TCP packets sent over IPv4. The function find_retransmissions is where the packet is analyzed.
#include <pcap.h>
#include <stdio.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <net/ethernet.h>
#include <string.h>

void process_packet(u_char *,const struct pcap_pkthdr * , const u_char *);
void find_retransmissions(const u_char * , int );

int main()
{
    pcap_t *handle;
    char errbuff[PCAP_ERRBUF_SIZE];
    handle = pcap_open_offline("smallFlows.pcap", errbuff);
    pcap_loop(handle, -1, process_packet, NULL);
}

void process_packet(u_char *args,
                    const struct pcap_pkthdr * header,
                    const u_char *buffer)
{
    int size = header->len;
    struct ethhdr *eth = (struct ethhdr *)buffer;
    if(eth->h_proto == 8) //Check if IPv4
    {
        struct iphdr *iph = (struct iphdr*)(buffer +sizeof(struct ethhdr));
        if(iph->protocol == 6) //Check if TCP
        {
             find_retransmissions(buffer,size);
        }
    }
}

void find_retransmissions(const u_char * Buffer, int Size)
{
    static struct iphdr  previous_packets[20000];
    static struct tcphdr  previous_tcp[20000];
    static int index = 0;
    static int retransmissions = 0;
    int retransmission = 0;

    struct sockaddr_in source,dest;
    unsigned short iphdrlen;

    // IP header
    struct iphdr *iph = (struct iphdr *)(Buffer  + sizeof(struct ethhdr));
    previous_packets[index] = *iph;

    iphdrlen =iph->ihl*4;

    memset(&source, 0, sizeof(source));
    source.sin_addr.s_addr = iph->saddr;
    memset(&dest, 0, sizeof(dest));
    dest.sin_addr.s_addr = iph->daddr;

    // TCP header
    struct tcphdr *tcph=(struct tcphdr*)(Buffer
                                  + iphdrlen
                                  + sizeof(struct ethhdr));
    previous_tcp[index]=*tcph;
    index++;

    int header_size =  sizeof(struct ethhdr) + iphdrlen + tcph->doff*4;
    unsigned int segmentlength;
    segmentlength = Size - header_size;

    /* First check if a same TCP packet has been received */
    for(int i=0;i<index-1;i++)
    {
        // Check if packet has been resent
        unsigned short temphdrlen;
        temphdrlen = previous_packets[i].ihl*4;

        // First check IP header
        if ((previous_packets[i].saddr == iph->saddr) // Same source IP address
            && (previous_packets[i].daddr == iph->daddr) // Same destination Ip address
            && (previous_packets[i].protocol == iph->protocol) //Same protocol
            && (temphdrlen == iphdrlen)) // Same header length
        {
            // Then check TCP header
            if((previous_tcp[i].source == tcph->source) // Same source port
                && (previous_tcp[i].dest == tcph->dest) // Same destination port
                && (previous_tcp[i].th_seq == tcph->th_seq) // Same sequence number
                && (previous_tcp[i].th_ack==tcph->th_ack) // Same acknowledge number
                && (previous_tcp[i].th_win == tcph->th_win) // Same window
                && (previous_tcp[i].th_flags == tcph->th_flags) // Same flags
                && (tcph->syn==1 || tcph->fin==1 ||segmentlength>0)) // Check if SYN or FIN are
            {                                                        // set or if tcp.segment 0
                // At this point the packets are almost identical
                //  Now Check previous communication to check for retransmission
                for(int z=index-1;z>=0;z--)
                {
                    // Find packets going to the reverse direction
                    if ((previous_packets[z].daddr == iph->saddr) // Swapped IP source addresses
                        && (previous_packets[z].saddr ==iph->daddr) // Same for IP dest addreses
                        && (previous_packets[z].protocol == iph->protocol)) // Same protocol
                    {
                        if((previous_tcp[z].dest==tcph->source) // Swapped ports
                            && (previous_tcp[z].source==tcph->dest)
                            && (previous_tcp[z].th_seq-1 != tcph->th_ack) // Not Keepalive
                            && (tcph->syn==1          // Either SYN is set
                                || tcph->fin==1       // Either FIN is set
                                || (segmentlength>0)) // Either segmentlength >0
                            && (previous_tcp[z].th_seq>tcph->th_seq) // Next sequence number is
                                                                     // bigger than the expected
                            && (previous_tcp[z].ack  != 1))  // Last seen ACK is set
                        {
                            retransmission = 1;
                            retransmissions++;
                            break;
                        }
                    }
                }
            }
        }
    }

    if (retransmission == 1)
    {
        printf("Retransmission: True\n");
        printf("\n\n******************IPv4 TCP Packet*************************\n");
        printf("   |-IP Version       : %d\n",(unsigned int)iph->version);
        printf("   |-Source IP        : %s\n" , inet_ntoa(source.sin_addr) );
        printf("   |-Destination IP   : %s\n" , inet_ntoa(dest.sin_addr) );
        printf("   |-Source Port      : %u\n",  ntohs(tcph->source));
        printf("   |-Destination Port : %u\n",  ntohs(tcph->dest));
        printf("   |-Protocol         : %d\n",(unsigned int)iph->protocol);
        printf("   |-IP Header Length : %d DWORDS or %d Bytes\n",
(unsigned int)iph->ihl,((unsigned int)(iph->ihl))*4);
        printf("   |-Payload Length   : %d Bytes\n",Size - header_size);

    }
    printf("Total Retransmissions: %d\n",retransmissions);
}

This approach is based on the wireshark wiki paragraph about Retransmission. I literally have clicked every page google has to offer on how to approach this analysis but this was the only thing I was able to find.
The results I get are somewhat correct, some Retransmissions go unnoticed, I get a lot of DUP-ACK packets and some normal traffic gets through as well (checked with wireshark). I use the smallFlows.pcap file found here and I believe that the results that I should have, should be the same as the tcp.analysis.retransmission && not tcp.analysis.spurious_retransmission filter in wireshark. Which amounts to 88 retransmissions for this pcap.
Running this code yields 45 and I can't understand why.
Sorry for the messy if statements, I tried my best to clean them up.
Comment: I recommend to do a smaller pcap file with retransmit you are not matching, and use gdb to find why you don't match it
Comment: I don't think the sequence number, window, flags, etc. have to be identical in a retransmission. The sender is allowed to add extra data to the retransmission, split up packets into smaller ones, etc. It is *bytes* which are retransmitted, not packets. Bytes are identified based on their sequence numbers.
Comment: (Source: https://tools.ietf.org/html/rfc793 page 42-43 says: "The sending TCP ... may repackage segments on the retransmission queue")
Comment: I've posted a part of the same code on another of my questions, but for another unrelatable problem I had, before encountering this one.
Comment: It's a retransmission if it starts with a repeat of a previous packet. There's no flag for retransmission, you have to match it up with previous packets.
Comment: @user253751 Yes, that's what I do on my code, but there is a mistake on how I check for retransmission.
Answer: For detecting a retransmission you have to keep track of the expected sequence number. If the sequence number is higher than expected the packet is a retransmitted one ( TCP Analysis chapter of the wireshark docs,
https://www.wireshark.org/docs/wsug_html_chunked/ChAdvTCPAnalysis.html )

TCP Retransmission
Set when all of the following are true:

This is not a keepalive packet.
In the forward direction, the segment length is greater than zero or the SYN or FIN flag is set.
The next expected sequence number is greater than the current sequence number

Beside TCP Retransmission this there is also TCP Spurious Retransmission and TCP Fast Retransmission
Basically a retransmission is only necessary if a package is lost.
Analyzing lost segment inconsistency :

source of graphic : http://www.opentextbooks.org.hk/ditatopic/3578
For detecting this type of fault in wireshark the filter tcp.analysis.ack_lost_segment is used. Maybe try to implement this.
(https://serverfault.com/questions/626273/how-can-i-write-a-filter-to-get-tcp-sequence-number-inconsisten)
In wireshark several filters can be applied to capture all types of inconsistencies in sequence numbers i.e. tcp.analysis.retransmission, tcp.analysis.spurious_retransmission and tcp.analysis.fast_retransmission, for the general case of packet loss check for tcp.analysis.ack_lost_segment
https://superuser.com/questions/828294/how-can-i-get-the-actual-tcp-sequence-number-in-wireshark

By default Wireshark and TShark will keep track of all TCP sessions
and implement its own crude version of Sliding_Windows. This requires
some extra state information and memory to be kept by the dissector
but allows much better detection of interesting TCP events such as
retransmissions. This allows much better and more accurate
measurements of packet-loss and retransmissions than is available in
any other protocol analyzer. (But it is still not perfect)
This feature should not impact too much on the run-time memory
requirements of Wireshark but can be disabled if required.
When this feature is enabled the sliding window monitoring inside
Wireshark will detect and trigger display of interesting events for
TCP such as :

TCP Retransmission - Occurs when the sender retransmits a packet after the expiration of the acknowledgement.

TCP Fast Retransmission - Occurs when the sender retransmits a packet before the expiration of the acknowledgement timer. Senders
receive some packets which sequence number are bigger than the
acknowledged packets. Senders should Fast Retransmit upon receipt of 3
duplicate ACKs.

...

source : https://gitlab.com/wireshark/wireshark/-/wikis/TCP_Analyze_Sequence_Numbers
Comment: Thanks for your answer, provided some extra insight on how to search for retransmissions. If I find anything new, I'll try to implement it on my code and see if it changed the outcome.
Answer: The concept of re-transmission is simple:  data that was sent, was sent again.
In TCP, every transmitted byte has an identifier.  If a TCP segment has 5 bytes in it (just a hypothetical example, in reality things are bigger of course), then the identifier of the first segment is the sequence number in the TCP header, +1 for the 2nd segment, ..., +4 for the 5th.
The receiver, when it wants to acknowledge a byte, it just sends an ACK with byte's sequence number +1.  If receiver wants to acknowledge the 5 bytes as in our example, it ACKs the 5th byte, which is seq_num + 4 + 1.  In your case, you do this calculation to get the next expected sequence number seq_num + 4 + 1.
Then, in order to detect if a re-transmission has happened, you simply know it if the same source has sent a TCP segment with a sequence number that's lower than the expected seq_num + 4 + 1.
Say, instead of getting seq_num + 4 + 1 in the next transmitted TCP message, you got seq_num.  This means that the this segment is a re-transmission of the previous one.
But does it mean that this TCP segment, with the re-transmission, only contains re-transmissions?  No.  It can contain re-transmissions from previous segment, plus extra bytes for the next segment.  This is why you need to count the total bytes in the segments to tell how many of the bytes are part of the re-transmissions, and how many are part of new transmission.  As you see, TCP re-transmission is not binary per segment, but can overlap across segments.  Because we are really re-transmitting bytes.  We just store bytes in segments for reducing TCP header's overhead.
Now, what if you got seq_num + 2 + 1?  This is a bit odd because it indicates that the previous segment got partially re-transmitted only.  It basically indicates that it's only re-transmitting from byte 3.  If the segment has only 3 bytes, it re-transmitting 3rd, 4th and 5th bytes (i.e. only the previous segment's bytes).  But if it has, say, 10 bytes, it means that 6th, 7th, 8th, 9th and 10th bytes are new bytes (not re-transmitted).
In my opinion you can only say that a TCP packet is a re-transmission only when it's carrying bytes with identifiers that were sent before.  But as said earlier, this might not be true, as a segment could contain some bytes sent earlier, plus more never sent, hence being a mixture between re-transmissions and new-transmissions.
Comment: Thanks for your answer. It shed some light on TCP communication. I now think that I fully understand why we can never be 100% sure of retransmissions we capture.
Comment: You're welcome.  However, not sure if I said anything that would imply that.  All I said is that each byte has a unique identifier, and if that unique identifier is seen again then it means that it is re-transmitted.  I just said that a given TCP segment can have a mixture of re-transmitted bytes and new bytes.  Unless I'm missing a deeper implication that I am not seeing, I don't see how this implies that re-transmissions cannot be detected by 100%.
Comment: Well after trying to comprehend your answer I tried to implement as a filter only the conditions you state in your answer. Actually the ```Say, instead of getting seq_num + 4 + 1 in the next transmitted TCP message, you got seq_num. This means that the this segment is a re-transmission of the previous one.``` part. In the results then I got as you said most of the TCP-Retransmissions, but I also got Dup-ACKs and Out-Of-Order packets. So what I meant in my comment was that with this filter you get the Retransmissions but other stuff gets through as well.


Relative Entropy and the Wasserstein distance

Question: Can anyone give an informative example of two distributions which have a low Wasserstein distance but high relative entropy (or the other way around)? I find the Wasserstein, defined (for some $p$) as
$$ W_p(\mu,\nu)=\left(\inf_{\pi\in\Pi(\mu,\nu)}\int d^p(x,y)\pi(dx,dy)\right)^{1/p},$$
an intuitive, reasonable way to calculate the distance (or displacement) between two probability measures.
However I'm struggling to see what relative entropy really tells us. I have seen from Sanov's theorem that it can be used to control the exponential rate of decay of the probability of a rare event, however I still haven't got an intuitive feel for how it works and would really appreciate a concrete example so I can compare it against the Wasserstein. I have heard that relative entropy controls the fluctuation of one distribution w.r.t another, however, I haven't yet quite understood what this means.
Comment: does (or how would) this question pertain to the usage of the entropy-regularized optimal transport, which contains both of the measures mentioned in the question title?
Answer: For an example, look at the point masses $\delta_0$ and $\delta_h$ supported at $0$ and $h$, respectively.  The Wasserstein distance between these is $O(h)$, which is small if $h$ is small. But for $h\ne0$ the relative entropy is infinitely large, as the two measures are mutually singular.
For an example the other way around, let $f(x)$ be the density of a $U[0,N]$ rv, and let $$g(x)=(1-\epsilon)f(x)$$ for $x\in[0,N/2]$ and $$g(x)=(1+\epsilon)f(x)$$ otherwise.
The Wasserstein distance is something like $O(N\epsilon)$ (because we have to transfer like $\epsilon$ of the mass over distance $N/2$, but the relative entropy is something like $O(\epsilon)$ because $\log f(x)/g(x) = O(\epsilon)$.  By proper choice of $\epsilon$, we can make the Wasserstein distance big but the relative entropy small.
The intuitive picture I have in mind, is that when one looks at the superimposed graphs of the densities of the two measures (pretending that they have densities) is that the relative entropy measures how much they differ in a vertical sense only, but the Wasserstein metric allows for sideways nudgings of the two graphs.
Comment: Nice answer, thanks!, but surely making epsilon small in your 2nd example makes both the relative entropy and the wasserstien smaller? Still really appreciate any other examples from people:)
Comment: Can anyone help with this related question: Why can't the Wasserstein distance equal $0$ if $\mu = \nu$? https://math.stackexchange.com/questions/3897273


AlertDialog Android "comentario" PopupMenu

Question: Como faço para obter este resultado

os 3 pontos nessa imagem já foi pressionado.
Meu layout
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:layout_margin="3dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imageComent"
        android:background="@mipmap/ic_perfil"
        android:layout_width="53dp"
        android:layout_height="53dp" />

        <TextView
            android:id="@+id/messageComent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="comentario"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_below="@+id/nameComent"
            android:layout_toRightOf="@+id/imageComent"
            android:layout_toEndOf="@+id/imageComent" />

        <TextView
            android:id="@+id/nameComent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/imageComent"
            android:layout_toRightOf="@+id/imageComent"
            android:padding="8dp"
            android:scrollbarAlwaysDrawHorizontalTrack="false"
            android:scrollbarAlwaysDrawVerticalTrack="false"
            android:text="TextView" />

        <ImageView
            android:id="@+id/imageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/messageComent"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:adjustViewBounds="false"
            android:background="@drawable/ic_3pontos"
            android:cropToPadding="false" />
    </RelativeLayout>

</android.support.v7.widget.CardView>

Erro relacionado com a pergunta que tive posteriormente
Problema com PopupMenu Recycleradpter
Comment: Será que é o que entendi. Você quer mostrar o popup com uma lista de opções certo?
Answer: É possível criar um popup com uma lista de opções usando a classe pública PopupMenu adicionado ao Android a partir do level 11. O PopupMenu aparecerá abaixo do item clicado se houver espaço na tela, ou acima se não houver.  Veja abaixo um exemplo básico:
Classe
btn = (ImageButton) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Criando uma instancia do popup
        PopupMenu popup = new PopupMenu(mContext, btn);

        //Inflando o popup usando o arquivo xml
        popup.getMenuInflater().inflate(R.menu.menu_popup, popup.getMenu());

        //Resgata o item clicado e mostra em um Toast
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(GetTextFileByURL.this, "Você clicou em : " + item.getTitle(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        popup.show();
    }
});

Menu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/one"
        android:title="Legal"/>
    <item
        android:id="@+id/two"
        android:title="Bom"/>
    <item
        android:id="@+id/three"
        android:title="Ótimo"/>
    <item
        android:id="@+id/four"
        android:title="Espetacular"/>
</menu>

Imagem
Em muitos casos, um GIF vale mais que 1000 imagens
Comment: exatamente oque eu quero, amanhã boto em pratica, obrigado!
Comment: estou tendo problema com o context, porque estou usando RecyclerView ,RecyclerAdapter.
Comment: @WallaceRoberto isso funciona independente se é RecyclerView ou não. Talvez esteja tendo outro problema. Se quiser criar outra pergunta não tem problema. Você que sabe.
Comment: http://pt.stackoverflow.com/questions/184083/problema-com-popupmenu-recycleradpter
Comment: Minha nova pergunta, Obrigado desde já :)