Is the union of all elements in a $\sigma$-field equal to $\Omega$?

Question: From the textbook I'm reading,

A collection of subsets $\mathscr{F}$ of $\Omega$ is called a
  $\sigma$-field if it satisfies:

empty set in $\mathscr{F}$
if $A_1, A_2, ... \in \mathscr{F}$, then union of $A$'s exist in $\mathscr{F}$
if $A \in \mathscr{F}$, then $A^c\in\mathscr{F}$

and the smallest $\sigma$-field for $\Omega$ is the collection $\mathscr{F} = \{ \emptyset, \Omega \}$.
My question: is the union of all the elements in the $\sigma$-field $\mathscr{F}$ equivalent to $\Omega$?
Comment: Yes, because by the first and third properties $\Omega$ is in the sigma field.
Answer: Trivially, yes, because if $\emptyset\in\mathscr{F},$ then $\emptyset^C=\Omega\in\mathscr{F},$ by the first and third properties you list.
As an aside, the definition that I'm familiar with is

$\mathscr{F}$ is closed under countable unions
$\mathscr{F}$ is closed under countable intersections
$\mathscr{F}$ is closed under complements

and $\mathscr{F}$ is a set of subsets of $\Omega.$ As Juho points out, this difference doesn't matter, though, because we can make intersections into unions using complements: $A_1\cap A_2=(A_1^c\cup A_2^c)^c.$
Comment: $\cap_{i=1}^{\infty} A_i = (\cup_{i=1}^{\infty} A^\mathrm{c}_i)^\mathrm{c}$
Comment: Saying that "$\mathscr F$ is a subset of $\Omega$" is inaccurate: F is a set of subsets of Omega.
Comment: @JuhoKokkala D'oh. That's a good point. Edited.
Answer: To show that two sets $A$ and $B$ contain the same elements, i.e. that $A=B$, it is often convenient to show the equivalent statement $A\subseteq B$ and $B \subseteq A$, so let us do that.
Let $O$ be the union of all the sets in $\mathscr F$. By properties 1 and 3, $\Omega \in \mathscr F$ and, thus, $\Omega \subseteq O$, which proves the first inclusion.
For the second inclusion, it suffices to show that  if $A_i\in \Omega, \forall i \in \mathcal I$, for some index set $\mathcal I$, then $\cup_i A_i \subseteq \Omega$. This is so because $O$ is defined as the union of elements of $\mathscr F$ which are all subsets of $\Omega$ by definition.
I find it illuminating to think about what it would mean if this was not true. Namely, there would exist a point in the union that is not in $\Omega$. But if such a point is in the union, it must, by definition, also be in one of the sets in the union, and all of these are subsets of $\Omega$ so this cannot be. We conclude $O\subseteq \Omega$.

Some notes on this proof:
In the comments @whuber expressed the view that the second inclusion is immediate from the definition of a union of subsets. I don't disagree with this view, but have often found the above thought exercise useful and it does, as far as I can tell, constitute a valid proof of the assertion so I leave it in.
Comment: The second inclusion is immediate and requires no elaboration, because *by definition* the union of subsets of $\Omega$ is a subset of $\Omega$, whence $O\subseteq\Omega$.
Comment: The [Axiom of Union](http://mathworld.wolfram.com/Zermelo-FraenkelAxioms.html) in ZFC asserts (among other things) that $x\in\cup\mathscr{F}$ implies there exists $F\in\mathscr{F}$ for which $x\in F$. But since $F\subseteq \Omega$, *a fortiori* $x\in\Omega$. Therefore $O\subseteq\Omega$.
Comment: I don't understand the point of that comment @whuber. Both directions are "immediate" by definitions. That doesn't mean you don't have to show them. To me, the contradiction argument illuminates exactly what you wrote.
Comment: @whuber Added something to satisfy readers of your opinion too.
Comment: I must be expressing myself unclearly, @whuber, because I feel that's exactly what I wrote, albeit in a less elegant way (without the reference to ZFC). I've edited it now, and will leave it for a while.


Can i store A record of my second level domain directly in TLD zone file (com. for example)?

Question: Can be A record for third-level domain stored directly in TLD zone file, not delegating zone of subdomain with NS record?
What about CNAME record for 2nd domain?
Answer: Yes, so long as no zone cut appears between the TLD and the record that is being defined. A zone cut occurs when a nameserver no longer considers itself authoritative for a subdomain, either through presence of a delegating NS record (i.e. non-apex) or an "overlapping" zone in the server configuration that is more specific.
An authoritative nameserver receiving a delegation is authoritative for all records inside of the delegated namespace. Until it gives that authority away, it owns the entire namespace. Once that authority has been delegated away, it cannot provide an authoritative definition for any records inside of the zone cut. It can offer temporary, non-authoritative suggestions for nameserver IPs in the form of glue records, but that is a separate topic.
Likewise, there is nothing to stop the operators of a TLD from defining catch-call wildcard records barring a contract forbidding them to do so. This is typical with ICANN partnerships, but there are a number of TLDs which have no such restrictions and choose to engage in those practices.

As a side note, based on the context of one of your comments, I suspect you're really asking whether you can get the TLD to define one of these records for you. The answer to that is no.
The first two levels of the DNS hierarchy are managed by domain name registries. There are systems in place that allow DNS registrars to insert and remove delegations from these zones in very controlled ways, but what you are looking to do falls outside of that process. It is an unreasonable administrative burden considering the "shared" nature of those domains.
Answer: Yes, you can, I just tried that on godaddy and route53 with 6 levels (l1.l2.l3.l4.l5.l6.my-domain.com)
Comment: @Alex That's not how you've worded it, though. You asked if it's possible, not whether it's possible for *you* to do it. (i.e. whether they will define one for you) Those are two very different things. :)
Comment: I asked about opportunity to store A record for my-domain.com in com. zone file.
Comment: Can domain registrar offer for me this opprtunity to store `A` record in com. zone file? Or only `NS` record?
Comment: @Alex I've updated the other answer to reflect what you're asking here.


Linq query using group by and having

Question: So, I've been trying to replicate this SQL query:
select COUNT(*) as Total_2_Review
from (
    select processed_image_id, count(*) as Total_Confirm from dbo.history
    where action_id=104
    group by processed_image_id
    having count(*) > 1
) as tbl

with Linq as follows:
var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104)
                    group h by new { h.ActionId, h.ProcessedImageId } into g
                    where g.Key.ActionId > 1
                    select g).Count();

However, I know it should not be right because I am not selecting the actual count greater to 1 in my group clause.
How can I accomplish this SQL query as a LINQ query?
Comment: Why are you grouping by `ActionId` in the Linq when you aren't in the SQL?
Answer: LINQ makes no difference between Where and Having. An appropriate SQL query would be generated based on your placement of the Where clause.
Here is how I would translate your SQL query to LINQ:
var total2Review = secondDb.Histories
    .Where(i => i.ActionId == 104) // This "Where" remains a "where"
    .GroupBy(i => i.ProcessedImageId)
    .Where(g => g.Count() > 1)     // This "Where" becomes "having"
    .Count();                      // This gets the overall count

Comment: Thanks for the explanation
Comment: Can you help me how to get Count on a datefield? I have some student data with their exam dates. I wanna count the dates where the count is greater than two. Date field doesnt have a date.Count()?
Answer: Change Key.ActionId for .Count() in the where after the group by:
var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104)
                    group h by new { h.ActionId, h.ProcessedImageId } into g
                    where g.Count()> 1
                    select g).Count();

Linq query using group by and having


Does the size of the code have any impact on the compile or runtime?

Question: For example, in many programming languages there are two ways to execute a loop. I'm referring to, of course, for loops and while loops. Would these two examples have any differences in compile time or runtime? Does it depend on the programming language?
for(int i = 0; i < 1; i+=0){
//Infinite loop
}
while(true){
//Infinite loop
}

FORTRAN 90 uses two different syntax for a loop
DO
    IF(CONDITION) EXIT
END DO
DO WHILE(CONDITION)
END DO

The first one has more characters, but I'm unsure if more characters means more compile/run time (as insignificant as that time would be).
Answer: "More characters"  really, really isn't the problem.
Compilers and interpreters have t deal with e.g. symbol tables. And the for loop has an extra symbol. That will matter far more. Also, there are two operators, and you need to consider the types of arguments there, all of which add up.
Decent compilers will turn either loop into a no-op though.


Does it matter what object's transform the TransformPoint() method is attached to?

Question: Does it matter what object's transform the TransformPoint() method is attached to, since it's supposed to return a world space position? For example given the following structure:

Obj1

ChildObj1

Obj2

Doing Obj1.transform.TransformPoint(Obj2.transform.position) should return the same thing as ChildObj1.transform.TransformPoint(Obj2.transform.position) regardless of Obj1 and ChildObj1's positions.
Is this correct? If so, what am I missing? Why does the TransformPoint have to be attached to an object's transform?
Comment: The given point is converted from the according transforms local space coordinates into world space coordinates .. so obviously it matters which transform you call it on! Fully  depends ofcourse on your scene setup since it will return the same for all transforms that have the same transformations ....
Answer: TransformPoint takes in a Vector3 and returns a Vector3. All it does is convert a point from localSpace to WorldSpace. Since your example shows that Obj2 is not a child of Obj1, there will likely be confusion.
Let's say the following:

Obj1 is at (5,0,0) in World position
ChildObj1 is at (8,0,0) in World position, which is (3,0,0) in Local position (because it is 3 x-units higher than Obj1.
Obj2 is at (6,0,0) in World position

Here is how the code shakes out for the above scenario:
Vector3 point1 = Obj1.transform.TransformPoint(Obj2.transform.position);
//point1 = (11,0,0)
Vector3 point2 = ChildObj1.transform.TransformPoint(Obj2.transform.position)
//point2 = (14,0,0)

The important thing to note here is that transform.position returns world position. If you were to use transform.LocalPosition where Obj2 is a a root object (localPosition = 0,0,0), then this would be the outcome:
Vector3 point1 = Obj1.transform.TransformPoint(Obj2.transform.localPosition);
//point1 = (5,0,0)
Vector3 point2 = ChildObj1.transform.TransformPoint(Obj2.transform.localPosition)
//point2 = (8,0,0)

Comment: Okay, so using an object's `transform.position` as the arg in `TransformPoint()` is a mistake because `transform.position` is already global. And even more confusingly, root objects have a localPosition of (0,0,0)!
Comment: And from what I gather, the conclusion is that `TransformPoint()` does NOT simply get an object's *global* position, but instead it translates the object's position relative to another object from local to *WorldSpace units*...
Comment: Is it not possible to just get the global coordinates of a vector without using another object as a reference point? I just want to global, absolute, position of a vector that's been through a complex series of transforms.
Comment: A Vector is neither global nor local. A Vector is just a struct to hold data. Transform.position is global, Transform.localPosition is local. Please provide more detail on what you're trying to accomplish by sharing your code that has a series of complex transforms @A__


How fast does the expected value of $\cos$ of a unif dist random variable converge to zero?

Question: If $\theta$ is uniformly distributed in $\left[-\pi,\pi\right]$, how fast does the sample mean $\left<\cos\left(\theta\right)\right>$ converge to zero? Is the convergence speed proportional to $N$ realizations? $N^2$ realizations?
Comment: If the observations are independent, [basic properties of variance](https://en.wikipedia.org/wiki/Variance#Basic_properties) cover this entirely (variance of the mean is proportional to $\frac{1}{N}$. Standard error is therefore proportional to $N^{-\frac12}$).
Answer: Let $X=\cos(\theta)$ where $\theta\sim U[-\pi,\pi]$. Denote the sample mean of $N$ observations by $S_N=N^{-1}(X_1+X_2+\cdots +X_N)$ (where each $X_i$ is an iid copy of $X$). Then the standard properties of variance imply that $\mathrm{Var}(S_N)=N^{-1}\mathrm{Var}(X)$, so convergence is $O(N^{-1})$.
You can get much better convergence with stratification - at least $O(N^{-3})$ according to (10.2) in this book chapter.
Comment: +1 -- but I don't understand the stratification proposal, because there doesn't seem to be anything to stratify on.  If you're going to exploit an assumption that $\theta$ is uniform, then it seems there's no point even to sampling: just report that the expectation of $\cos(\theta)$ is zero!  Some elucidation of your idea would therefore be welcome.
Comment: Thanks. Do you think that the knowledge that $\theta \sim U\left[-\pi,\pi\right]$ could be used to extract even more information on the speed of this convergence? Could $\mathrm{Var}[X]$ can be expressed as a function of $\mathrm{Var}[\theta]$ for example?
Comment: @unkown What sort of information on the speed of convergence? I'm not sure if there's anything else to say. $\mathrm{Var}(\theta)$ is a constant so your second question doesn't quite make sense to me as stated. I would be interested to know why you're looking into this question.
Comment: @S.Catterall, thanks again for your help. I am calculating a quantity that cannot be negative: $P^{2} = N \times a^{2} + N^{2} \times b^{2} \times \left<\cos(\theta)\right>$, where $a^2 > b^2$ and $N$ is the number of observations of $\theta$. I'm interested in values of $N$ of the order of $10^{11}$ however, I can only perform numerical simulations until, say, $N=10^{7}$ and occasionally I find $P^2 < 0$ so I was hoping to prove that, for $N$ sufficiently large, $P^2$ could never the negative.
Comment: @unkown Ah, I see. Unfortunately, no matter how large $N$ is, it is always possible that $\left<\cos(\theta)\right>$ can take a value close to -1, even if the probability of this happening is very small. So I don't think you could prove that $P^2$ is *never* negative in this situation.
Comment: @S.Catterall, I found a problem with my code. I was setting $N=10^{11}$ in the equation but was actually using $10^{7}$ as the number of $\theta$ points for calculating $\left<\cos(\theta)\right>$. This may be a problem. I will fix it and re-run the simulation with $10^7$ for both.


Is there an easy way to create a command alias in mysql?

Question: This question is similar to what I'm asking:
Is there a way to create an SQL "alias"?
But not quite the same - I'm learning mysql and am going to be running the select command a lot as I screw with different commands.  Is there a way I can alias something like:
select * from testdb
to
ls
Or something equally similar?  Ideally, I'd be able to alias "select * from" to something like "show" and then just type "show testdb".
Comment: I've searched for such a functionality, but AFAIK it's not possible with the standard mysql client.
Answer: Three ideas come to mind:

a stored procedure, so you'd end up doing "call
show('testdb')"
a shell alias, so you run "show testdb" have it map to
"mysql -e 'select * from testdb'"
suck it up and type the command.
Answer: using alias with function can help you pass parameter to a alias like example query = select * from testdb where param = 'test param'  created alias = sftb test param  to create such alias you can write something like this in your bashrc file. alias sftb='function sftb(){ mysql -e "select * from testdb where param = '$1'"; };sftb'


Que atributo uso para colocar legendas ocultas em HTML(não quero em CSS) para deficientes visuais?

Question: Gostaria de colocar uma legenda oculta em uma imagem usando apenas HTML, mas não é o título da imagem quando coloco o mouse em cima, é um atributo da imagem, uma legenda que não aparece para usuários normais, porém quando um deficiente visual está usando uma ferramenta de leitura de texto, o programa ou ferramenta lê essa legenda que o programador colocou e assim ajuda para que o deficiente visual tenha acesso a informação que descreve a imagem.
Comment: Não seria o atributo `alt` o que você procura?
Answer:
O ARIA é um conjunto de atributos especiais para a acessibilidade,
  que pode ser adicionado a qualquer linguagem marcação, mas é
  especialmente adequado para HTML. - MDN

O atributo aria-label, em especial, é usado para definir um string na tag do elemento atual. Ele pode ser comparado com outros métodos de descrição de imagem no exemplo a seguir:

Percebe-se que:

alt substitue o tradicional ícone de erro quando o src é inválido;
title exibe um pequeno texto quando o cursor repousa sobre a imagem; e
aria-label configura um texto a ser processado pelo leitor de tela.
Comment: Não entendi direito qual o objetivo do aria-label, o atributo que precisava era o alt, ele é um dos resposáveis por deixar o site mais acessível:
  (https://tableless.com.br/o-poder-do-atributo-alt/).


Adicionar elemento num Array

Question: Preciso adicionar lista.get(i) num array, será adicionado no array com o valor da key spec_linha-criativa alterado. Porém, no meu código eu sempre perco a referência e quando j = 1 a minha lista está com os mesmo valores. Por exemplo, quando o laço é executado: j = 0 o elemento 0 da lista está correto, quando j = 1 o elemento 1 está correto mas o elemento 0 se torna igual o 1. Como corrigir isso? Eu já dou o new no objeto a cada interação para evitar isto mas ocorre.
private List<BasicDBObject> linhaCriativa(List<BasicDBObject> linhas) {
    List<BasicDBObject> lista = new ArrayList<>();
    for (int i = 0; i < linhas.size(); i++) {
        if (linhas.get(i).toMap().containsKey("spec_linha-criativa")) {
            String[] linhaCriativa = linhas.get(i).get("spec_linha-criativa").toString().split(";");
            if (linhaCriativa.length > 1) {
                for (int j = 0; j < linhaCriativa.length; j++) {
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject = linhas.get(i);
                    dbObject.replace("spec_linha-criativa", linhaCriativa[j]);
                    lista.add(dbObject);
                }
            }
        }
    }
    return lista;
}

Já tive o mesmo problema de "perder" referência mas não consigo
  aplicar aqui
  https://stackoverflow.com/questions/29658869/why-cant-i-concatenate-the-json
Comment: `lista` e `linha` sempre terão o mesmo tamanho?
Comment: São as mesmas coisas, trouxe por parâmetro duas vezes para tentar ver se conseguia alterar.
Answer: Primeiro, isto daqui está errado:
BasicDBObject dbObject = new BasicDBObject();
dbObject = linhas.get(i);

O primeiro valor atribuído vai ser perdido porque logo após um outro valor é atribuído sem que o primeiro seja usado para nada. Além disso, como nesta parte você está iterando o j, mas pegando com o i, isso vai sempre pegar o mesmo objeto na iteração e aplicar o replace várias vezes no mesmo objeto. Acho que o que você quer não é alterar o BasicDBObject, mas sim criar um novo BasicDBObject com as alterações.
Para simplificar o seu código, vou aplicar o for-each nos seus dois laços e nos ifs, inverter a condição e usar o continue:
private List<BasicDBObject> linhaCriativa(List<BasicDBObject> linhas) {
    List<BasicDBObject> lista = new ArrayList<>();
    for (BasicDBObject db : linhas) {
        if (!db.toMap().containsKey("spec_linha-criativa")) continue;
        String[] linhaCriativa = db.get("spec_linha-criativa").toString().split(";");
        if (linhaCriativa.length == 0) continue;
        for (String criativa : linhaCriativa) {
            BasicDBObject dbObject = new BasicDBObject();
            dbObject = db;
            dbObject.replace("spec_linha-criativa", criativa);
            lista.add(dbObject);
        }
    }
    return lista;
}

Agora vamos tentar corrigir o problema:
private List<BasicDBObject> linhaCriativa(List<BasicDBObject> linhas) {
    List<BasicDBObject> lista = new ArrayList<>();
    for (BasicDBObject db : linhas) {
        if (!db.toMap().containsKey("spec_linha-criativa")) continue;
        String[] linhaCriativa = db.get("spec_linha-criativa").toString().split(";");
        if (linhaCriativa.length == 0) continue;
        for (String criativa : linhaCriativa) {
            BasicDBObject dbObject = db.copy();
            dbObject.replace("spec_linha-criativa", criativa);
            lista.add(dbObject);
        }
    }
    return lista;
}

Observe que eu inventei um método copy(). Este método vai criar uma cópia do BasicDBObject. Desta forma, eu posso criar várias cópias de cada instância e alterar cada uma delas de um jeito diferente sem alterar a original.
Talvez isso ainda dê algum problema que você queira manter uma cópia inalterada quando não houver nenhum "spec_linha-criativa" para substituir. Neste caso:
private List<BasicDBObject> linhaCriativa(List<BasicDBObject> linhas) {
    List<BasicDBObject> lista = new ArrayList<>();
    for (BasicDBObject db : linhas) {
        String linhaCriativa = db.toMap().containsKey("spec_linha-criativa")
                ? db.get("spec_linha-criativa").toString().split(";")
                : new String[0];
        if (linhaCriativa.length == 0) {
            lista.add(db.copy());
            continue;
        }
        for (String criativa : linhaCriativa) {
            BasicDBObject dbObject = db.copy();
            dbObject.replace("spec_linha-criativa", criativa);
            lista.add(dbObject);
        }
    }
    return lista;
}

Comment: Uau, eu sempre tenho esse problema de "perder o objeto" quando quero substitui-lo. Bem esclarecedor, obrigada

Adicionar elemento num Array


How to turn a system of first order into a second order

Question: So I have two equations
$X' = aX + bY$
$Y' = cX + dY$
I want to convert it back to a second order equation with the form
$X'' + \alpha X' + \beta X$ with $\alpha,\beta$ in terms of a,b,c,d.
I have been racking my brain for hours trying to go backwards from a reduction of order, but just can't seem to figure it out. Any help would be much appreciated!
Comment: Not sure this is what you're looking for, but couldn't you take the derivative of the first equation, then substitute $Y$ and $Y^\prime$ in?
Comment: Nonlinear version of question: https://math.stackexchange.com/questions/2175641/can-you-convert-a-system-of-coupled-first-order-des-into-a-higher-order-de
Answer: If you derive the first equation, you get:
$$  X ^"=aX '+bY ' $$
(if you are considering $a$ and $b$ as constants).
But we have $Y'=cX+dY $, so substitute in the above equation, you get
$$ X ^" = a X' +b(cX+dY).$$
Note that $Y=\frac{1}{b}(X'-aX)$ for $b \neq 0$.
So, substituting again you get the final answer.
Comment: ah, that was much easier than I was making it, just a question how did you get Y, I think that was where I was running into major issues.
Comment: Im guessing you just solve the first equation correct?
Comment: I get $Y$  from  the first equation $X'=aX+bY$.
Comment: Awesome that's what I thought thanks for the help! Storing that trick for later!


Dúvida sobre struct e lista em c

Question: Estou com problema quando precisa dar um valor a uma pessoa, no caso, preciso dar o valor nome e idade para a pessoa. Eu tentei criar uma struct PESSOA e uma lista que contém uma pessoa e um id, porém durante a compilação me apresenta o erro da imagem.

Segue abaixo meu código:
typedef struct PESSOA
{
    char nome[100];
    int idade;
}Pessoa;

typedef struct NO
{
    int id;
    Pessoa pess;
    struct No *prox;
}No;

int main()
{
    int controle;
    int id=0;
    No *no_inicial;
    No *no_proximo;

    no_inicial = (No *)malloc(sizeof(No));
    no_proximo = no_inicial;
    no_proximo->prox = NULL;

    while(1)
    {
        printf("Insira o nome");
        gets(no_proximo->pess().nome);
        printf("Insira a idade");
        scanf("%d", &no_proximo->pess->idade);
        no_proximo->id = id;
}
}

Comment: Corrigi a formatação para você.
Answer: Assim deve compilar:
#include <stdio.h>
#include <stdlib.h>

typedef struct PESSOA {
    char nome[100];
    int idade;
} Pessoa;

typedef struct NO {
    int id;
    Pessoa pess;
    struct NO *prox;
} No;

int main() {
    int controle;
    int id = 0;
    No *no_inicial;
    No *no_proximo;

    no_inicial = (No *) malloc(sizeof(No));
    no_proximo = no_inicial;
    no_proximo->prox = NULL;

    while(1) {
        printf("Insira o nome");
        fgets(no_proximo->pess.nome, 100, stdin);
        printf("Insira a idade");
        scanf("%d", &no_proximo->pess.idade);
        no_proximo->id = id;
    }
}

Não sei se esse programa vai fazer o que você quer no entanto.
Algumas observações:

Nunca, jamais, de forma alguma, ouse pensar na hipótese de utilizar a função gets. Esta função é unanimemente odiada e detestada na comunidade de programadores em C por ter sido pessimamente projetada e ser extremamente insegura. No seu código, eu a substitui por uma chamada equivalente, porém segura, de fgets.
Não confunda No com NO. O nome No é o que você deu como apelido para struct NO. O nome NO isolado nada significa. Não adianta colocar No dentro da declaração dos { ... } do próprio No porque isso cria um problema do ovo e da galinha: Para que o compilador saiba o que é No dentro da estrutura, ele já tem que ter terminado de ler a estrutura. Entretanto, ao usar struct NO, o compilador já viu o cabeçalho anteriormente, embora ainda não tenha terminado de ler a estrutura, e portanto não há problema.
O uso de a->b é o mesmo que (*a).b. Se o que existe no a é um ponteiro para uma estrutura no qual você quer acessar um elemento, use ->. Se o a não é um ponteiro, e use .. No caso da sua No, ela tem um ponteiro (prox) para um outro No, e por ser ponteiro, você acessa o conteúdo dele com ->. Na sua estrutura No, também há uma outra estrutura aninhada (pess) do tipo Pessoa que não é um ponteiro e portanto deve ter seu conteúdo acessado com ..
Só use () após um nome se ele representar uma função. O uso de no_proximo->pess() só faria sentido se pess fosse um ponteiro para função, coisa que iniciantes na linguagem C não vão encontrar tão cedo. Logo, não coloque parênteses após o nome de um campo de alguma struct (seja ele acessado por -> ou por .).
Comment: @ViníciusFrança Neste caso, caso não lhe reste nenhuma dúvida, clique no ✅ que aparece abaixo do número de votação desta resposta para marcá-la como aceita e marcar a sua pergunta como resolvida. Foi um prazer ajudá-lo.
Comment: Obrigado, resolveu tudo.
Answer: Versão Simplificada - Testada
Crie um arquivo chamado main.c
#include <stdio.h>
#define EXIT_SUCCESS 0
int main(int argc, char** argv) {
    typedef struct{
        char* nome;
        int idade;
    }PESSOA;
    int numPessoas=3;
    int x;
    PESSOA* pessoas = malloc(numPessoas * sizeof *pessoas);
    printf("Insere 3 pessoas\n\r");
    for (x = 0; x < numPessoas; x++){
        pessoas[x].nome=(char*)malloc(sizeof(char*));
        printf("Insira o nome: ");
        scanf("%s",pessoas[x].nome);
        printf("Insira a idade: ");
        scanf("%d",&pessoas[x].idade);
    }
    for (x = 0; x < numPessoas; x++)
        printf("Nome: %s, idade: %d\n",pessoas[x].nome,pessoas[x].idade);
    return (EXIT_SUCCESS);
}

Compilado e testado com gcc (Linux)

gcc -o main *.c

Executado no Linux

./main

Criado com editor

nano

Teste feito no Ubuntu 16.04 LTS

Dúvida sobre struct e lista em c


JQuery Add Class to Unrelated Div On Click

Question: I would like to add the class "favourite" to the first div with class "box" above the div with class "click-me" when clicked. But it isn't a parent or related at all.

                   Click me

I have tried:
            $(".click-me").click(function () {
                $(this).prevAll('.box:first').addClass('favourite');
            });

Answer: Try a combination of closest and prev

$(".click-me").click(function() {
  $(this).closest('.modal').prev(".box").addClass('favourite');
});
.favourite {
  background: #ccc;
}

    box

              Click me

Answer: It'll working:
 $(".click-me").click(function () {
          $('.box').first().addClass('favourite');
     });


Odds of winning a prize where chance of winning increases after each win

Question: Suppose you are playing a video game. Every time you win a game you have an $x\%$ chance of winning a prize. After the $n^{th}$ win you have a $x\%=(2+2.3(n-1))\%$ chance of winning a prize. Obviously on the $22^{nd}$ win we have about a $50\%$ chance of winning a prize, but intuitively I feel like we can expect to win a prize before then because although we have a $50\%$ chance on the $22^{nd}$ win, we have already had $21$ other chances to win.
So I guess my real question is: For what value of $n$ can we expect to have won a prize with a $50\%$ probability? Is it just $n=22$ or is my intuition correct and how would I go about making this assertion rigorous?
Comment: Do you mean after the $n^{th}$ game the probabilities increase, as opposed to wins? Because then how can you say you expect to have won a prize by the time when $n=22$, which means by your $22^{nd}$ win? Or alternatively, do you mean to find the value of $m$ (where $m$ is number of games played) for which we can expect (all that stuff)? Also in this case, what happens to the chance of winning if you lose? Does it stay the same?
Comment: @ErickWong I got confused by this too, but the comment clears it up, and also careful reading - you may win the game but you only have $x\%$ chance of winning a prize - and this is what we care about.
Comment: @user451847 Perhaps you should try improving the wording of your question.  For instance by using "complete" instead of "win" when referring to a game.
Comment: I see where there was confusion. I went and made the problem less confusing and more explicit.
Comment: Hmmmm, maybe I wasn't very clear. You can assume I win every game and so my chance of winning a prize goes up every game. So $n$ is effectively games played and we can disregard the concept of whether or not I won a game.
Comment: @user451847 That makes no sense.  If $n=22$ then by your definition you have already won 21 times.  Why are you referring to 21 chances to win if they are 21 certainties to win?
Comment: @JohnDoe Ah, thanks.  The problem is that "win" is a really poor term to use since it doesn't specify whether it's a game win or a prize win.
Answer: The probability of not winning the prize on the nth game win, in percentage terms is
$$100 - \left[2+2.3\left(n-1\right)\right] = 100.3-2.3n$$
In fractional terms, this is
$$1.003 - 0.23n$$
Let's ignore the fact the you have a less than 0 chance of winning the prize when n=0, and assume the probability is just 0 then.
The probability of not winning any prize at all from any wins up to and including the nth win is
$$\Pi_{k=1}^{n}(1.003-0.023k)$$
We can calculate this for different values of n:
n   Probability of not getting the prize
1   0.98
2   0.93786
3   0.87596124
4   0.79800068964
5   0.7086246124
6   0.612960289726
7   0.51611256395
8   0.422696189875
9   0.33646616714
10   0.260088347199
11   0.1950662604
12   0.14181317131
13   0.0998364726026
14   0.0679886378424
15   0.0447365237003
16   0.0284076925497
17   0.0173855078404
18   0.010240064118
19   0.00579587629078
20   0.0031471608259
21   0.00163652362947
22   0.000813352243845
23   0.000385528963582
24   0.000173873562576
25   7.44178847824e-05
So you probably get the prize by the 8th win, and are very unlikely to have to wait until the 22nd.
Comment: This is what I just tried to work out on my own. This makes perfect sense.


Encontrar .keystore do APK

Question: Alguém sabe onde eu encontro o arquivo .keystore do meu APK assinado digitalmente?
É o mesmo .jks?
Comment: Sim, é o .jks. xD
Comment: Ah! Legal! Obrigado!
Answer: O JKS(Java KeyStore) você não consegue encontra-lo se ainda não criou. Antigamente a extensão do certificado era .keystore aí depois de um tempo o Google mudou para .jks. Para criar veja o comando abaixo como exemplo:
$ keytool -genkey -v -keystore my-key.jks -alias alias_name -keyalg
RSA -keysize 2048 -validity 10000

Veja aqui neste artigo mais detalhes de como gerar certificado release/debug.

É o mesmo .jks?

Sim é o mesmo.
Comment: Obrigado pela informação
Comment: @adventistaam precisar, estamos por aqui.
Comment: ele cria para qual pasta?
Comment: @adventistaam você que escolhe a pasta onde deve ser criada. Se você inserir o comando sem definir o local, ele será criado na pasta raiz onde você abriu o cmd caso seja windows.
Comment: no caso eu segui esse comando no linux
Comment: @adventistaam verifique em seu terminal qual é a pasta raiz quando você abre ele. O arquivo estará lá. Para direcionar pra uma pasta específica, na hora de colocar o comando keytool, faça desta forma: /home/my-key.jks Ai vai salvar na sua home

Encontrar .keystore do APK


XAMPP/Localhost external Javascript File empty

Question: I've set up a website with XAMPP, have working on some PHP things and now tried to include some Javascript functions. My index.php is in the htdocs folder. In that htdocsfolder, I have a JS folder with a scripts.js file. The file shows up in my Sources when inspecting the website in my browser, but it is completely empty.
I have the following line in the head of my index file:

I found this question:
resource files are coming up empty when hosted locally
People mention it might be an htaccess problem. I don't know anything about htaccess. There is currently no htaccess file in my htdocs folder.
Code in my scripts.js file:
alert("Hi!");

function toggle(element, show) {
    document.getElementById(element).style.display = show;
}

function toggleLogin() {
    toggle('registerWrapper', 'none');
    toggle('loginWrapper', 'block');
}

function toggleRegister() {
    toggle('loginWrapper', 'none');
    toggle('registerWrapper', 'block');
}

How can I solve this?
Comment: is your file there ? is there any error in your console ?
Comment: The file shows up in the Sources, but it's empty. There are no errors in the console, until I start using functions that are supposed to be in the empty file.
Comment: what code is in your script file which is not showing up?
Comment: Added scripts.js content to the original question.
Answer: Try to give that file full permissions just to see if that is your issue. Then lower it if that is a case.
Also see if the file owner is as your xampp expects (or as other files are)
Comment: I don't know anything about permissions unforunately :(
Comment: can you go into console -> network -> select file on the left -> and see what code or error you get there.. somethink like this: https://i.imgur.com/OrvLPVt.png
Comment: Status code for scripts.js is 200 OK (from memory cache).
Comment: the I guess that some server issue you have,, but again you get 200 OK replay what is very puzzling :(


Multidimensional Arrays fro Random Walk Program

Question: So I am working on my multidimensional array homework for my C++ class and honestly I am 100% lost on how this is supposed to work. It's the random grid walk and I've found plenty of examples but I am still just not understanding it. I understand what the program is supposed to output but it is the how that has me stumped, logically I just don't get it. If anyone can explain to me what the code is doing and how I'd really appreciate it. I can code it from their it's just trying to understand it that is kicking my butt.

Requirements and constants for the assignment:

Libraries: iostream, cstdlib (for stand & rand), ctime (for time)
const int SIZE = 10; (10 can never show up in the program must call through variable)
typedef char Grid[SIZE][SIZE];
Function Prototypes that must be used as shown no less but can add functions.

The mock up we were give of the main program looked like this:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

/*** Function Prototypes ***/
bool can_move_up(int i, int j, Grid walk);
bool can_move_up(int i, int j, Grid walk);
bool can_move_up(int i, int j, Grid walk);
bool can_move_up(int i, int j, Grid walk);
void init_array(Grid walk);
void generate_random_walk(Grid walk);
void print_array(Grid walk);
/***************************/

int main(void)
{
const int SIZE = 10;
typedef char Grid[SIZE][SIZE];

Grid walk; // the grid in which the random walk occurs

srand(static_cast<unsigned>(time(NULL)));

init_array(walk);
generate_random_walk(walk);
print_array(walk);

return 0;

}

This is the code that I have come up with so far. I have not been able to get it to run but I think I'm on the right track I'm just confused on where to go to from here logically. I am stressing that I want to UNDERSTAND LOGICALLY how this works and not have someone do it for me. I'm not a CS or CE major but I do find this stuff interesting.
(I am using classes and have this separated into .cpp & .hpp files but placed the class portion at the beginning of the code for you all to see how my classes are set up and the functions within them are set to work.)
Thanks for the help!
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// References these two variables to the other classes through public domain with in class
class BaseClass
{
public:
    const static int SIZE = 10;
    typedef char Grid[SIZE][SIZE];
private:

};

// Contains the initialization, generation, and printing functions for the program
class RandomWalkClass : public BaseClass
{
public:
    // Initializes the Grid filling all 100 spaces with '.' and starting poin "0,0" with 'A'
    void init_array(Grid walk)
    {
        for (int i = 0; i < SIZE; i++)
        {
            for (int j = 0; j < SIZE; j++)
            {
                Grid[i][j] = '.'; // Xcode gives me error for '=' "Expected unqualified-id"
                Grid[0][0] = 'A'; // Xcode gives me error for '=' "Expected unqualified-id"
            }
        }
    }
    // I am honestly not sure what to do with this funciton or what should be included in it's body
    void generate_random_walk(Grid walk)
    {

    }
    // Will print the random walk to the grid
    void print_array(Grid walk)
    {
        for (int i = 0; i < SIZE; i++)
        {
            for (int j = 0; j < SIZE; j++)
            {
                cout << Grid[i][j]; // Xcode error "Unexpected type name 'Grid'"
            }
            cout << endl;
        }
   }
private:

};

// Contains the move functions for the program
class MoveDirectionClass : public BaseClass
{
public:
    bool can_move_up(int i, int j, Grid walk)
    {
        if (i > 0 && walk[i - 1][j] == '.')
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool can_move_down(int i, int j, Grid walk)
    {
        if (i < 9 && walk[i + 1][j] == '.')
        {
           return true;
        }
        else
        {
           return false;
        }
    }
    bool can_move_left(int i, int j, Grid walk)
    {
        if (j > 0 && walk[i][j - 1] == '.')
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool can_move_right(int i, int j, Grid walk)
    {
        if (j < 9 && walk[i][j + 1] == '.')
        {
            return true;
        }
        else
        {
            return false;
        }
   }
private:

};

#include "program6.hpp"

int main()
{
int i;
int j;
int walk;
int letter;
int move;

// Unsure of where this should go and what it's purpose to the program is (we've never discussed srand in class)
srand(static_cast<unsigned>(time(NULL)));

// Calls initialization of program
RandomWalkClass initialize;
initialize.init_array(<#char (*walk)[10]#>);

// randomly chooses 0,1,2,3
move = rand() % 4;

// Runs through alphabet with each move of the switch program
for (letter = 1; letter < 26; letter++)
{
    switch (move)
    {
        case 0:
            MoveDirectionClass up;
            up.can_move_up(<#int i#>, <#int j#>, <#char (*walk)[10]#>);
            break;
        case 1:
            MoveDirectionClass down;
            down.can_move_down(<#int i#>, <#int j#>, <#char (*walk)[10]#>);
            break;
        case 2:
            MoveDirectionClass left;
            left.can_move_left(<#int i#>, <#int j#>, <#char (*walk)[10]#>);
            break;
        case 3:
            MoveDirectionClass right;
            right.can_move_right(<#int i#>, <#int j#>, <#char (*walk)[10]#>);
            break;
        default: break;
    }

}

// Calls the printing of the grid with the random walk
RandomWalkClass generate;
generate.print_array(<#char (*walk)[10]#>);

return 0;
}

Comment: `Grid[i][j] = '.';` is wrong - you defined `Grid` as a type, not a variable.
Comment: Welcome to Stack Overflow. When you write code, you should start with something small and simple that works perfectly, then add complexity a little at a time. *Never add to code that doesn't work.* Have you tried coding a one-dimensional random walk? If you really want help with a specific problem, then make your question about that problem; a little background material or context is all right, but don't post everything you have and ask a dozen specific questions about it.
Answer: When it came to the Unexpected type name you did typedef Grid and didn't put it in your class.
Well, just to move from room to room, if you want objects in this room I would do something like this.
#include <iostream>
#include <string>
using namespace std;
struct Room{
//insert variables here like
int object;
}
typedef struct Room room[5][5];
int main()
{
string direction;
int x;
int y;
room space; //This is the variable to access both the array and the struct
space[0][0].object = 0; //This variable represents what room you start off in and the 0 could represent the type of object or the fact that there is no object.
//Now create rooms [0][0] through [4][4] which is a 5 by 5 area. After that create this.
cout << "Enter W to go north, S for South, D for East, and A for West." << endl;
cin >> direction;
if (direction == "W")
y++;
if (direction == "S")
y--;
if (direction == "D")
x++;
if (direction == "A")
x--;
//Then repeat this code and access the different rooms using space[x][y].object or whatever the variable you want to access from the struct
}

Please let me know if you have any questions or concerns. I also have a game with an example of moving between rooms. My email is firstname.lastname@example.com
Answer: Instead of Grid[i][j] = '.' and Grid[i][j] = 'A', use
walk[i][j] = '.';
walk[0][0] = 'A';

Comment: Oh man I feel really stupid on that one! I knew it was a simple error I've just been staring at this and over thinking it way too much already. Thanks man!


Ordinary equation of the line $\{P + tA\}_{\ t\ in\ \mathbb R}$

Question: Exercise 1 page 247 of "Basic Mathematics" by S.Lang.
Question: Is mine $\eqref{2}$ or the author's $\eqref{1}$ solution correct?
Problem statement: Find the ordinary equation of the line $\{P + tA\}_{\  t\  in\  \mathbb R}$ in the following case
$$P = (3, 1), A = (7, -2)$$
The author's solution is
$$\bbox[5px,border:2px solid red] {3x + 4y = 13}  \tag{1}\label{1}$$
Which I belive is wrong, and could've possibly come from using points $P$ and $A$ as points of this same line, i.e. considering the line $\{P + t(A - P)\}_{\  t\  in\  \mathbb R}$, yielding the following equation:
$$(3, 1) + t(7 - 3, -2 - 1) = (3, 1) + t(4, -3)$$
Whose parametric representation is
\begin{cases}
x = 3 + 4t \\
y = 1 -3t
\end{cases}
Following the procedure suggested by the author, we can eliminate the parameter $t$ by multiplying expressions $x$ and $y$ by some amount, and adding them together:
\begin{cases}
3x = 9 + 12t \\
4y = 4 -12t
\end{cases}
It follows
\begin{align}
3x + 4y & = 9 + 12t + 4 -12t \\
& = 9 + 4 \\
& = 13
\end{align}
My interpretation of $\{P + tA\}_{\  t\  in\  \mathbb R}$ is all $t$ dillations of $A$ followed by a translation by $P$; the line parallel to $A$, passing through $P$.
With this interpretation I get
\begin{align}
P + tA & = (3, 1) + t(7, -2) \\
& = (3 + 7t, 1 -2t)
\end{align}
Which can be represented parametrically as
\begin{cases}
x = 3 + 7t \\
y = 1 -2t
\end{cases}
With the same procedure as before, we get
\begin{cases}
2x = 6 + 14t \\
7y = 7 -14t
\end{cases}
It follows
\begin{align}
2x + 7y & = 6 + 14t + 7 -14t \\
& = 6 +7 \\
& = 13
\end{align}
Yielding the ordinary equation
$$\bbox[yellow,5px] {2x + 7y = 13} \tag{2}\label{2}$$
Answer: Calculate a normal vector for the line $\vec n = \hat A=\binom{2}{7}$. Now pick a fixed point on the line $P = (3,1)$. Now a equation for the line is:
\begin{align*}
 \vec n \cdot \binom{x-3}{y-1} = 0 \Leftrightarrow 2(x-3)+7(y-1)=0 \Leftrightarrow 2x+7y = 13
\end{align*}
That is - you are right, and the book is wrong.


the easiest solution for a JavaScript/jQuery countdown timer

Question: I want to implement a countdown timer, that will countdown until a specific date, starting with a date that will be taken form the database.
The countdown timer should not restart at page refresh, it should just countdown until a specific date.
I was wondering if it exists a jQuery or JavaScript open source solution for that?
Comment: @ngduc: what is wrong with that ?
Answer: Here is a great looking countdown timer with a nice tick animation: http://www.littlewebthings.com/2010/02/jquery-countdown-script/
Comment: Nice animation and customizability.
Answer: jQuery Countdown is a good one and easy to implement.


how to avoid/shorten the SourcePath too Long files/folders name

Question:
Please can you let me know how to (dont want to delete or avoid)shorten the LongSourcePath files/folders name in robocopy while copying to the destination folder. As I am using this snippet:
<code>robocopy %source% %destination% /MIR /E /PURGE /XF ntuser.* ntuser.dat.*
</code>
Any assistance or inputs here:
Comment: Can you give some more info please? If you don't show any other info on `%source%`, it will be hard to give you any other advice than rename the directories on the source path or the filenames.
Comment: try using [8.3 format](http://www.computerhope.com/jargon/num/8-3-format.htm)
Comment: `subst Z: "%source%"` and then `robocopy Z:\ ...` might help.
Answer: AFAIK, you can't. You can "delete" the file with robocopy by /mir'ing an empty directory as the source and the offending folder as the destination, but that will delete everything in the destination folder (bad if you don't first copy/move out what you can).
You can backup everything you can "move" that doesn't have a path name that is too long, then use the /mir trick above to delete those files.
Or, you can also do this: https://superuser.com/a/638162/1838110 which may be a better solution for you.


Is it possible to use SignalR outside of a Microsoft Environment?

Question: I currently have an API solution created with WebApi that hosts a Hub.
When I create an MVC project inside of this solution SignalR works correctly and as expected.
I have a separate project with no Microsoft infrastructure associated with it aside from a sole reference to jquery.signalR-2.0.2.js
When I reference  in this project it is not found (my understanding is that this is auto-generated). Is there a way I can use signalR in my separate HTML/JS solution or am I limited to creating my projects inside the same solution?
Comment: Besides the reference to jquery.signalR....js - do you have a reference to signalr/hubs? Javascript client is standalone and not tied to any project or solution but it needs to be able to connect to the server.
Answer: Sure you can. Download/save or generate a proxy file. To generate install the Microsoft.AspNet.SignalR.Utils NuGet package. Include the generated proxy (js script) in your none MS client project.
If your client is deployed under different domainname, then the hub endpoint, configure support for cross-domain requests.
If JSONP is required on the client (to support cross-domain requests in older browsers), it will need to be enabled explicitly by setting EnableJSONP on theHubConfiguration object to true. JSONP is disabled by default, as it is less secure than CORS.
Answer: Yes it is possible on the client side. I am working on an AngularJS web application that uses SignalR v2.0.2 using the jquery.signalR-2.0.2.js reference.
On the server side, SignalR needs OWIN to startup using these lines of code in the Startup.cs:
public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // SignalR Hub Startup
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            hubConfiguration.EnableJavaScriptProxies = true;
            hubConfiguration.EnableJSONP = false;

            app.MapSignalR(hubConfiguration);

        }
    }

Then a javascript file will be auto-generated on the server-side and can be accessed by the client using a tag in the HTML document. Here is what is needed on the client-side for setting up the hub:

The last script line simply is a reference to the auto-generated javascript created by the server-side. If you open this URL in your browser you will see the script generated that will be accessed by the non-.NET web client.
More info here: ASP.NET SignalR Hubs API Guide - JavaScript Client


Giving a second initial point to solve Kepler's Equation

Question: I am trying to solve Kepler's equation ( $ 0 = E - e·\sin(E) + M $ ) with an iterative method but due to the elliptic orbit of the body for some typical values of e and M which causes eccentric anomaly, I prefer to use Secant Method instead of Newton Method. However, I cannot decide on the initial points. For Newton, I use the initial point:
$$
E_0=M + \frac{e\sin(M) }{1 - \sin(M + e) + \sin(M)}
$$
However, what could be a good choice for the second initial point? I guess close values may work but I am not sure.
Comment: $M=E-e\sin E$ is equivalent to $0=E-e\sin(E)-M$, or do you use a different convention? But your initial guess $E_0=M+e\sin M+...$ is compatible with the standard, else one would start with $E_0=-M+...$
Answer: Not using the secant method.
I always think that it is much better to use Newton method provided that we are able to generate a good starting point. One thing I use to do is to build the $[1,m]$ Padé approximant of  function $f(x)$ around a given point $x_0$.
These approximants write
$$f(x) \sim \frac {f(x_0)+a^{(m)}(x-x_0) } {1+\sum_{i=1}^m b_i^{(m)} (x-x_0)^i}$$ where all coefficients are defined in terms of the function and high-order derivative value at $x_0$. I find this more efficient than series reversion which are often suggested (have a look here)
Then the estimate
$$x_{(m)}=x_0-\frac {f(x_0)}{a^{(m)}}$$ For small values of $m$, this correspond to Newton method, original Halley method or original Householder method.
For Kepler's equation $$M=E-e \sin(E)$$ using $x_0=0$ this would give the following estimates
$$E_{(0)}=E_{(1)}=\frac M{1-e}$$
$$E_{(2)}=\frac {6(1-e)^2 M} {e M^2+6(1-e)^3}$$
$$E_{(3)}=\frac{e M^3+6 (1-e)^3 M}{2 e (1-e) M^2+6 (1-e)^4}$$
Suppose  $e=0.1$ and $M=0.5678$. Converted to decimals, the above formulae (and the next ones) give
$$\left(
\begin{array}{cc}
 m & E_{(m)} \\
 0 & 0.63088888888888888889 \\
 1 & 0.63088888888888888889 \\
 2 & 0.62627278539121795082 \\
 3 & 0.62630631527966334097 \\
 4 & 0.62642926189145170922 \\
 5 & 0.62642749747544870702 \\
 6 & 0.62642515169269243491 \\
 7 & 0.62642520885980656763 \\
\dots & \cdots \\
\infty & 0.62642525037762133960
\end{array}
\right)$$
Comment: Why E0 depend on E1? Should they be interchanged? Also, I have a specific task that I am required to use Secant, otherwise, I am also comfortable with Newton as I mentioned in the question. Do you think that using your E0 and E1 will work?
Comment: @thisguy. They are not dependent; just equal.
Comment: Oh! my mistake. What about the second question?
Comment: @thisguy. Why not to use a golden search ?
Comment: i do not know what that is and how it will help
Comment: @thisguy.Have a look at https://en.wikipedia.org/wiki/Golden-section_search  As soon as the solution has brackets, switch to the secant method.
Comment: As soon as the solution has brackets, what do you mean by this?


What type of statistic should I use to compare ratios in my experiment?

Question: I have performed an experiment to analyse the ratio of intronic versus exonic levels for 1000 transcripts after treated the cells with a drug and compare my results with untreated cells . Each transcript is equivalent to a gene, while intronic regions represent a part of the transcript that is rapidly remove and exons the part of the transcript that encode for proteins. The drug is thought to potentially increase the levels of intronic regions compare to exonic regions.
I have compared the ratio of intron/exon signals in treated versus untreated cells in two independent experiments (two biological replicates). What kind of statistic test should I use to see if there is any significant increase in intronic/exonic regions after drug treatment?
I was performing a student´s t-test comparing the ratio of the intron/exon at biological replicates 1 and 2 treated with the drug with untreated cells, is that correct?
Thanks a lot for your help
Comment: does this: http://courses.washington.edu/dphs568/course/day12.htm help?
Comment: Thanks for your help, but I should say that I don´t know much about statistic :( Do you say I should use a Chi square test?
Answer: Ok here's a quick summary of what I think you can do:
Since you expect an increase in intronic/exonic regions after drug treatment, you expect to see a ratio of intronic/exonic regions that is significantly higher for the treated cells than for the untreated one (if I've understood your problem correctly).
So let $r_t$ be the "true" ratio (intronic/exonic) for treated cells and $r_u$ the "true" ratio for untreated ones. Your null hypothesis ($H_0$) is that $r_t=r_u$ (i.e., no significant difference, drug has no effect) whereas your alternative hypothesis $H_a$ is $r_t > r_u$ (upper tail alternative)). Now we can transform this problem in a problem of proportions by considering
$$p={\#\text{intronic}\over (\#\text{intronic} + \#\text{exonic})} = {r\over r+1}$$
and noting that $r_t>r_u \Leftrightarrow p_t>p_u$.
Now you can compare the observed difference in proportions $\hat p_t-\hat p_u$. Under the null hypothesis (i.e., under the hypothesis that $p_t=p_u=p$) and suitable assumptions [1],
$$ \hat{p}_t-\hat{p}_u \sim \mathcal N\left(0,p(1-p)\left({1\over n_t}+{1\over n_u}\right)\right)$$
So under the null, the following statistics should follow a standard normal distribution:
$$ z = {\hat{p}_t-\hat{p}_u\over \sqrt{\hat{p}(1-\hat{p})\left({1\over n_t}+{1\over n_u}\right)}} $$
where $\hat{p}$ is the observed proportion over the total population i.e.,
$$\hat{p} = {n_tp_t+n_up_u\over n_t+n_u} .$$
Now remains for you to compute $P(Z\ge z)$ if it's very small then there is evidence for you to reject the null hypothesis (i.e., to say that your drug does indeed seem to have a significant effect).
Remark: even before computing the statistic etc. You can just look at your observed difference $\hat{p}_t-\hat{p}_u$ and at the variance over the whole population ($\hat{s}^2=\hat{p}(1-\hat{p})(1/n_t+1/n_u)$). If the observed difference is much larger than the observed standard deviation $s$ then it provides evidence that the difference is significant. (Do you see why?)
[1] I strongly recommend you check a reference to know and understand the underlying theory. (not hard) Any good introductory book on statistics will mention hypothesis testing etc. An example among many others is "Mathematical Statistics with Applications" (Wackerly, Mendenhall, Scheaffer)
Comment: ... I'm kind of wondering whether anyone should report p-values without any understanding of the underlying theory ... Anyway, the test I've made is a baseline Z-test to compare proportions. But to obtain the said proportions you should still convert your ratios in proportion (first formula: proportion = number of intronic/(total number). What program do you use?
Comment: Thanks for your comment. But I have to apologize for my poor knowledge of statistic, I´m only a lab scientist. You have understand the problem perfectly, but I don´t know about the proportions you have friendly told me. The point is I need to Know the name of the specific statistic test I have to use and then apply it to my samples by same computer program that give me a p-value for each of the 1000 samples of my experiment. I´m very sorry I do not understand your formulas :(
Comment: Thanks again for your comment. I don´t want to report the p-values without understand the statistic used, but as a result of my limited knowledge in the field is much easier for me to ask first to the specialist the statistic I have to employ and then try to understand why. I have an excell with the values of the ratios intron/exon for the 1000 genes: 0.98; 1.50; 2.0 are some of the most frequent values.
Comment: gen.a Ratio Intron/Exon values-Untreated1 0.19-Untreated2 0.17-Treated1 0.34-Treated2 0.45. That´s the kind of ratios I have for 1000 genes. Two ratios obtained in two independent untreated experiments and other two ratios obtained in two independent treated experiment. I would like to know if the differences between treated and untreated are significant for each gene.
Comment: The answer is great but since the experiment is about comparing ratios, I doubt that using z score (an by this way assuming normal distribution) is a good idea.... It is what I do but it is not what we SHOULD do.


coloring specific bars of grouped bar chart in r using lattice

Question: I would like to create a bar chart in R using lattice. It's a simple chart with six double columns, currently the color pattern is the same for all of them. That means the first double column is in red and black as well as the other five double columns. Would it be possible to change the color pattern, so that each column has its own color? If it's not possible using lattice, might it be possible with ggplot2? To clarify what I have in mind, see the following two pictures:
Current result:

Desired color pattern:

My current code:
library(lattice)
mitte_table <- read.table(text = "Partei; Jahr; Ergebnis
CDU;2017;18.6
CDU;2013;22.6
SPD;2017;17.9
SPD;2013;26.1
Linke;2017;21.5
Linke;2013;18.7
Gruene;2017;17.2
Gruene;2013;16.7
AfD;2017;8.2
AfD;2013;3.9
FDP;2017;8.7
FDP;2013;3.7
Sonstige;2017;7.9
Sonstige;2013;8.3",
header = TRUE,
sep = ";",
)

colors_Jahr = c("black", "red")

my.settings <- list(
superpose.polygon = list(col = colors_Jahr)
)

barchart(
data = mitte_table,
Ergebnis ~ Partei,
groups = Jahr,
horizontal = FALSE,
main = "Zweitstimme im Wahlkreis Mitte",
xlab = "Parteien",
ylab = "Stimmenverteilung in %",
auto.key = TRUE,
par.settings = my.settings
)

Answer: Something like this? (Using ggplot2.)

Two caveats:

I didn't attempt to match the colors to the parties. But that should be easy to fix, just use a different color vector.
It's hard in ggplot2 to get the bars to overlap, as in the example. If you insist on that then some more work is required.

Here is the code:
require(dplyr)
require(ggplot2)

mitte_table <- read.table(text = "Partei; Jahr; Ergebnis
CDU;2017;18.6
CDU;2013;22.6
SPD;2017;17.9
SPD;2013;26.1
Linke;2017;21.5
Linke;2013;18.7
Gruene;2017;17.2
Gruene;2013;16.7
AfD;2017;8.2
AfD;2013;3.9
FDP;2017;8.7
FDP;2013;3.7
Sonstige;2017;7.9
Sonstige;2013;8.3",
header = TRUE,
sep = ";",
)

# make combined dark and light color palette
cols_dark <- c("#CD8E04", "#5E9FC8", "#028D67", "#D6CB35", "#0266A0", "#BB571E", "#AE7192", "#898989")
cols_light <- c("#FFB746", "#7DCCFF", "#4BC095", "#F9ED51", "#579BDB", "#FF834A", "#EC99C6", "#B7B7B7")
colors <- c(rbind(cols_dark, cols_light))

# add a column that has a smaller number for the larger year and vice versa
mitte_table <- mutate(mitte_table, order = 10000 - Jahr)

# reorder levels so they are in the order in which they are in the table
mitte_table$Partei <- factor(mitte_table$Partei, levels = unique(mitte_table$Partei))

# the trick is to fill by a factor that combines the party name and the order (10000 - year)
ggplot(mitte_table, aes(x=Partei, group=order, y=Ergebnis, fill=factor(paste0(Partei,order)))) +
  geom_col(position="dodge") +
  scale_fill_manual(values = colors,
                    breaks = paste0(mitte_table$Partei[1], 10000-c(2017, 2013)),
                    labels = c("Wahl 2017", "Wahl 2013"),
                    name = "") +
  scale_y_continuous(limits = c(0, 29), expand = c(0, 0)) +
  # override the fill aes to get gray colors in the legend
  guides(fill = guide_legend(override.aes = list(fill = c("#9A9A9A", "#C5C5C5")))) +
  theme_minimal(14) +
  theme(legend.position = "bottom")

Comment: Thanks so much for your helpful reply and the useful comments!


Other unbiased estimators than the BLUE (OLS solution) for linear models

Question: For a linear model the OLS solution provides the best linear unbiased estimator for the parameters.
Of course we can trade in a bias for lower variance, e.g. ridge regression. But my question is regarding having no bias. Are there any other estimators that are somewhat commonly used, which are unbiased but with a higher variance than the OLS estimated parameters?
If I would have a huge data set I could of course sub-sample it and estimate the parameters with less data, and increase the variance. I assume this could be hypothetically useful.
This is more of a rhetorical question, because when I have read about BLUE estimators, a worse alternative is not provided. I guess that providing worse alternatives could also help people understand the power of BLUE estimators better.
Comment: Relevant:  http://andrewgelman.com/2015/05/11/theres-no-such-thing-as-unbiased-estimation-and-its-a-good-thing-too/
Comment: @RichardHardy, I also tried the MLE, with the results you anticipated.
Comment: What about a maximum likelihood estimator? E.g. if you think your data is sampled from a $t$ distribution with a relatively low degrees of freedom parameter ($t(3)$ or $t(4)$ may be characteristic to financial returns), a maximum likelihood estimator would not coincide with OLS but I guess it would still be unbiased.
Answer: One example that comes to mind is some GLS estimator that weights observations differently although that is not necessary when the Gauss-Markov assumptions are met (which the statistician may not know to be the case and hence apply still apply GLS).
Consider the case of a regression of $y_i$, $i=1,\ldots,n$ on a constant for illustration (readily generalizes to general GLS estimators). Here, $\{y_i\}$ is assumed to be a random sample from a population with mean $\mu$ and variance $\sigma^2$.
Then, we know that OLS is just $\hat\beta=\bar y$, the sample mean. To emphasize the point that each observation is weighted with weight $1/n$, write this as
$$
\hat\beta=\sum_{i=1}^n\frac{1}{n}y_i.
$$
It is well-known that $Var(\hat\beta)=\sigma^2/n$.
Now, consider another estimator which can be written as
$$
\tilde\beta=\sum_{i=1}^nw_iy_i,
$$
where the weights are such that $\sum_iw_i=1$. This ensures that the estimator is unbiased, as
$$
E\left(\sum_{i=1}^nw_iy_i\right)=\sum_{i=1}^nw_iE(y_i)=\sum_{i=1}^nw_i\mu=\mu.
$$
Its variance will exceed that of OLS unless $w_i=1/n$ for all $i$ (in which case it will of course reduce to OLS), which can for instance be shown via a Lagrangian:
\begin{align*}
L&=V(\tilde\beta)-\lambda\left(\sum_iw_i-1\right)\\
&=\sum_iw_i^2\sigma^2-\lambda\left(\sum_iw_i-1\right),
\end{align*}
with partial derivatives w.r.t. $w_i$ set to zero being equal to $2\sigma^2w_i-\lambda=0$ for all $i$, and $\partial L/\partial\lambda=0$ equaling $\sum_iw_i-1=0$. Solving the first set of derivatives for $\lambda$ and equating them yields $w_i=w_j$, which implies $w_i=1/n$ minimizes the variance, by the requirement that the weights sum to one.
Here is a graphical illustration from a little simulation, created with the code below:
EDIT: In response to @kjetilbhalvorsen's and @RichardHardy's suggestions I also include the median of the $y_i$,  the MLE of the location parameter pf a t(4) distribution (I get warnings that In log(s) : NaNs produced that I did not check further) and Huber's estimator in the plot.

We observe that all estimators seem to be unbiased. However, the estimator that uses weights $w_i=(1\pm\epsilon)/n$ as weights for either half of the sample is more variable, as are the median, the MLE of the t-distribution and Huber's estimator (the latter only slightly so, see also here).
That the latter three are outperformed by the OLS solution is not immediately implied by the BLUE property (at least not to me), as it is not obvious if they are linear estimators (nor do I know if the MLE and Huber are unbiased).
library(MASS)
n <- 100
reps <- 1e6

epsilon <- 0.5
w <- c(rep((1+epsilon)/n,n/2),rep((1-epsilon)/n,n/2))

ols <- weightedestimator <- lad <- mle.t4 <- huberest <- rep(NA,reps)

for (i in 1:reps)
{
  y <- rnorm(n)
  ols[i] <- mean(y)
  weightedestimator[i] <- crossprod(w,y)
  lad[i] <- median(y)
  mle.t4[i] <- fitdistr(y, "t", df=4)$estimate[1]
  huberest[i] <- huber(y)$mu
}

plot(density(ols), col="purple", lwd=3, main="Kernel-estimate of density of OLS and other estimators",xlab="")
lines(density(weightedestimator), col="lightblue2", lwd=3)
lines(density(lad), col="salmon", lwd=3)
lines(density(mle.t4), col="green", lwd=3)
lines(density(huberest), col="#949413", lwd=3)
abline(v=0,lty=2)
legend('topright', c("OLS","weighted","median", "MLE t, 4 df", "Huber"), col=c("purple","lightblue","salmon","green", "#949413"), lwd=3)

Comment: Another possibility would be (robust) estimators based on minimizing a criterion such as $W=\sum_{i=1}^n w(e_i)$ where $e_i$ is the ith residual and $w$ is some symmetric function, convex or non-convex, with (global) minimum at 0, $w(0)=0$.  The Huber estimator would be an example.
Comment: Neat! I think this is a very simple illustrative example, bit more general than the one I came up with. When people are learning about estimators in a frequentist setting I feel that these kind of examples are often missing, they really help you get a better grasp of the concept.
Comment: @kjetilbhalvorsen, I now also include the Huber estimator, which actually does rather well.


how many words are there of 5 letters that have at least one I and at least two T's, but no K or Y?

Question: So it is more of a riddle than research-level mathematics, but your help would be hugely appreciated.
Here is the full problem: With the Latin alphabet, how many words are there (counting all of them, even those that don't make sense) of 5 letters that have at least one I and at least two T's, but no K or Y?
I already know the answer because I coded it, but I'm looking for simple math proof. Here is my code.
<code>import itertools

alphabet = string.ascii_uppercase.replace("K", "").replace("Y", "")

count = 0
for word in itertools.product(alphabet, repeat = 5):
    if "I" in word and word.count("T") >= 2:
        count += 1

print (count)
</code>
The code answer is 15645
Thank you so much!
Comment: You can consider cases: one I, two Ts, and two other letters; one I, three Ts, and one other letter; one and four Ts, two Is, two Ts, and one other letter; two Is and three Ts; and three Is and two Ts.  Your code gives the correct answer.
Answer: prerequisite :
the number of permutation with n objects of which a are alike , b are alike , c are alike ... is
$$\frac{n!}{(a!*b!*c!*....)}$$
proof:
3 letters for the 5 letter word are fixed i.e (i,t,t)
lets signify all letters other than i,t,k,y using x
for the 2 letters left , we can have seven cases:
case 1 : i,i
case 2 : i,t
case 3 : i,x
case 4 : t,t
case 5 : t,x
case 6 : x,x but both letters are different
case 7 : x,x but both letters are the same
as these are all the cases that exist , the sum of all these cases will give us the answer
case 1 :
the set contan i,i,i,t,t
no of possible permutatons :
$$\frac{5!}{(2!*3!)} = 10$$
case 2 :
the set contain i,i,t,t,t
no of possible permutatons :
$$\frac{5!}{(2!*3!)} = 10$$
case 3 :
the set contain i,i,t,t,x (x represent any of the 22 letters)
no of possible permutations :
$$\frac{(22*5!)}{(2!*2!)} = 660$$
case 4 :
the set contains i,t,t,t,t
no of possible permutations :
$$\frac{5!}{4!} = 5 $$
case 5 :
the set contains i,t,t,t,x
no of possible permutations :
$$\frac{(22*5!)}{3!} = 440$$
case 6 :
the set contains i,t,t,x,x (with both x reprsent different letter )
no of possible permutations :
$$\frac{({22 \choose 2} *5!)}{(2!)} = 13,860$$
case 7 :
the set contains i,t,t,x,x (both x representing same letter )
no of possible permutations :
$$\frac{(22*5!)}{(2!*2!)} = 660$$
sum of all cases : 10 + 10 + 660 + 5 + 440 +13,860 + 660 = 15,645


How to generate a result list from pandas DataFrame

Question: I need to generate a list from pandas DataFrame . I am able to print the result,but  i don't know how to convert it to the list format.The code i used to print the result(without converting to list) is
df=pandas.DataFrame(processed_data_format, columns=["file_name", "innings", "over","ball", "individual ball", "runs","batsman", "wicket_status","bowler_name","fielder_name"])**
  #processed_data_format is the list passing to the DataFrame
t = df.groupby(['batsman','over'])['runs','ball'].sum()
print t

i am getting the result like
Sangakara 1   10   5

          2    0   2

          3    3   1

    sewag 1    2   1

          2    1   1

I would like to convert this data into list format like
[ [sangakara,1,10,5],[sangakara,2,0,2],[sangakara,3,3,1],[sewag,1,2,1][sewag,2,1,1] ]
Answer: You can use to_records:
import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5]})

>>> list(df.to_records())

 [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]

This will make a list of tuples. Converting this to a list of lists (if you really need this at all), is easy.
Comment: Thank you .It works, How to convert it to List of lists??
Comment: @EdwinBaby See [here](http://stackoverflow.com/questions/14831830/convert-a-list-of-tuples-to-a-list-of-lists).
Comment: The answer is really helpful for me, Since i am new to StackOverflow i did'nt know about the things .So, thanks for point out the things


Continuous accelerometer updates while in the background on iOS

Question: I have researched this topic thoroughly before asking the question but need to ensure that I have come to the right conclusions and, if so, I would like help on implementing this as efficiently as possible.
It is essential for my app to receive accelerometer updates every 5 seconds or so and may be more quickly under certain situations; without this feature, its not a very useful app.
So, how to go about achieving this? The basic strategy is to use the method:
[cmMotionManager startDeviceMotionUpdatesToQueue:...]

with an appropriate deviceMotionUpdateInterval and then to somehow 'make sure' your application never gets suspended ie. you have to implement one of the background modes (e.g.  Location, Background Audio, VOIP etc)
This is the strategy used by many applications already on the app store such as Sleep Cycle ("sound recording"), Nike+ and Pacer (sound playback).
(Correct me if there is another way to continuously get accelerometer information)
My problem is that my app won't be recording sound, doesn't need VOIP etc and doesn't require any of the new background fetch/remote notification API in iOS 7. So how to go about making sure I stay active in the background?
Well, since im designing an app that measures movement, its not a far stretch to receive Location information. My question is how to go about implementing location updates in the most efficient way possible given the fact that I don't really need these location updates at all while ensuring that my app is never suspended?
This is what I have at the moment in my app delegate:
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

- (void)applicationWillResignActive:(UIApplication *)application
{
    [self.locationManager startUpdatingLocation];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self.locationManager stopUpdatingLocation];
}

I have noticed that sometimes for a short while after the time I press the home button on my app, my app becomes suspended - presumably as Core Location tries to get a location fix to deliver to the app.
I would also like to know, once you have been awoken by a location update, how long do you have before the system suspends you again if a new location update doesnt arrive? Will I have to try and receive continuous location updates (navigation style) to ensure I am never suspended?
Please help!
Thanks
Comment: possible duplicate of [iPhone collecting CoreMotion data in the background. (longer than 10 mins)](http://stackoverflow.com/questions/20766139/iphone-collecting-coremotion-data-in-the-background-longer-than-10-mins)
Comment: did u find your answer?
Answer: Considering this was asked 3 years ago, I'm going to try and give a response applicable to 2017. If you are using Swift I would strongly suggest using this framework https://github.com/MHaroonBaig/MotionKit.
It makes it very trivial to use CoreMotion services. There is probably another friendly wrapper for Core Location services.
I found another SO question that seems to have answered this using your approach of hijacking location services to stay active in the background.
Run app for more than 10 minutes in background
Hopefully this helps. I'll just leave a word of caution that using location services to get continuous accelerometer data in the background without actually needing the location services would probably be grounds to have your app rejected from the app store. Navigation apps genuinely use both location and accelerometer data. The simple answer would be to add a feature that actually uses the location to justify getting the accelerometer data in the background. Anyway, best of luck.


Experiments where the treatment is such that the act of applying the treatment to some people within the group and not others undermines the treatment

Question: Let's say we have an experiment where we want to apply some treatment to some group to test whether the treatment "works". But the treatment is such that the act of applying the treatment to some people within the group and not others actually undermines the treatment; in other words, in order for the treatment to work "properly" / to "full effectiveness", the treatment must be applied to the entire group. In the world of experimental design, what is this phenomenon called? It seems to me like it might be considered some kind of "interaction" or dependency effect? Is there an area of experimental design that deals with this sort of stuff? Is this a case where so-called "observational studies" or "observational experimental design" are more suitable than the so-called "controlled trial" / "randomised controlled trial" sort of experimental design?
Comment: Yes. For more on this, look at the literature on clustered RCT's.
Comment: I'd call it group effects. E.g.: exterminators are more effective when they can apply their treatment to every unit in a building.
Comment: @MattF. As per Demetri Pananos's answer, it seems to be "interference" from the "non-interference assumption". From *Design of Observational Studies*, second edition, by Paul R. Rosenbaum:
"The notation for treatment effects appears innocuous, but it actually entails a fairly strong assumption, called "no interference between units" by David Cox [12, §2.4], namely "that the observation on one unit should be unaffected by particular assignment of treatments to other units."" [...]
Comment: [...] In our case, assignment of control to one unit diminishes the effectiveness of the (actual) treatment to those units that are assigned it.
Comment: For RCT's the natural units are often geographic units, e.g. everyone in a particular village is assigned either to treatment or to control, or all the patients at a particular primary care clinic, or all the students in a particular classroom, etc. Do you have natural clustering like this?
Comment: [...] Assuming the entire problem is that there exists an interference effect where the efficacy of a treatment is affected by whether or not everyone in some group is assigned to that treatment, and assuming there is some limiting minimum group size where this interference effect ceases (that is, assuming the treatment doesn't require every human being / member of the population to be assigned to the treatment), then [...]
Comment: [...] you can design an RCT with this limiting minimum group size as what would conventionally be the "individuals" and then split them into (two) "groups of groups" (for treatment vs control/placebo). Does this sound sensible / is this what you had in mind?
Comment: This sounds like an opposite of heard immunity or cluster effect.
Comment: If you think "interference" is a good answer, then you should post it as an answer, rather than as a rejection of a comment.
Comment: "In our case, assignment of control to one unit diminishes the effectiveness of the (actual) treatment to those units that are assigned it." Sounds somewhat similar to vaccine trials. If everyone isn't vaccinated, it diminishes the effectiveness of the vaccine for those who are vaccinated. Is a clustered RCT not possible such that natural groups of units are assigned (together) to either treatment or control?
Comment: @num_39 Hmm, what do you mean by "natural groups of units"?
Comment: @num_39 Ahh, I think you're speaking to an idea that I was thinking of: instead of just having a bunch of individuals and splitting them into groups, which is the canonical example of RCT design, we can use *groups* as the individuals and then split the groups into *larger groups* for the RCT design. [...]
Answer: A term you might be interested in is "Stable unit treatment value assumption (SUTVA)".  The scenario you describe is a violation of SUTVA and hence makes causal inference much more difficult.
Roughly, SUTVA is the assumption that potential outcomes are independent of the treatment status of other participants.  That is to say, whatever happens to me under treatment/control is independent of what group you are assigned to.  From your description, this seems to be the case since the treatment "effectiveness" (and hence I would argue the potential outcomes of the participants) are effected by the size of the treatment group.
Comment: Ahh, yes. This seems to be related to the "non-interference assumption" and kind of the opposite of "spillover"?


My code is looping once more than I want it to, I suspect something is wrong with my getchar statement

Question: Firstly, I would like to thank everyone here in advance. I look very forward to advancing in the realm of computer science, and helping others as I become more proficient.
Now here is my code:
#include <stdio.h>
#include <stdlib.h>

#define RECORDS 30

/*Questions
Formatting display() - can we use spaces to format?
Is the patient structure supposed to be global or local in enter()?
*/

void enter();
void display();
void update();
void loadDisk();
void writeDisk();
void emptyDisk();
void sort();
void clear();

struct patient
{
    char * name;
    int age;
    double highBP, lowBP, riskFactor;
};

struct patient * db[RECORDS];
int counter = 0;

main()
{
    int flag = 1;

    while (flag == 1)
    {
        printf("---------------------------------------------------------\n");
        printf("|\t(N)ew record\t(D)isplay db\t(U)pdate record |\n");
        printf("|\t(L)oad disk\t(W)rite disk\t(E)mpty disk    |\n");
        printf("|\t(S)ort db\t(C)lear db\t(Q)uit          |\n");
        printf("---------------------------------------------------------\n");
        printf("choose one: ");

        char selection = getchar();

        printf("selection %c\n", selection);

        if ((selection == 'n') || (selection == 'N'))
        {
        //New record
        enter();
        }

        else if ((selection == 'd') || (selection == 'D'))
        {
        //Display db
        //printf("display %d\n", flag);
        display();
        }

        else if ((selection == 'u') || (selection == 'U'))
        {
        //Update db
        update();
        }

        else if ((selection == 'l') || (selection == 'L'))
        {
        //Load disk
        loadDisk();
        }

        else if ((selection == 'w') || (selection == 'W'))
        {
        //Write disk
        writeDisk();
        }

        else if ((selection == 'e') || (selection == 'E'))
        {
        //Empty disk
        emptyDisk();
        }

        else if ((selection == 's') || (selection == 'S'))
        {
        //Sort db
        sort();
        }

        else if ((selection == 'c') || (selection == 'C'))
        {
        //Clear db
        clear();
        }

        else if ((selection == 'q') || (selection == 'Q'))
        {
        //Quit
        flag = 0;
        }

        else
        {
        printf("not a vaild input\n");
        }
    }
}

void enter()
{
    /*struct patient temp;

    printf("name: "); sscanf("%s", temp.name);
    printf("age: "); scanf("%d", temp.age);
    printf("high bp: "); scanf("%f", temp.highBP);
    printf("low bp: "); scanf("%f", temp.lowBP);

    db[counter] = (struct patient *) calloc(1, sizeof(temp));
    *db[counter] = temp;

    //printf("%s, %d, %f, %f", db[counter]->name, db[counter]->age, db[counter]->highBP, db[counter]->lowBP);
    counter++;*/
}

void display()
{

}

void update()
{

}

void loadDisk()
{

}

void writeDisk()
{

}
void emptyDisk()
{

}

void sort()
{

}

void clear()
{

}

The issue I am having when running it is that the menu displays twice after I enter an option. I am having trouble understanding what is going wrong, but I suspect it has something to do with getchar which storing the selection and the new line character, hence running it twice. This would also mean the final else statement would run, which it does.
I think I have triangulated the problem, just unsure how to fix it. Thank you in advance!
Comment: FYI: `getchar` returns an `int`, not a `char`. Before casting it back to an `char`, you must first test it against the constant `EOF` to see if you've hit the end-of-input (e.g., control-D on a Unix-ish terminal, or from end of input in a pipe, or redirected file). You should probably treat that as if the user had entered `q`. Also, doesn't C have a `switch` statement?
Answer: If the problem is with getchar, which it does look to be, why not use a different function?
Try replacing:
char selection = getchar();

With this:
char selection;
scanf("%c",&selection);

If you're worried about overflow in the single character, then do a scanf() for a string and only use the first character in your checks:
char selection, selectionstr[20];
scanf("%s",selectionstr);
selection = selectionstr[0];

Comment: I tried your first solution, it didn't work. Same problem. Am I trying your second one now. Thanks!
Comment: Bingo! Your second one worked! Now I am trying to figure out why your first didn't, as I tried the exact same thing before...Thanks again!
Comment: Happy to help.  I would recommend looking at the comment @derobert left in your original statement about using a switch-case block rather than a bunch of if-else statements.
Answer: getchar also returns '\n' character.
Comment: Thanks! I guessed that was what was causing the issue.
Answer: Yeah, the problem is that your input is always a string, at least one character followed by a newline.  I would either change your loop so that it terminates if selection is 'q' or use a function other than getchar and prune your input.
Comment: Any recommendations besides getchar? Thanks!
Comment: I would try scanf or one of it's cousins.
Answer: I think you can do this using curses! Here is a a website which you may find useful. Curses is a cursor control library for c.
From the manual:

Initially the terminal may or may not be in cbreak mode, as the mode is
  inherited;  therefore, a program should call cbreak or nocbreak explic-
  itly.  Most interactive programs using  curses  set  the  cbreak  mode.
  Note  that  cbreak overrides raw.
Comment: Hmm I'll look into that. For the time being, I have to do what my teacher is asking :) Thanks!


What is the distribution of the reciprocal of a random variables with U[a,b]?

Question: Suppose that $Y_n$ are random variables that are uniformly distributed in the range $[a,b] (a>0)$.
What is the distribution of reciprocal $Z_n=\frac{1}{Y_n}$?
I found that it is Pareto distribution when $a=0$. But I found nothing when $a>0$.
Comment: You could always try to calculate the density of $Z_n$. For this, you would have to find $F(x) := P(Z_n \leq x)$.
Answer: We first find the cumulative density function $F_Z(z) = P(Z \leq z)$ and then differentiate it to obtain the probability density function $f_Z(z)$. Note that
\begin{align*}
F_Z(z) = P(Z \leq z) = P\left (\frac{1}{Y} \leq z \right) = P\left(\frac{1}{z} \leq Y \right) = 1 - P\left(Y < \frac{1}{z} \right) = 1 - F_Y\left( \frac{1}{z}\right),
\end{align*}
where $F_Y$ is the cumulative distribution function of $Y$. Then, we can write:
$$\tag{1} F_Z(z) =1 - F_Y\left( \frac{1}{z}\right) = 1 - \int_{a}^{z^{-1}}\frac{1}{b-a}dx = 1 - \frac{z^{-1} - a}{b-a}.$$
If we set $a=0$ then we get Paretto cumulative density function. If we differentiate $F_Z(z)$ with $a=0$ we get Paretto probability density function $f(z) = \frac{b^{-1}}{z^2}$ with parameters $\alpha=-1$ and the scale parameter $b$.
Otherwise, just differentiate (1) and you obtain the probability density function $f_Z(z) = \frac{z^{-2}}{b-a}$.


[Dummit and Foote : Algebra] 2.1 Subgroups Question 10(b) Some help/hint please

Question: So, the question goes like this "Prove that the intersection of an arbitrary nonempty collection of subgroups of $G$ is again a subgroup of $G$ (do not assume the collection is countable)."
At first, I thought of approaching this question with a normal mathematical induction. ( Assume true for base case, prove that if it's true for $n$ number of set, then it must be true for $n+1$ number of set and so on so forth) However, the bold part of the question confused me. Isn't it the case that if we use MI to prove this, the set is countable? ( although, it could be countably infinite ). Or, does the question actually ask us not to assume the number of sets is finite instead?
Thanks in advance for the pointers.
Comment: Mathematical induction would not work even for a countably infinite collection.  The collection is supposed to be "arbitrary", not assumed finite or countable.  The argument is more direct than induction.
Comment: I think the authors **are** "Dummit and **Foote**"; **not** "Dummit and **Forte**"
Comment: by definition is OK.
Comment: Thanks a lot for the help guys.
Comment: Well, you could prove it by transfinite induction, I suppose.  (Not that you should or that it is at all necessary or helpful to do it that way...)
Comment: @biralol You have received some answers, and I think they answer your question. Please accept the answers given.
Answer: The following steps lead to a solution:
(1) Let $\{H_{\alpha}\}_{\alpha\in A}$ be a collection of subgroups of a group $G$ where $A$ is an index set and let $H=\bigcap_{\alpha\in A} H_{\alpha}$ be their intersection. Prove directly from the definitions that $H$ is a subgroup of $G$. For example, if $x\in H$, then by definition of "intersection", $x\in H_{\alpha}$ for all $\alpha\in A$. Since $H_{\alpha}$ is a subgroup of $G$, we know that $x^{-1}\in H_{\alpha}$ for all $\alpha\in A$. In particular, $x^{-1}\in H$ since $H=\bigcap_{\alpha\in A} H_{\alpha}$.
(2) Prove similarly (and carefully) that if $x,y\in H$, then $xy\in H$. (Hint: think carefully about the definition of "intersection" and relate to the proof given in (1) above.)
The following exercises will strengthen your understanding of the concepts relevant to the the question you asked:
Exercise 1: Let $H,K\subseteq G$ be subgroups and supppose $H\cup K$ is also a subgroup of $G$. Prove that either $H\subseteq K$ or $K\subseteq H$. (Hint: prove this by contradiction. In particular, if neither of the alternatives in the second sentence holds, choose $x\in H$, $x\not\in K$ and $y\in K$, $y\not\in H$. Note that $x,y\in H\cup K$ and use the fact that $H\cup K$ is a subgroup of $G$.)
Exercise 2: Let $G$ be a group and let $x\in G$. The centralizer of $x$ in $G$ is the set $\textbf{C}_G(x)=\{g\in G:xg=gx\}$. Prove that $\textbf{C}_G(x)$ is a subgroup of $G$.
Exercise 3: Let $G$ be a group with the property that there do not exist three elements $x,y,z\in G$ no two of which commute. Prove that $G$ is abelian. (Hint: fix $x,y\in G$; in order to prove that $x$ and $y$ commute, write $G$ as the union of two appropriately chosen subgroups and appeal to Exercise 1 above. Exercise 2 is relevant.)
Exercise 4: Let $H$ and $K$ be subgroups of a group $G$ such that $HK=KH$. (Let me recall that $HK=\{hk:h\in H \text{ and } k\in K\}$ and $KH=\{kh:h\in H \text{ and } k\in K\}$.) Prove that $HK=KH$ is a subgroup of $G$. Conversely, if $HK$ (or $KH$) is a subgroup of $G$, prove that $HK=KH$. (Hint: the proof (like the solution to your question) is a simple manipulation of the definitions which you should carefully work through.)
Exercise 5: Let $H$ be a subset of $G$ such that for every proper subgroup $K$ of $G$, we have that $H\cap K$ is a subgroup of $G$. Is it necessarily true that $H$ is a subgroup of $G$?
Comment: I should mention that exercise 3 is a beautiful exercise because it looks (at a first glance, at least) like a simple exercise in logic. However, it is more subtle than it first appears. In particular, it is a good (challenging) exercise to first ask a student *who has only seen the definition of a group* to solve. Once the student has seen Exercises 1 and 2 above, it is then again worth asking him to solve Exercise 3 (but without explicitly mentioning Exercises 1 and 2 as hints). The student will then appreciate how the notion of a "subgroup" provides a more unified approach to group theory.
Comment: Dear Amitesh, A minor point, but in your steps (1) and (2) you write the group operation additively, rather than multiplicatively (as would seem more natural for a question that doesn't require the groups to be abelian).  Is there a reason for this?  Best wishes,
Comment: Dear Matt E, I have been thinking too much about commutative rings lately! Thank you for noting this. I will fix it. Regards, Amitesh
Comment: @Amitesh Datta Please see my answer below:
Comment: @DLim Thank you for noting this; I have seen and commented on your answer below.
Answer: For statement 2 above, choose $x,y$ such that $x,y \in A\cap B$. Then this is the same as saying that ($x$ is in $A$ and $B$) and ($y$ is in $A$ and $B$). Because the logical connective $^$ is associative and commutative we can move the paranthese around and say that this is equivalent to ($x \in A$ and $y \in A$) and ($x \in B$ and $y \in B$).
Because $A$ and $B$ by themselves are subgroups, it follows that $xy \in A$ and $xy \in B$, so that $xy \in A \cap B$.
Of course this proof can be extended to the case of an arbitrary (finite?) intersection of subgroups.
For exercise 2, I can prove a similar problem: Prove that the set $Z(G) = \{z\in G : zx = xz \quad \forall x \in G\}$, i.e. the center of the group is a subgroup of $G$.
Clearly $1_G$ is in $Z(G)$ as $1_Gx = x1_G$ for all $x \in G$. Now suppose $z_1$ and $z_2$ are in $Z(G)$. Then $z_2z_1x = z_2xz_1 = xz_2z_1$ so that $z_1z_2 \in G$. Finally, suppose $z \in Z(G)$. We need to show that $z^{-1} \in G$. If
$\begin{eqnarray*}
xz &=& zx, \\ \implies z^{-1}(xz)x^{-1}
&=& z^{-1}(zx)x^{-1} \\
&=& (z^{-1}z)xx^{-1} \\
&=& z(z^{-1}x)x^{-1}. \end{eqnarray*}$
Now $z^{-1}(xz)x^{-1} = z(xz^{-1})x^{-1}$ using the fact that $xz = zx$. We conclude that
$\begin{eqnarray*}z(xz^{-1})x^{-1} &=& z(z^{-1}x)x^{-1}\\
\implies xz^{-1} &=& z^{-1}x. \end{eqnarray*}$
So $z^{-1} \in Z(g)$ and by the facts above, we conclude that $Z(G) \leq G.$
P.S. By the way exercise 1 is part of our recent assignment in algebra!
Comment: +1 The solutions are certainly correct. However, there is an easier way to solve ***Exercise 2***. Indeed, if $z\in \textbf{Z}(G)$, then $zx=xz$ for all $x\in G$. Let us invert both sides of the equation $zx=xz$ and obtain $x^{-1}z^{-1}=(zx)^{-1}=(xz)^{-1}=z^{-1}x^{-1}$. Since every element in $G$ is of the form $x^{-1}$ for some $x\in G$, it follows that $z^{-1}\in \textbf{Z}(G)$.
Comment: Also, the proof you have given in your first paragraph extends to arbitrary (not necessarily finite) intersections of subgroups.
Comment: @Amitesh Datta Thanks for checking them. I won't mention the proof here but to prove exercise 1 is just an exercise in logic.
Comment: @Nice proof by the way. Just using the fact that $xz = zx$! I must be blind or something...


Why does this code use an .aspx file for JavaScript?

Question: I found some old code which I'm not sure I understand completely. The folowing is an .aspx page containing only JavaScript:
<%@ Page Language="C#" EnableSessionState="True" CodePage="65001" uiculture="auto" %>

<%
Response.ContentType = "text/plain";
%>

var csBackgroundColor;

function testfx() {
    csBackgroundColor.setAttribute('disabled', 'disabled');
}

and it was referenced like this:

I'm wondering why it wasn't just marked as completely a JavaScript file? Was it done this way so you could include code blocks?  With the file this way, I don't even get IntelliSense.
Comment: That's the only content of the file?
Comment: +1 @ClaudioRedi would like to see if there is more server-side processing...
Answer: First time I see something like that but you're right, the reason behind this is to make the file to be processed by the asp.net engine and run it as any other aspx page, giving him the chance to use server side code to build the js file.
If that's all the code in the file, it seems the only objetive was to set the character encoding (CodePage="65001" and the content type (Response.ContentType="text/plain"). It wouldn't make a lot of sense as you can imagine.
Answer: <hack>To get intellisense you could wrap the code in  blocks and remove them before saving.</hack>
This was probably created by a developer that didn't want to, couldn't, or didn't have the time to write object oriented JavaScript. Encapsulating the logic and configuring through a configuration object would allow you to de-couple the code from external variable dependencies, (e.g. var foo = <%= SomeServerSideVariable %>).


String length changes suddenly

Question: Here in this code, the character length is changing suddenly. Before introducing char file the strlen(str) was correct. As I introduced the new char file the strlen value of variable str changes.
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){

    char buf[BUFSIZ];

    if(!getcwd(buf,BUFSIZ)){
            perror("ERROR!");
    }

    cout << buf << endl;

    char *str;
    str = new char[strlen(buf)];
    strcpy(str,buf);
    strcat(str,"/");
    strcat(str,"input/abcdefghijklmnop");
    cout << str << endl;
    cout << strlen(str) << endl;

    char *file;
    file = new char[strlen(str)];
    cout << strlen(file) << endl;
    strcpy(file,str);
    cout << file << endl;
}

Comment: Your buffer `str` is too short. Why don't you use `std::string`?
Comment: What's the question?
Answer: Your code has undefined behavior because of buffer overflow. You should be scared.
You should consider using std::string.
  std::string sbuf;
  {
      char cwdbuf[BUFSIZ];
      if (getcwd(cwdbuf, sizeof(cwdbuf))
        sbuf = cwdbuf;
      else {
        perror("getcwd");
        exit(EXIT_FAILURE);
      }
 }
 sbuf += "/input/abcdefghijklmnop";

You should compile with all warnings & debug info (e.g. g++ -Wall -Wextra -g) then use the debugger gdb. Don't forget that strings are zero-byte terminated. Your str is much too short. If you insist on avoiding std::string (which IMHO you should not), you need to allocate more space (and remember the extra zero byte).
str = new char[strlen(buf)+sizeof("/input/abcdefghijklmnop")];
strcpy(str, buf);
strcat(str, "/input/abcdefghijklmnop");

Remember that the sizeof some literal string is one byte more than its length (as measured by strlen). For instance sizeof("abc") is 4.
Likewise your file variable is one byte too short (missing space for the terminating zero byte).
file = new char[strlen(str)+1];

BTW on GNU systems (such as Linux) you could use asprintf(3) or strdup(3) (and use free not delete to release the memory) and consider using valgrind.

String length changes suddenly