Ordem Crescente em uma lista encadeada em c

Question: #include <stdio.h>
 #include <stdlib.h>

typedef struct LISTA{

int dado;
struct LISTA *prox;

}lista;

lista *insere(lista *p, int valor){

lista *novo;
novo=(lista*)malloc(sizeof(lista));
novo->dado = valor;
novo->prox = p;
return novo;

 }

void imprime(lista *p){
lista *novo;
for(novo = p; novo!= NULL; novo=novo->prox){
    printf("%d",novo->dado);

}

 }
 lista *ordemCrescente(lista *p){
lista *aux = NULL;
lista *novo = p;

int *recebe;
int x=0;
int menor=0;
while(novo != NULL){
    if(novo->dado < menor){
        aux = novo->prox;
         novo = novo->dado;
         novo->dado = aux;
    return p;
    }

    novo= novo->prox;
}

     }

     main(){

  lista *l,i;
  lista *primeiro, *ultimo;
l = NULL;
l = insere(l, 20);
l = insere(l, 30);
l = insere(l, 40);
l = insere(l, 50);
l = insere(l, 60);

imprime(l);
printf("\n");
l = ordemCrescente(l);
imprime(teste);
  }

Comment: Esta função deveria fazer o que exatamente? Mostrar os elementos em ordem crescente? Porque se for, não há nenhum `printf` aí. O que ela parece estar tentando fazer (mas faz errado) é buscar o menor elemento na lista, mas o nome dela não indica isso. O que é que ela deveria fazer? Como e onde você está usando esta função?
Comment: Eu posso postar o código inteiro mas basicamente era pra ela colocar em ordem crescente oque já foi inserido na lista que é feito por outra função e também tem uma funcão print. O problema  é que a função esta errada.
Answer: Primeiro vou começar com os problemas mais simples.

Faltou um espaço após o %d na função imprime.
Evite usar l ou O como nome de variáveis, pois é muito fácil confundir isso com os números 1 e 0.
Aprenda a identar adequadamente o seu código. Facilita muito a sua vida.

Agora vamos para o mais difícil. Observe isso:
        aux = novo->prox;
        novo = novo->dado;
        novo->dado = aux;

novo é um ponteiro. Ao fazer novo->dado, você vai pegar um inteiro e atribuir a um ponteiro (o seu compilador deve estar te dando uma warning por causa disso). Com isso, novo tornar-se-á um ponteiro inválido. Ao fazer novo->dado = aux;, o resultado é que você vai tentar acessar o endereço inválido e colocar alguma coisa lá. O resultado será uma falha de segmentação.
A forma correta de permutar novo e novo->prox seria assim:
        int aux = novo->dado;
        novo->dado = novo->prox->dado;
        novo->prox->dado = aux;

Apesar disso, o procedimento de organização como um todo está totalmente errado. O return dentro dele faria com que algo seja retornado na primeira "desinversão" de itens a ser feita, e não depois de todas terem sido feitas. Mesmo se não houvesse o return, o while percorre cada elemento da lista uma única vez (O(n)), e portanto é impossível que uma abordagem como essa sirva para ordenar a lista vez que a complexidade mínima possível é O(n log n). Para piorar, qualquer abordagem baseada em varrer a lista e permutar elementos vizinhos vai ter obrigatoriamente desempenho mínimo O(n²).
Assim sendo, não há nada na sua função ordemCrescente que seja aproveitável para uma boa solução. Ela teria que ser refeita do zero.
Sugiro estudar os algoritmos de ordenação existentes para entender como eles funcionam e então escolhe um deles para implementar. Dentre os que você pode tentar implementar com listas ligadas (use dois whiles um dentro do outro para fazer isso), são o Bubble sort, o Selection sort e o Insertion sort. Todos eles terão complexidade O(n²) e todos eles têm como estratégia permutar elementos vizinhos diversas vezes até que a lista esteja ordenada.
Se quiser ir além e procurar algoritmos de ordenação mais eficientes mas que provavelmente não têm como ser implementados com listas ligadas (ao menos não de forma eficiente), você pode olhar o Shell sort e o Quick sort, que embora ainda sejam O(n²) no pior caso, são O(n log n) no caso médio. Ou então olhar o Heapsort e o Merge sort que têm complexidade O(n log n) em todos os casos.
Como bônus, há também o Bogosort que é um dos algoritmos mais ineficientes já inventados. Falo sobre ele aqui.


Zynq/ Petalinux : Unknown command 'gzwrite' - try 'help'

Question: For folks familiar with Zynq, Petalinux and u-boot.
I am using a microzed board, and trying to boot it using an SD card. The boot.bin file is generated using Petalinux 2018.3 SDK. The u-boot runs and then gives error Unknown command 'gzwrite' - try 'help'.
This error comes while executing the command install_ext4=gzwrite mmc 0 ${rootfsloadaddr} ${filesize} 0x100000 ${rootfsmmcstart}\0
I ran help command on the u-boot console and gzwrite doesn't show up in the list of commands. But the thing is that boot.bin was generated by petalinux and that includes the code above to load rootfs.
Do I need to tune up Petalinux project, is my board missing anything ?
Answer: This type of problem occurred when,  LC_ALL is set to some languages encoding format such as  "en_US.UTF-8"
That's why before building u-boot, unset the language encoding format as below:-
In the terminal where you are building u-boot  run "unset  LC_ALL".


Does Objective-C auto generate setter and getter?

Question: I am calling a method from other class, as below
@property (nonatomic,strong) CalculatorModel *calculatorModel;

double result = [self.calculatorModel result:operator];

however this method doesn't received the message from the caller. Until I wrote the getter my self
- (CalculatorModel*)calculatorModel {
    if (!_calculatorModel) _calculatorModel = [[CalculatorModel alloc]init ];
    return _calculatorModel;
}

and it works. why, I remember once you did @property, the Objective-C will generate setter and getter automatically. Am I wrong?
Thanks
updated:
Comment: you are right, but the synthesized getter wouldn't lazily allocate an instance of the requested property like you did. this is why the message 'result' was sent to nil
Comment: Yes, that's the point of a property.
Answer:
Does Objective-C auto generate setter and getter?

Well, rather the compiler, but yes, recent versions of Clang have this feature. You don't need to manually synthesize properties anymore.
Comment: @AnoopVaidya I prefer the answer from xxd, and I think the point is the Lazy instantiation.
Comment: @TomH: Your title says something else, your question says something else. He picked another point to discuss!!!
Comment: @H2CO3: I didn't, downvote needs 125 reputation, however I saw you have -4 reputation from my question. Anyway, still thanks for answered my question.
Comment: @AnoopVaidya added "anymore" to make it perfect :P
Comment: You can also say "This is available from XCode4.4+" :)
Comment: @AnoopVaidya I can't - it's unrelated to the version of Xcode.
Comment: Then he may ask I have XCode3.2, can i use that clang.
Comment: @AnoopVaidya Then I reply, 'irregardless of the version of your Xcode installation, clearly depending on the *compiler version* only, you may or may not'.
Comment: @AnoopVaidya I hope too. He should, definitely.
Comment: @TomH : So you are very much updated!!! Yesterday only I downloaded XCode4.6, Even AppCode uses same LLVM/clang compiler
Comment: @TomH No need to downvote my answer, it's technically correct.
Answer: Seems like You don't need to manually synthesize properties anymore from xCode4.5.The IDE will help you do it.But terrible thing is if you open your project on xCode4.3 or xCode4.4, it will not work,lots of warning will appear,then you should add the code by yourself .
Comment: well.Got your point.The getter and setter just return the pointer's value of property.If your property isn't init,it's still nil, then , return nil to you. it's always return what you give it,case you give it nothing.
Answer: You are right. However you still have to initialize the property by using [[Class alloc] init]. Like we set the property for NSMutableArray, @property (nonatomic, strong) NSMutableArray *anArray; and before you are using anArray you have to init it as _anArray = [[NSMutableArray alloc] initWithCapacity:10];
the - (CalculatorModel*)calculatorModel method is called Lazy instantiation, which will take over the [[Class alloc] init] job before calling, this will give help on both performance and memory control.


Is Single-member relation an equivalence

Question: Single-member relation is an equivalence.
For example the relation R={(1,1)}.  Is R equivalence relation on a set?
Thanks.
Comment: $R$ is, but $(1,2)$ not.
Comment: "Is R equivalence relation on a set?" If the set is {1}, yes. Otherwise, it is not.
Answer: Not every single-member relation is an equivalence.
Counter-example: $R_2 = ${$(1, 2)$}
Comment: So $R_1 = ${$(1, 1)$} is  an equivalence?
Comment: Yes. But not any single-member relation
Comment: Actually $\{(1,1)\}$ is **not** an equivalence relation, except on the set $\{1\}$.
Comment: You mean the relation $R_1 = ${$(1,1)$} on set   $S = ${$1, 2, 3, 4$} , is not an equivalence?
Comment: @wokwok: no it isn't since it doesn't contain $(2,2)$, $(3,3)$, or $(4,4)$.


Proof in a extended side triangle

Question: Let the base BC of triangle ABC be extended at D. Prove that DCA > DBA, and DCA > BAC. So the more intuitive approach to prove would be to first let CBA, BAC, ABC be $x, y, 180 - x - y$ respectively, so that DCA is $x + y$, and then compare $x + y$ with $x$, and $y$. However, the result that angles in a triangle add to 180 cannot be used since the book that has this problem has only proved the SSS, SAS theorems, as well as it introduced to basic euclidean geometry axioms. So I am stuck on a way to prove without using results which are not proven yet.
Comment: I simply forgot to add the tick to the solution you posted
Comment: This is a famous theorem by Euclid: https://en.wikipedia.org/wiki/Exterior_angle_theorem
Comment: Here's Euclid's proof: http://aleph0.clarku.edu/~djoyce/elements/bookI/propI16.html
Comment: Is the proof in the answer too difficult? Or else?
Answer: The Elements - Book I - Proposition 16 (transl. by T. L. Heath)
In any triangle, if one of the sides is produced, then the exterior angle is greater than either of the interior and opposite angles.

Let ABC be a triangle, and let one side of it BC be produced to D.
I say that the exterior angle ACD is greater than either of the interior and opposite angles CBA and BAC.
Bisect AC at E. Join BE, and produce it in a straight line to F.
Make EF equal to BE, join FC, and draw AC through to G.
Since AE equals EC, and BE equals EF, therefore the two sides AE and EB equal the two sides CE and EF respectively, and the angle AEB equals the angle FEC, for they are vertical angles.
Therefore the base AB equals the base FC, the triangle ABE equals the triangle CFE, and the remaining angles equal the remaining angles respectively, namely those opposite the equal sides. Therefore the angle BAE equals the angle ECF.
But the angle ECD is greater than the angle ECF, therefore the angle ACD is greater than the angle BAE.
Similarly, if BC is bisected, then the angle BCG, that is, the angle ACD, can also be proved to be greater than the angle ABC.
Therefore in any triangle, if one of the sides is produced, then the exterior angle is greater than either of the interior and opposite angles.

Proof in a extended side triangle


Sai do meu estágio e me removeram como colaborador, perdi todos meus commits no meu histórico

Question: Galera, trabalhei por 7 meses em uma empresa e depois que meu contrato acabou me tiraram como colaborador. Eu tinha em torno de 100 commits no projeto privado deles, porém todos eles sumiram do meu perfil do git. Alguém sabe se tem como eu ter no meu perfil minhas contribuições privadas de volta?
Answer: De acordo com a documentação do GitHub:

Private contributions are not shown by default and, when enabled, are completely anonymized to the general public. [...] Details of the issues, pull requests, and commits you have made on private repositories are only visible to your fellow repository collaborators.

Ou em tradução literal:

As contribuições privadas não são apresentadas por padrão e, quando ativadas, são completamente anonimizadas para o público em geral. [...] Os detalhes de issues, pull requests  e commits que você realizou em repositórios privados só são visíveis para seus colegas colaboradores de repositório.

Ou seja - tanto os administradores do projeto precisam habilitar a visualização anonimizada, quanto você precisa selecionar 'Public and Private Contributions' no painel de visualização de contribuições. Se eles não ativarem, seu conteúdo não pode ser visualizado no seu perfil.
Comment: É q antes os commits, mesmo com detalhes privados aos colaboradores, apareciam no meu github. Aparecia la pras pessoas fulano fez 100+ contribuições em repositorio privado. Porem desde minha remoção do repositorio isso sumiu do meu perfil tanto pra mim quanto para as pessoas. Eu só queria que aparecesse de volta isso, pq meu git no momento ta zerado ja q era meu primeiro estágio :)
Answer: Infelizmente não... Como você mesmo disse, o repositório é privado, de forma que, se você foi removido dele, o github desconsidera todas as suas contribuições ao mesmo.
No entanto, você pode continuar contribuindo com códigos open source! É uma ótima forma de aprender, e não será removida da sua lista de contribuições, somente se o projeto for deletado (mas seu fork vai se manter). Lembre-se, quantidade de contribuições não é uma métrica para qualidade de software ou para a skill do programador, por exemplo, eu posso fazer 5000 commits inúteis, enquanto outra pessoa pode solucionar um grande problema em apenas 1.
Um bom programador não é aquele que tem mais contribuições, mas aquele que sabe o que está fazendo e gosta do que faz.
Seja bem vindo ao StackOverflow PT!


objective c subclass UIImageView

Question: I'm trying to subclass UIImageView to add some custom functionality in it. I started trying to do the basics, just init an object with a given image and display it on the screen.
Using UIImageView everything works fine, but if i change my object from UIImageView to my custom class, no image is displayed.
Here's what i've done so far:
//Imager.h
#import <UIKit/UIKit.h>
@interface Imager : UIImageView {

}

-(id) init;
-(void) retrieveImageFromUrl: (NSString *)the_URL;

@end

//Imager.m
#import "Imager.h"
@implementation Imager
@synthesize image;

-(id)init
{
    self = [super init];
    return self;
}

-(void) retrieveImageFromUrl: (NSString *)the_URL{

     //Not implemented yet
}
@end

So, i am using this statment: cell.postImage.image = [UIImage imageNamed:@"img.png"];
Before this is executed, i also have postImage = [[UIImageView alloc] init];
If postImage is declared as UIImageView everything works as expected. But if i change it to Imager instead, then nothing is displayed.
What am i missing?
Comment: Why do you have `@synthesize image;`? You don't have a property defined? It looks like something is missing in your example.
Answer: You're synthesizing image, thus blocking calls to setImage on the superclass (i.e. UIImageView) when you attempt to use the dot notation to set the image.
Remove this line:
@synthesize image;

Comment: Thanks for your instant reply! That's what was causing the problem.
Just to make it clear, is it a general rule, if i don't want to customize getters/ setters in my subclass, i should not use @synthesize?
Comment: @CrisDeBlonde `@synthesize` exists to create accessor methods for you, it's up to you whether you use it when customizing getters and setters. See [Declared Properties](http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html).
Comment: Thanks a lot for answering. Now i think i've got it more clear.
Answer: I would suggest using an Objective-C "Category" instead of subclassing the UIImageView. As long as you don't have to add any member variables, a Category is a better solution. When you use a category you can call your extended functions on any instance of the original class (in your case UIImageView. That removes the need for you to consciously use your subclass anywhere you might want to use your new functions.
You can just do the following in a header:
@interface UIImageView (UIImageView+URL)

-(void) retrieveImageFromUrl: (NSString *)the_URL;

@end

Then in an implimentation file:
@implimentation UIImageView (UIImageView+URL)

-(void) retrieveImageFromUrl: (NSString *)the_URL
{
    // implimentation
}

@end

Then wherever you want to use your new function on a UIImageView, you just need to include the header file.
Comment: thanks a lot for replying! It's true i didn't know much about categories, but in this case later on, i will add some member variables that are needed, as well as some more methods. This is only the beginning of the subclass construction. Anyway, thanks again for answering!

objective c subclass UIImageView


Water and wine mixing problem

Question: This is a well-known problem involving a water barrel and a wine barrel, described here. The trick to solving the puzzle is that one need not make the calculations for each stage of the liquid movement. But if one does...
The units here are the quantity of liquid moved each time, e.g. cupfuls. At the end of each "take out/put back" movement, the amount of wine in one barrel is the same as the amount of water in the other, so we can consider just the two volumes of liquid without caring about what they are made from.
At the beginning the two volumes are $0$ and $n$, say.
After the first movement the volumes are $$\frac{n}{n+1}\text{ and }\frac{n^2}{n+1}.$$
After the second the volumes are $$\frac{n(2n)}{(n+1)^2}\text{ and }\frac{n(n^2+1)}{(n+1)^2}.$$
After the third the volumes are $$\frac{n(3n^2+1)}{(n+1)^3}\text{ and }\frac{n(n^3+3n)}{(n+1)^3}.$$
There is a pattern here suggesting that after $t$ goes the volumes are
$$\frac{n}{(n+1)^t}\sum_{k=0}^{t/2-1}{\binom{t}{t-2k}n^{2k}}$$ and $$\frac{n}{(n+1)^t}\sum_{k=0}^{t/2}{\binom{t}{t-2k-1}n^{2k+1}}.$$
As more liquid is moved the two volumes will each start to approach $\dfrac{n}{2}$.
To my question: how do we show that the two volumes above both tend to $\dfrac{n}{2}$ as $t\rightarrow\infty$?
Answer: If you have $\frac{n}{2}+w$ water in the water tank before a transfer, after a transfer each direction you have $\frac{n}{2}+w\frac{n-1}{n+1}$, so $w$ is driven to zero.
Answer: The upper limits on the summations should be $\lfloor t/2 \rfloor$ and $\lceil t/2 \rceil$, and you can simplify the binomial coefficients to get $$\frac{n}{(n+1)^t}\sum_{k=0}^{\lfloor t/2 \rfloor}\binom{t}{2k}n^{2k}\text{ and }\frac{n}{(n+1)^t}\sum_{k=0}^{\lceil t/2 \rceil}\binom{t}{2k+1}n^{2k+1}.$$
Now $$(n+1)^t = \sum_{k=0}^t \binom{t}{k}n^k\text{ and }(n-1)^t = \sum_{k=0}^t\binom{t}{k}(-1)^{t-k}n^k,$$ so
$$\begin{align*}
\frac12\left((n+1)^t+(n-1)^t\right) &= \frac12\sum_{k=0}^t\binom{t}{k}\left((1+(-1)^{t-k}\right)n^k\\
&= \begin{cases}
\sum_{k=0}^{\lfloor t/2\rfloor}\binom{t}{2k}n^{2k},&\text{if }t\text{ is even}\\
\sum_{k=0}^{\lceil t/2\rceil}\binom{t}{2k+1}n^{2k+1},&\text{if }t\text{ is odd},
\end{cases}
\end{align*}$$
and
$$\begin{align*}
\frac12\left((n+1)^t-(n-1)^t\right) &= \frac12\sum_{k=0}^t\binom{t}{k}\left((1-(-1)^{t-k}\right)n^k\\
&= \begin{cases}
\sum_{k=0}^{\lfloor t/2\rfloor}\binom{t}{2k}n^{2k},&\text{if }t\text{ is odd}\\
\sum_{k=0}^{\lceil t/2\rceil}\binom{t}{2k+1}n^{2k+1},&\text{if }t\text{ is even}.
\end{cases}
\end{align*}$$
It follows that $$\sum_{k=0}^{\lfloor t/2\rfloor}\binom{t}{2k}n^{2k} =
\begin{cases}
\frac12\left((n+1)^t+(n-1)^t\right),&\text{if }t\text{ is even}\\
\frac12\left((n+1)^t-(n-1)^t\right),&\text{if }t\text{ is odd}
\end{cases}$$
and $$\sum_{k=0}^{\lceil t/2\rceil}\binom{t}{2k+1}n^{2k+1} =
\begin{cases}
\frac12\left((n+1)^t+(n-1)^t\right),&\text{if }t\text{ is odd}\\
\frac12\left((n+1)^t-(n-1)^t\right),&\text{if }t\text{ is even}.
\end{cases}$$
(This is a useful trick to bear in mind when you have alternate binomial coefficients.)
Thus, for every $t$ the numbers $$\frac{n}{(n+1)^t}\sum_{k=0}^{\lfloor t/2 \rfloor}\binom{t}{2k}n^{2k}\text{ and }\frac{n}{(n+1)^t}\sum_{k=0}^{\lceil t/2 \rceil}\binom{t}{2k+1}n^{2k+1}$$ are $$\frac{n}{2(n+1)^t}\left((n+1)^t+(n-1)^t\right)\text{ and }\frac{n}{2(n+1)^t}\left((n+1)^t-(n-1)^t\right)$$ in one order or the other. These are $$\frac{n}{2}\pm\left(\frac{n-1}{n+1}\right)^t = \frac{n}{2}\pm\left(1-\frac2{n+1}\right)^t,$$ which clearly approach $\dfrac{n}2$ as $n\to \infty$.
Answer: The sums you write can be evaluated in closed forms:
$$
   \frac{1}{(n+1)^t} \sum_{k=0}^{t/2} \binom{t}{t-2k} n^{2k+1} = \frac{1}{(n+1)^t} \sum_{k=0}^{t/2} \binom{t}{2k} n^{2k+1} = \frac{n}{2} \left( 1 + \frac{(1-n)^t}{(n+1)^t} \right)
$$
from which the property you seek to establish is apparent.
Now to establish the formula
$$
  \sum_{k=0}^{t/2} \binom{t}{2k} n^{2k+1} = \sum_{k=0}^{t} \frac{1}{2}\left(1 + (-1)^k \right)\binom{t}{k} n^{k+1} = \frac{n}{2}\left( (n+1)^t + (1-n)^t \right)
$$

Water and wine mixing problem


Struct singly linked list. Why does this not work?

Question: #include <stdio.h>

struct item {
    int key;
    int data;
    struct item *next;
};

struct item *head = NULL;

int main()
{
    extern void filllist(), printall();
    filllist();
    printall();
    return(0);
}

void filllist()
{
    static struct item a, b, c, d;
    head = &a;
    a.key = 5;
    a.data = 0;
    a.next = &b;
    b.key = 20;
    b.data = 2;
    b.next = &c;
    c.next = &d;
    c.key = 22;
    c.data = 6;
    d.key = 38;
    d.data = 3;
    d.next = NULL;
}

void printall()
{
    static struct item h;
    head = &h;
    for(int i = 0; i < 5; i++) {
        printf("%d: %d\n", h.data, h.key);
        h = h.next;
    }

}

For the printtall function I get an error "error: incompatible types when assigning to type 'struct item' from type 'struct item *'". Also is there a way to traverse through a singly linked list without a fixed for loop? I want to print out the singly linked list from fillist.
Could someone assist me on how to get printtall to work? Thank you
Comment: @axiac one of the problems is that it doesn't work, therefore it's off-topic on Code Review. Please read [our guide for SO migration](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) before you redirect users to [Codereview.SE].
Comment: Where did you learn this use of `static` and `extern`? It's non-idiomatic use of the language and error prone. Anyhow, your question is off topic and the reasons are explicitly ("why doesn't this code work?") mentioned.
Comment: @Zeta got it. Thank you for pointing that out.
Answer: You are assigning a pointer to a struct here:
h = h.next;

h is type struct item but h.next is a pointer to struct item so you can't set h equal to h.next
Maybe you wanted:
h = *h.next;

A better way to print the list is:
void printall(struct item* h)
{
    while (h != NULL) {
        printf("%d: %d\n", h->data, h->key);
        h = h->next;
    }
}

and call it like:
printall(head);

Besides that you should get rid of all the static variables.
For instance make a function to add a single item. Normally you would use dynamic memory (malloc) but here is an example without dynamic memory, i.e. all variable defined in main (and no static variables):
struct item* add_to_front(struct item* h, struct item* n, int key, int data)
{
    n->key = key;
    n->data = data;
    n->next = h;
    return n;
}

and use it like:
int main()
{
    struct item* head = NULL;
    struct item a, b, c;
    head = add_to_front(head, &c, 1, 2);
    head = add_to_front(head, &b, 3, 4);
    head = add_to_front(head, &a, 5, 6);
    printall(head);
    return(0);
}

Comment: Thank you so much for your updates. I understood linked list fully in python but had a hard time translating it to C. I believe I have a better understanding now thanks to your answer.


In Soccer, can it be a foul even if the player gets to the ball first?

Question: There is a lot of confusion surrounding this topic, both from media and from fans.
For example, in the 2014 World Cup, Gonzalo Higuain was hit pretty hard by Manuel Neuer (with his knee), but no foul was given because Neuer touched the ball first.

However, just as an example, in this last Copa America, Jorge Fucile was given a second yellow after hitting Alexis Sanchez, despite getting to the ball first. Most commentators seemed to agree this was a foul.

In some of the video replays of the aftermath of this foul you can actually hear Fucile's teammates scolding the referee for the call because Fucile "got the ball!!"

There's a lot of cases like this. What does the rulebook say about these fouls?  Were these two calls good?
Answer: Short answer: Yes. Getting the ball first has no relation (in the rules) to whether it's a foul or not.
In the Law of the Game there is actually no mention about getting to the ball first when in reference to a foul.
Law 12, regarding Fouls and Misconduct, can be found starting on Page 36 of the document linked below. I won't recap the full text of it (it's about 4 pages long), but the highlights are basically that a foul (in the run of play) consists of any of the following, if the referee considers it to be careless, reckless or using excessive force:

Kicking, attempting to kick, tripping, attempting to trip, pushing, tackling, jumping at, charges, striking, attempting to strike, holding, or spitting at an opponent
Handling the ball deliberately
Playing in a dangerous manner
Impeding the progress of an opponent
Interfering with a goalkeeper releasing the ball from his hands
Unsporting behavior (yellow card)

I've left out fouls that are not in relation to the run of play, but you can see the whole list on the document.
As you can see, none of the fouls have anything to do with the ball. Many fans will claim that if a player gets the ball they can do no wrong, but that is not part of the rules.
With regard to the first example you cited, the reason behind why the foul was not given was not because Neuer got to the ball first. Rather, it was likely because the referee did not think a foul had been committed (in fact, I think he called a foul against Higuain). There is an argument to be made that Neuer's jump towards the ball was reckless, but both players had eyes on the ballso if that was reckless, then Higuain running into the goalkeeper could also be deemed reckless. Goalkeepers do tend to be protected a bit because they are often in vulnerable positions - jumping up high to get to the ball with their hands.
For the Fucile-Sanchez foul, that was called a foul because the referee deemed it a reckless challenge. It's hard to see on the replays I've seen, but it looks like Fucile comes in and lifts his trailing leg up, thus catching Sanchez's feet between his two legs. This can be very dangerous for the player's ankles. That's my guess as to why the card was given.
The answer to whether these calls were "good" or not will likely be different depending on which team you're rooting for! Being impartial, I think the second call is a very good one. The first I think would be a good no-call (though, as I said, I think a foul was called against Neuer, which I would disagree with).
http://www.fifa.com/mm/document/footballdevelopment/refereeing/81/42/36/log2013en_neutral.pdf
Comment: This is also a good answer. I didn't even see yours until after I posted mine - it looks like you got in just before me! I agree with everything here except your judgement on Neuer's foul - but the careless/reckless/excessive force judgement is opinion-based, and your reasoning is correct, therefore your decision would be correct if you were the referee in the match - in spite of others potentially disagreeing.
Comment: Good catch! Correcting. Also, studro's answer is using the most recent copy of the Laws of the Game (I was inadvertently linking to last year's). I'd recommend his answer over mine.
Comment: That was a reasoned and well expressed comment.... are you sure you're a soccer fan? ;)
Comment: This wasn't clear cut decision for me, hence why I'm agreeing to disagree, but if I was on the field and I was the attacker, no I definitely wouldn't be this calm. :P
Comment: Your Neuer-Higuain foul comment is unclear because you seem to have used the wrong player name. Do you mean that "*Higuain* running straight into the goalkeeper... could also be deemed reckless"?
Answer: Getting the ball first has minimal relevance as to whether a foul has occurred. There is no reference to making contact with the ball in the section relating to Fouls and Misconduct in the Laws of the Game, but it may be considered by the referee in deciding whether contact was careless, reckless or excessively forceful.
There are six offences in which contact is made with an opponent that cause a direct free kick to be awarded:

kicks an opponent carelessly, recklessly or with excessive force
trips an opponent carelessly, recklessly or with excessive force
charges an opponent carelessly, recklessly or with excessive force
strikes an opponent carelessly, recklessly or with excessive force
pushes an opponent carelessly, recklessly or with excessive force
holds an opponent

There are five offences in which contact may or may not be made with an opponent that cause a direct free kick to be awarded:

attempts to kick an opponent carelessly, recklessly or with excessive force
attempts to trip an opponent carelessly, recklessly or with excessive force
jumps at an opponent carelessly, recklessly or with excessive force
attempts to strike an opponent carelessly, recklessly or with excessive force
tackles an opponent carelessly, recklessly or with excessive force

There are two offences in which contact is not made with an opponent that cause an indirect free kick to be awarded:

plays in a dangerous manner
impedes the progress of an opponent

The full text of these offences is found on pages 37-38 of the 2015/2016 FIFA Laws of the Game, which is too long to quote in full here.
As seen, contact does not necessarily mean there is a foul - for some offences it must be either careless, reckless or excessively forceful. These are defined on page 119 of the 2015/2016 FIFA Laws of the Game:

"Careless" means that the player has shown a lack of attention or
  consideration when making a challenge or that he acted without precaution.

No further disciplinary sanction is needed if a foul is judged to be careless

"Reckless" means that the player has acted with complete disregard to the
  danger to, or consequences for, his opponent.

A player who plays in a reckless manner must be cautioned

"Using excessive force" means that the player has far exceeded the necessary use of force and is in danger of injuring his opponent.

A player who uses excessive force must be sent off

In a lot of challenges, contact is made with an opponent both before and after the ball is won. Whether it rises to the level of careless (or worse) usually depends on a number of things (and can depend on how/when the ball was won) - eg.

was the tackle inherently unsafe?
was the contact reasonably unavoidable as part of the challenge?
was the challenge made to win the ball or did it just have the effect of holding up the player?

These are some of the questions the referee decides answers to in an instant as part of their foul recognition process.
In the Neuer / Higuain incident, the referee decided that the collision after the challenge was caused by Higuain, awarding a direct free kick to Germany. I tend to disagree here, as the majority of the force in this challenge was caused by Neuer, due to the pace he was moving at and due to his knee being raised high. Higuain had a right to be where he was on the field without being cleaned up. The collision was unavoidable as part of the challenge, but the challenge was made with complete disregard for the consequences of the opponent. There was no way to make a safe challenge here at that pace.
I believe Neuer should have been cautioned and a penalty kick should have been awarded to Argentina. As you see on the following links, here, here and here a number of experienced match officials tend to agree with my view that the referee made an incorrect decision here.
In the Fucile / Sanchez incident, the referee decided that in spite of winning the ball, Fucile acted with complete disregard for his opponent and that the challenge was reckless and hence cautionable. I tend to agree with the referee here - the challenge is fast and catches a large amount of Sanchez with a decent amount of force.
Comment: Giving Argentina a penalty is too harsh. If GKs are to be punished for rushing out to clear the ball and actually getting to the ball first then the game would be hard to play. At most you would caution Neuer for dangerous action, but in terms of gameplay it should be advantage of Germany. Basically a penalty is almost never given for an act where the defender gets to the ball first, not to mention a goalkeeper. This is irrelevant to whether his action is dangerous and should be cautioned separately.
Comment: "Basically a penalty is almost never given for an act where the defender gets to the ball first, not to mention a goalkeeper." As a referee, this is one of the most frustrating, long-enduring myths that I have to deal with in every game. If the action is careless, reckless, or excessively forceful, getting the ball first is absolutely irrelevant. Some contact is obviously allowed, but an elbow into the head of the player who has done nothing but run into empty space would always be called.
Comment: in the Higuain / Neuer case, I don't think the ref's call is that bad. Neuer just plays the ball and Higuain makes too small effort to really get the ball, thus he puts himself in a dangerous situation. If my memory is good, I think Rizzoli awarded Germany an indirect free kick.
Comment: I find the claim that he put himself in a dangerous position a bit strange, considering HIguain kept both feet on the ground and ran into space he was entitled to run into and Neuer completely cleaned him up with his knee into his face. The fact he got the ball first is completely irrelevant when this sort of contact occurs after the ball has been won. I rewatched the clip (https://www.youtube.com/watch?v=14WDjvsxCQk) and Rizzoli awards a direct free kick - an indirect free kick is impossible since contact occurred.
Comment: Actually I think for a "dangerous play" the punishment is an indirect free kick. So no penalty would have been given whatsoever.
Comment: "Actually I think for a "dangerous play" the punishment is an indirect free kick." Dangerous play cannot be called if contact occurs. A direct free kick or penalty kick must be awarded instead.
Answer: Yes, it can
Unlike the legal system, in football, players are punished by their intent rather than the consequences of their actions. Referees look for objective observations to deduce the intent of the players. For example, you can still get cautioned even if the opponent breaks your leg. Therefore, touching the ball has no impact on the decision of the referees whatsoever, except for situational offenses, like denying a goal scoring opportunity. Hence, rather than touching the ball, the question should be "can it be a foul even if the player had a very realistic attempt to play with the ball?"
Laws of the Game are treated more like a holy book. FIFA and UEFA officials, acting like scholars, train the Referee Committees about the interpretations of these laws. These interpretations sometimes include touching the ball.
A realistic attempt to play with the ball may have an effect on the overall decision, i.e., if there is no realistic intent, a reckless offense can be considered violent conduct and a caution might turn into a red card.
Touching the ball can be used to differentiate between violent conduct and serious foul play. Both are send-off offenses but federations usually punish violent conduct with a longer suspension. This has no impact for the particular game, but still an example where touching the ball might have an impact in the overall decision. For the sake of completeness, I have to add that you can still get a violent conduct ban even if you touched the ball.
For situational fouls, like denying a goal scoring opportunity, touching the ball may have a huge impact on the decision of the referee. For promising attacks and goal scoring opportunities, a contact which would not even be considered foul in another situation results in a caution or send-off if the player does not touch the ball. Still, touching the ball does not magically exonerate you from caution or send-off, it is just the beginning of the "if-else" routine of the referee decision making process.
For the specific question, Neuer-Higuain position is a hard position, but the referee probably interpreted as Higuain impeded Neuer, i.e., run into Neuer's path without attempting to play the ball. Whether Neuer touches the ball or not does not change the interpretation. As I explained above, referee tried to deduce the intentions of both players and believed that Higuain did not consider playing with the ball.
However, the FIFA and UEFA scholars of today, consider jumps with one knee raised up as reckless. It would result in a penalty and depending on the positions of rest of the players, it might be a yellow or a red card.
Comment: While I generally agree with this answer, the legal system (in the UK anyway) absolutely does take intent into account - at the highest end, [it is the difference between murder and manslaughter](https://www.bcl.com/services/murder-manslaughter/).
Comment: @PhilipKendall I am not a lawyer in any capacity,  so I am absolutely sure you are right. Still, if I stalk you, shoot you on the head, leave you to die and you miraculously survive, my punishment is magically lowered, even though I did everythingin my power to kill you. In football the end results should have minimal impact on the referee decision.
Answer: One thing that seems to have been left out of this discussion is that the source of all the "ball first" talk is that a defender who tackles and makes contact with the ball is then entitled to that space.  So if you slide tackle, get the ball, and as a result, your foot/leg is front of the attacker who then, because of his momentum, trips over it; not careless, reckless, or excessive because the defender is entitled to that space after getting the ball.  Anything else you do, (e.g, studs showing, two foot slides, scissoring motions, etc.) can all move the tackle into the realm of careless, reckless, or excessive, regardless of whether you got the ball first. On the otherhand, if you slide tackle, don't get the ball, and then attacker trips over your foot/leg, it's a trip and a foul; you didn't get the ball and therefore you are not entitled to that space.
Comment: Being entitled to space has no relevance to whether a tackle was careless or reckless or involved excessive force. Your response ignores large portions of law and high-level advice.
Comment: This comment is 100% wrong. Being entitled to space is absolutely relevant. It is what defines whether it's a trip or not. If a defender has his foot somewhere, and attacker runs into it and falls over, it's not a trip. If the attacker is running and the defender sticks his foot into the path of the run, it's a trip. When the defender tackles, gets the ball, and commits no further movement, he's entitled to that space, no trip, no foul. If there's further movement that trips the attacker, foul. That's the source of the "ball first" misunderstanding. It actually is all about entitled space.
Comment: From what I understand of your answer, touching the ball can be used as a litmus test to check if the actions of the players are too irrelevant. Touching the ball does not exonerate the player from discipline but not touching the ball can be a good start for a referee to decide what type of discipline is required. I can give you countless examples where an action involving touching the ball is still penalised.
Comment: A good example is sticking your leg between ball and another player when the opponent is in clear control of the ball. Clear control is determined by speed of the ball and your and the opponent's position. If you stuck your leg between ball and another opponent, touch the ball and get your leg broken by the opponent who only wanted to shoot, you get a caution because reckless behaviour in football cuts both ways  i.e., you can't disregard your own safety either.
Comment: I agree with the first comment, I don't think I understand the 2nd.  If you're talking about sticking your foot in front of a player who is in the act of shooting, yes you'll probably be cautioned as that's dangerous play. If you make a legitimate play for the ball, it becomes more of a grey area.  Otherwise, yes, generally agree with all that.
Comment: Also, this concept of being entitled to space is common in many sports (basketball, American football, hockey, etc.).  It's an indication of who initiated the contact.  Defender "gets the ball"-->defender was there first-->the other player initiated the contact --> no foul. That's assuming no other factors (recklessness, further contact, etc.) that could still make it a foul.
Comment: It's the same concept in basketball that indicates whether it's an offensive charge or not.  All the people saying "It's not in the rules" are missing the point. It's not a "rule", it's evidence of what happened. Like a torn shirt is not "in the rules", but indicates there was a shirt pull. And it's not dispositive, there are other factors. But it's a big one.


Genymotion localhost access inside a webview

Question: I have a problem, i can't access to an api i created in my localhost with genymotion.
The api link works fine in the android browser but when i use it in $http.get it doesn't work, i tried logging the error message but it returns null.
Here's my code:
<code>$http.get('http://10.0.3.2:80/api/user')
    .success(function(json) {
        console.log(json);
        deferred.resolve(json);
    })
    .error(function(error) {
        console.log("Error: "+error);
        deferred.reject();
    })
</code>
The console show: "Error: null"
Answer: I found a solution, the problem was not in genymotion or in my code but actually in the local server, i had to enable CORS (you can find how to enable cors in wamp here)
I also had this problem with my remote server so i have to enable CORS there also.


iptables "recent" module - setting module parameters

Question: The manpage for iptables 'recent' module explains that the module itself accepts parameters. How does one go about setting these parameters? I would imagine they would be set somewhere where the module is loaded. I do not know where that is.
Does anyone have any ideas?
Answer: If you load the module by hand, you just add it to the modprobe command line:
modprobe ipt_recent param1=val1 param2=val2

Otherwise, if it's being loaded automatically, you can create a file in /etc/modprobe.d, say /etc/modprobe.d/ipt_recent, with contents of:
options ipt_recent param1=val1 param2=val2

Which will do the same thing as the modprobe line above.
Comment: Keep in mind at least on Ubuntu all files inside `/etc/modprobe.d/` need to end with `.conf`. Also the module seem to differ from system tot system: on Ubuntu it's `xt_recent`. I couldn't get it to work using an conf file so I did it manually via: `modbrobe -r xt_recent ; modprobe xt_recent ip_list_tot=value`
Comment: On RHEL6 it appear to be xt_recent now also.
Answer: Warning: Understand that changing this has an impact on the memory usage of the machine as these details are stored in memory and iptables require greater resources to deal with storing larger amounts of data.
Setup the xt_recent configuration file
Create the file /etc/modprobe.d/xt_recent.conf and include a line like this:
options xt_recent ip_list_tot=50 ip_pkt_list_tot=150
Don't forget to add some comments about what you're doing. Future you will thank you.
Prepare to reinitialize xt_recent
Before we remove any rules in your firewall currently using the recent module or simply disable the firewall. You may want to save your rules before you do this with sudo iptables-save > somefile.txt or maybe sudo service iptables save if you distro supports that.
Choose one of these two depending on your situation to clean up. You could also simply restart your computer at this point and skip to adding rules.
To shutdown iptables
sudo service iptables stop
To Remove specific Rules:

Use iptables -L --line-numbers to list the rules and look for "recent:" in the rules.
Use iptables -D INPUT # where # is the line number to delete rules.

Reinitialize xt_recent
Remove the module with sudo modprobe -r xt_recent.
Add it back with sudo modprobe xt_recent.
Check to make sure your parameters were applied with sudo cat /sys/module/xt_recent/parameters/ip_pkt_list_tot.
Add the rules that you couldn't
If you stopped iptables sudo service iptables start to bring it back.
Add your rules back in with the higher values you wanted.
Bonus:
sudo watch 'iptables -nvL' will allow you to watch stuff hit the xt_recent rules.
Answer: I don't have the reputation to reply to TopQ's answer, but I signed up for an account just to tell people not to do what he suggests. The source code of the module (http://lxr.linux.no/linux+v3.9/net/netfilter/xt_recent.c) has no provision to detect changes to that parameter and no provision to reallocate the kernel buffer responsible for keeping track of recent hits.
Therefore, if you chmod that parameter writable and subsequently change it, subsequent entries to existing recent hit logs will overrun the previously allocated kernel buffers and cause a kernel panic.
Answer: If the module is already loaded, you can still change the parameter by manipulating the value in /sys/module/ipt_recent/parameters/.
For example, to change the value of ip_pkt_list_tot you can do:
echo 200 > /sys/module/ipt_recent/parameters/ip_pkt_list_tot
Of course, you got to have the permission.
Comment: RHEL6 will not permit changes of permission to even sudo these that I can find. Perhaps this is a protection from what planetbeing mentions below.
Comment: Not a good idea as already mentioned here: https://serverfault.com/a/504298/39337


Internal infrastructure with docker

Question: I have a small company network with the following services/servers:

Jenkins
Stash (Atlassian)
Confluence (Atlassian)
LDAP
Owncloud
zabbix (monitoring)
puppet
and some Java web apps

all running in separate kvm(libvirt)-vms in separate virtual-subnets on 2 machines (1 internal, 1 hetzner-rootserver) with shorewall inbetween. I'm thinking about switching to Docker.
But I have two questions:

How can I achieve network security between docker containers (i.e. I want to prevent owncloud to access any host in the network except ldap-hosts-sslport)
Just by using docker-linking? If yes: does docker really allow to access only linked containers, but no others?
By using kubernetes?
By adding multiple bridging-network-interfaces for each container?
Would you switch all my infra-services/-servers to docker, or a hybrid solution with just the owncloud and the java-web-apps on docker?
Answer: Regarding the multi-host networking: you're right that Docker links won't work across hosts. With Docker 1.9+ you can use "Docker Networking" like described in their blog post http://blog.docker.com/2015/11/docker-multi-host-networking-ga/
They don't explain how to secure the connections, though. I strongly suggest to enable TLS on your Docker daemons, which should also secure your multi-host network (that's an assumption, I haven't tried).
With Kubernetes you're going to add another layer of abstraction, so that you'll need to learn working with the pods and services concept. That's fine, but might be a bit too much. Keep in mind that you can still decide to use Kubernetes (or alternatives) later, so the first step should be to learn how you can wrap your services in Docker containers.
You won't necessarily have to switch everything to Docker. You should start with Jenkins, the Java apps, or OwnCloud and then get a bit more used to the Docker universe. Jenkins and OwnCloud will give you enough challenges to gain some experience in maintaining containers. Then you can evaluate much better if Docker makes sense in your setup and with your needs to be applied to the other services.
I personally tend to wrap everything in Docker, but only due to one reason: keeping the host clean. If you get to the point where everything runs in Docker you'll have much more freedom to choose where a service can run and you can move containers to other hosts much more easily.
You should also explore the Docker Hub, where you can find ready to run solutions, e.g. Atlassian Stash: https://hub.docker.com/r/atlassian/stash/
If you need inspiration for special applications and how to wrap them in Docker, I recommend to have a look in https://github.com/jfrazelle/dockerfiles - you'll find a bunch of good examples there.
Comment: thanks for that detailed answer. do you also know if i can configure which container is allowed to communicate with which container (on same host)?
Comment: When using the Docker new networking, you can use several differently named networks to achieve such a setup. When using links (or plain Docker ip addresses) I'm not aware of such configuration.
Answer: You can give containers their own IP from your subnet by creating a network like so:
docker network create \
  --driver=bridge \
  --subnet=135.181.x.y/28 \
  --gateway=135.181.x.y+1 \
  network

Your gateway is the IP of your subnet + 1 so if my subnet was 126.96.36.199 then my gateway should be 126.96.36.199
Unfortunately I have not yet figured out how to make the containers appear to the public from their own ip, at the moment they appear as the dedicated servers' ip. Let me know if you know how I can fix that. I am able to access the container using its ip though.

Internal infrastructure with docker


Concatenate 2 different pdf with or without PdfCopy class of Itext

Question: I'm trying to concatenate two different PDF files in a java project.
I've read in others posts that the best way is to use Itext class "PdfCopy", but the strange thing is that there isn't in my project even though I have the 7.0.6 of Itext in the pom and a commercial license.
Is there an explanation or another way to solve this task without using Itext or others external libraries?
Thank you
Comment: *I've read in others posts that the best way is to use Itext class "PdfCopy"* - that recommendation refers to itext up to version 5.x. itext 7.x is a major re-design of the whole api. In particular the functionality of the `PdfCopy` classes had been moved. Try `PdfDocument.copyPagesTo` instead.
Comment: Please show us your code.
Answer:
I've read in others posts that the best way is to use Itext class "PdfCopy"

That recommendation refers to iText up to version 5.x. iText 7.x is a major re-design of the whole iText api. In particular the functionality of the Pdf*Copy* classes had been moved. Try PdfDocument.copyPagesTo instead.
I.e. if you have loaded your source documents into PdfDocument instances doc1 and doc2 and have another, writable PdfDocument instance dest you want to copy those source documents into, simply do:
doc1.copyPagesTo(1, doc1.getNumberOfPages(), dest);
doc2.copyPagesTo(1, doc2.getNumberOfPages(), dest);

Answer: Please refer this as well:
Is it possible to merger several pdfs using iText7
Another library that can be used is PDFBox, sample below"
https://www.tutorialkart.com/pdfbox/pdfbox-merge-multiple-pdfs/


Acoustic guitar damaged by impact. How to repair?

Question: Introduction
My acoustic guitar has suffered damage at four locations. It still sounds very good, and it is more than twenty years old.
The damage done
The different damage locations are pictured and numbered at the bottom of this post. Here is a short description for each of them.

Serious damage caused by a some blunt object just right to the center.
Tiny dent.
Small impact damage by some sharper object.
Elongated dent.

Question
I don't want to pay to have this fixed -- there is no fun in that. My goal is to hide the damage as well as possible, and still preserve the sound.
I hope that this question can be used as further reference for others wanting to repair similar damages. If you need me to provide more information or reformulate something -- please let me know.
Answer: Your guitar looks pristine for being 20 years old compared to my dinged up 1970 Gibson J45.
Personally all the dings in the picture seem somewhat less likely to be a problem than ding #1 which makes me wonder how far that crack goes and if it extends unseen to under the bridge.
The first question I think that you should ask is, "does this instrument have any collectibility?" If yes, then fixing it yourself is out of the question unless you are certified luthier. If you want to sell this in the future to a collector, they will see that there was damage, and ask how it was repaired. Home repairs are a 'no no' for a collectible. In fact, strictly speaking, if this has any potential value as a collectible, it might be best to leave it alone.
If this instrument does not have any collectibility, than I would then learn from a certified luthier on how to make the repairs. Even if this is a 'player' you want to make sure that any work you do will not make things worse.
In any event, I would take it to luthier to get a professional opinion on how bad the damage on ding #1 is as that one looks like a show stopper to me.
Comment: This answer is spot on! There are many many valuable instruments out there with major damage. As a guitar player, you need a local luthier anyway; assuming you aren't driven to learn the craft. They will usually give good, free advice.
Comment: Take it to a luthier if you're concerned. Agreed.


How do I loop through a list of columns in pg/PLSQL?

Question: I have a table with about 3 dozen VARCHAR columns that all need the same cleanup before the record is inserted into the database (convert empty string to NULL). There are multiple apps accessing the DB, so I'd like to do this in a trigger. I could write code to check and set each column, but I'd like to loop through the columns instead. The function I wrote does not produce an error, but it also does not set empty columns to NULL.
CREATE OR REPLACE FUNCTION public.validate_flds() RETURNS trigger AS
$BODY$
DECLARE
  coldata VARCHAR;
  collist VARCHAR[];
BEGIN
  collist := ARRAY[NEW.fld01,NEW.fld02,NEW.fld03];
  FOREACH coldata IN ARRAY collist LOOP
    IF coldata = '' THEN coldata := NULL; END IF;
  END LOOP;
  RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;

What am I missing?
Comment: A loop with 36 statements every triggered on insert is going to harshly kill performance, especially if this table is hit by multiple apps.   Perhaps a better way of accomplishing your goals than a loop.
Comment: It's a low-volume system, so performance is not an issue.
Comment: You cannot to it in plpgsql. The record's fields cannot be accessed dynamically today - there is not necessary API. There are some workarounds, but none is good for update. Some years ago I wrote trigger function that does inverse transformation, but it can be easy modified https://github.com/okbob/replace_empty_string
Answer: In
IF coldata = '' THEN coldata := NULL; END IF;

you alter the value of the variable while the NEW record remains unchanged. There is no easy way to do what you want in a loop. I would suggest using NULLIF().
begin
    new.fld01:= nullif(new.fld01, '');
    new.fld02:= nullif(new.fld02, '');
    new.fld03:= nullif(new.fld03, '');
    return new;
end;


Calculate expected survival time for two stage survival

Question: In a book about Biostatistics, I found this example to calculate expected value:

Consider the following hypothetical example of a lung cancer study in which all patients start in phase 1, transition into phase 2, and die at the end of phase 2. Unfortunately, but inevitably, all people die. Biostatistics is often concerned with studying approaches that could prolong or improve life. We assume the length of phase 1 is random and is well modeled by an exponential distribution with mean of five years. Similarly, the length of phase 2 is random and can be modeled by a Gamma distribution with parameters α = 5 and β = 4. Suppose that a new drug that can be administered at the beginning of phase 1 increases 3 times the length of phase 1 and 1.5 times the length of phase 2. Consider a person who today is healthy, is diagnosed with phase 1 lung cancer in 2 years, and is immediately administered the new treatment. We would like to calculate the expected value of the survival time for this person. Denote by X the time from entering in phase 1 to entering phase 2 and by Y the time from entering phase 2 to death without taking treatment. Thus, the total survival time is 2 + 3X + 1.5Y and the expected total survival time, in years, is
E(2+3X +1.5Y) = 2+3E(X)+1.5E(Y) = 2+3×3+1.5×5/4 = 12.875 .

What I don't understand is why in the last equation E[x] is set to 3 while in my opinion it should be 5 because the length of phase 1 (for patients not taking the drug) has the exponential distribution with mean of five years?
I'm also a bit confused with this sentence:

Consider a person who today is healthy, is diagnosed with phase 1 lung cancer in 2 years, and is immediately administered the new treatment

Does that mean that the person will enter the phase 1 in the next two years while today they are healthy? It sounds kind of strange to me how medical advancements can help predict a future disease for someone's today healthy two years from now.
Comment: Please edit the question to provide a reference to the book you are quoting. Sometimes other context around a quote helps clarify what is being said.
Comment: @EdM I've just updated, please check again.
Answer: There is one way that this might have been thought by the authors to make sense. But I think that you are correct.
Their argument might be if the diagnosis of Phase 1 came 2 years after Phase 1 actually started. Then the argument might be that expected remaining length of Phase 1 is $5-2=3$ years.
The problem with that argument is the memoryless nature of the assumed exponential survival function. For an exponential survival function, the mean residual life conditional upon survival to any time after 0 is always equal to the expected survival from time 0. That supports your argument that the remaining expected duration of Phase 1 for that individual should be 5 years, and that the extension of Phase 1 by the drug would be 3 times that. It's possible that the authors had some other model for the effect of the drug in mind that would support their argument, but that's not clear from what you quote.
It looks like the book you cited is essentially self-published, and thus might not have undergone the editorial review of a traditionally published text. This seems to be an error, perhaps made without properly thinking through the implications, that might have been caught during a traditional editorial process.
In this case, it would make sense to address your question directly to the authors. If they provide a compelling argument to support what you quote, please provide that as another answer to this question. (It's OK to provide and accept your own answer to your question on this site.)


expected values of distributions over applied functions

Question: Assume two distributions $p_1$ and $p_2$ over $F$, where $F$ is a set of functions from a set $X$ (no matter what $X$ s) to the set of non negative reals (or naturals if this simplifies the problem).
Assume there exist $x,y \in X$ with $x \neq y$ such that both inequalities below hold:

$\sum_{f \in F} p_1(f) \cdot f(x) \ge \sum_{f \in F} p_2(f) \cdot f(x)$
$\sum_{f \in F} p_1(f) \cdot f(y) \ge \sum_{f \in F} p_2(f) \cdot f(y)$

Can we infer the following inequality?
$\sum_{f \in F} p_1(f) \cdot f(x) \cdot f(y) \ge \sum_{f \in F} p_2(f) \cdot f(x) \cdot f(y)$
Many thanks in advance.
Answer: Unfortunately, this is not the case. We can simplify our problem by generalizing it in the following way :

Let $(X_1, Y_1)$ and $(X_2, Y_2)$ be couples of non-negative random variables. Assume that $\mathbb{E}(X_1) \ge \mathbb{E}(X_2)$ and $\mathbb{E}(Y_1) \ge \mathbb{E}(Y_2)$. Is it true that $\mathbb{E}(X_1 Y_1) \ge \mathbb{E}(X_2 Y_2)$?

We can get back to your setting by taking $(X_1, Y_1) = (f(x), f(y))$ under the distribution $p_1$, and $(X_2, Y_2) = (f(x), f(y))$ under the distribution $p_2$. Actually, the two problems are equivalent.
Let us take $X_2 = 1$ and $Y_2 = 1$ almost surely. Then, let us take $(X_1, Y_1) = (1/2, 3/2)$ with probability $1/2$ and $(3/2, 1/2)$ with probability $1/2$. Then :
$$\mathbb{E}(X_2 Y_2) = 1$$
and:
$$\mathbb{E}(X_1 Y_1) = \frac{1}{2} \cdot \frac{1}{2} \cdot \frac{3}{2} + \frac{1}{2} \cdot \frac{3}{2} \cdot \frac{1}{2} = \frac{3}{4} < \mathbb{E}(X_2 Y_2).$$


Porquê usar contemporaneamente float:left e display:inline?

Question: Estou a ver um tutorial, onde o professor a um certo momento, minuto 28, estabelece o style do elementos duma ul para criar uma barra de navegação horizontal, e fa-lo usando seja o float:left que o display:inline. O problema é que eu ontem tinha visto que os métodos que citei em cima são dois métodos diferentes para obter a barra horizontal, mas então porque ele usa os dois contemporaneamente?
.mainheader nav ul li{
    float:left; /* li are set to the left of their "brothers"*/
    display:inline;
}

Answer: Geralmente, elementos flutuados têm um valor de display definido implicitamente como block. Porém, o caso dos itens de lista é uma exceção. Segundo a especificação,

no CSS 2.1 não é definido se valores list-item deverão assumir o valor computado block ou list-item.

(tradução livre)
No Chrome, por exemplo, os itens de lista flutuados deixam sobrar os bullets. Acredito que a intenção de incluir display: inline na regra foi justamente de eliminar esses bullets, forçando que os
 flutuados assumam display: block em vez de display: list-item.
Comment: Nota: removi minha resposta anterior, pois estava incorreta.
Answer: Estas duas instruções do permitem que os elementos html
 sejam dispostas um do lado do outro pois por padrão o CSS mostra uma lista não ordenada (
) ou ordenada (
) cujo elementos estarão um embaixo uns dos outros.

Assim aparecerão um item abaixo do outro.

Item 01

Item 02

Item 03

Item 04

Item 05

Assim aparecerá um item ao lado do outro.

Item 01

Item 02

Item 03

Item 04

Item 05

Comment: Já viu isto aqui? [*Apresentando: JS, CSS e HTML executáveis!*](http://meta.pt.stackoverflow.com/q/2115/201) :)
Comment: ps, faltou encapsular o `` com o ``... ou remover o `nav` do CSS.
Comment: @MarcosVinicius Essa ferramenta é nova, foi acrescentada [ao SOpt] só ontem, mas está disponível pra todos os usuários.
Comment: Não havia reparado a ferramenta, imagino que ela tenha se adicionada conforme minha reputação alcançou uma determinada pontuação.
Answer: Display é pra fazer o elemento se comportar como block ou inline de acordo com o box model... Já o Float tira o elemento do fluxo padrão, fazendo com q flutue como se fosse uma layer... definindo a camada por meio do z-index... Então pode-se usar por exemplo os dois ao mesmo tempo sempre que vc quiser q um elemento se comporte como bloco ou inline e q ainda saia do fluxo
Comment: O que z-index tem haver com float?
Comment: quis dizer apenas q o z-index pode ser usando junto com o float... q um não impede o outro... ajustando a ordem na pilha de layers... tipo neste exemplo... http://stackoverflow.com/questions/579753/css-floating-w-overlap
Comment: `z-index` com `float`? Pensei que `z-index` requeria `position` (`relative`, `absolute` ou `fixed`)...  Leia por favor: http://www.w3.org/wiki/CSS/Properties/z-index Note: O OP da questão está falando de `float:;` e não de `position:;`


Context for panel not activating for custom menu item

Question: I'm loading a group node from a custom menu item I've created in a module. The reason I've created a custom menu item is because I wanted to use a different path than the one associated with the node.
I have a panel with a selection rule set to all group nodes. The custom menu item works and loads the group node, however, the panel is not being activated. I think it is something to do with the way I am loading the node from my hook_menu function which is preventing the context from being activated. The code I'm using is:
function mymodule_menu() {

$items['course/course-1/resources'] = array(
    'title' => 'Resources',
    'access callback' => TRUE,
    'page callback' => '_getpage1',
    'page arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'menu-course-menu',
    'weight' => '1',
);

return $items;

 }

function _getpage1($arg1) {
    $path = drupal_get_normal_path("course/" . $arg1);
    $node=menu_get_object('node',1,$path);
    return node_page_view($node);
 }

Is there anything I need to add to activate the context for the group?
Many thanks,
Ben
ADDTIONAL INFORMATION:
I have two variants set up.
For the first:
Selection rule: Node is an OG group AND path matches "course/*/resources".
Context: No context is set
Relationship: OG Group from node
For the second:
Selection rule: Node is an OG group.
Context: No context is set
Relationship: OG Group from node
The first variant is supposed to be activated for the same group node when the path "course/course-1/resources" is used, and the second is supposed to be activated when the path is simply "course/course-1". At the moment only the second variant is being activated. When the path "course/course-1/resources" path is used it just shows the Course 1 group node in it's default layout with no panels being used.
Comment: Please provide info on how the panel is configured including its path, selection rules, contexts and relationships.
Comment: Hi Ashlar, I've updated my question with more information above.
Comment: What is the basic path for the page panel?
Answer: I like to test a panel answer before I post it, but will be gone for a couple days, so I'll give you my speculation on what may be causing this.  I suspect your page panel path is /course/%course and so that is the only path that is intercepted.  It does not matter that you have a variant for resources because it never gets tested. The basic panel definition has already rejected it.  Try changing the basic path to /course/%course/!other.  The !other variable is optional so the panel should intercept 2 and 3 level paths matching the pattern.  Your variant should then be triggered.
The variable labels in the path (%course & !other) are used to identify associated contexts listed on the context/relationships tab for defining the variant and the specific label name does not matter.  Hope this works. If not, I'll check back in a couple days.
Comment: Hi Ashlar, thank you very much for your answer.  I'm knew to panels so may well be making a mistake somewhere.  I didn't create an additional page panel but overrode the system node template at node/%node.  I have been trying to create a new page panel based on the path you suggest above but I can't get it to work at all now. I'm going to carry on trying and will keep you posted.
Comment: I've been trying different things, and one way I tried to activate the panel was by making the keyed path in my hook_menu function be just "/test". But this has the same effect and doesn't activate the page panel (based on the "node/%node" system template override. So I'm not sure that it's not working has something to do with the last path argument. It does seem to have something to do with the fact that the path (alias) is not saved internally in Drupal. When I save the alias "/course/course-1/resources" to go to "node/1" (my course page) then the panel does get activated.
Comment: Maybe the problem is linked to the question at http://drupal.stackexchange.com/questions/789/hook-preprocess-page-node-load-node-page-view-versus-node-node-page?
Comment: Try defining a node as I suggested to test it, but do so using the panels UI (its quicker and less can go wrong). Let me know what happens.
Comment: I tried defining a panel page based on "course/%course" (I disabled my other panels), but it is not activating for any of the course group pages. I'm also unclear using this method how I will relate my group content to the panel. I could do this in the node override panel by using the Group from node relationshiop, but this is not available in this panel.
Comment: I'm also a little confused. If I create a page panel with a path "course/%course", does that mean if I have a node with a path "course/course-1" that this will use the page panel? (as this doesn't seem to be happening). And if so how do I get the content of "Course 1" into the panel?
Comment: Hi Ashlar, I managed to solve it and have added my answer. Many thanks for your input.
Comment: @Ben On this site it is appropriate to show appreciation for an answerer's efforts by up-voting their answer. Doing so does not indicate that it is the correct or complete answer, but does indicate it is helpful and well considered.  Such actions encourages more response on your next question on the site.
Comment: Ashlar, thanks for the tip, and again for your help, I have done as you suggested.
Answer: I managed to solve the problem. I did some research and a post at Url aliases and arguments/ Panels put me on the right track.
The Drupal path module does not match sub-paths but only full URLs, so I downloaded and enabled the Sub-pathauto module and then the panels were being activated correctly. Now I can have different variants activated by different arguments at the end of the URL (ie alternative displays for the same organic group node). I needed this module as I was using aliases. So there was nothing wrong with the panel set up it was just the sub-path was not being added for Drupal.


Certificate issue when using serverless and serverless-domain-manager with custom domain

Question: I'm trying to set up a custom domain for my API Gateway and Lambda function.
I registered a domain with route53. Ex: myDomainToTestApi.net
I also created the certificates for: myDomainToTestApi.net, *.myDomainToTestApi.net, www.myDomainToTestApi.net
I installed the plugin serverless-domain-manager for serverless framerwork
In my serverless.yml I added (under custom):
 customDomain:
    domainName: myDomainToTestApi.net
    basePath: ''
    stage: ${opt:stage, 'dev'}
    certificateName: '*.myDomainToTestApi.net'
    createRoute53Record: true

ALL resources are in us-east-1
When I run:
sls create-domain

I receive the following error...
Serverless: Load command test
Serverless: Load command dashboard
Serverless: Invoke create_domain
Serverless: [AWS apigateway 404 0.374s 0 retries] getDomainName({ domainName: 'myDomainToTestApi.net' })
Serverless Domain Manager: NotFoundException: Invalid domain name identifier specified
Serverless: [AWS acm 200 0.35s 0 retries] listCertificates({ CertificateStatuses: [ 'PENDING_VALIDATION', 'ISSUED', 'INACTIVE', [length]: 3 ] })

  Error --------------------------------------------------

  Error: Error: Could not find the certificate *.myDomainToTestApi.net.
      at ServerlessCustomDomain.<anonymous> (/Users/user/project/node_modules/serverless-domain-manager/dist/index.js:279:23)

If I go to the Certificate Manager view, the status for all is Issued
Anyone knows what could be happening...? Thanks.
Comment: I'm getting the same error, did you manage to fix this?
Answer: Try to add another propertie called certificateArn, you can find certicateArn in the certificate manager detailed view of the domain
certificateArn: 'xxxxx'

Comment: I added the `arn`. Still failing but with new `error`: Serverless: Load command dashboard
Serverless: Invoke create_domain
Serverless: [AWS apigateway undefined 9.234s 0 retries] getDomainName({ domainName: 'myDomainToTestApi.net' })
`Serverless Domain Manager: CredentialsError: Missing credentials in config`

  Error --------------------------------------------------

  Error: Error: Unable to fetch information about myDomainToTestApi.net

Btw, I do have my AWS credentials in `/.aws/credentials`
Comment: And then another cryptic error appears... `UnexpectedParameter: Unexpected key 'securityPolicy' found in params` even though I did not specify it myself (uses the default)
Answer: It is actually
sls create_domain

(notice the underscore)
Comment: @AnkurLoriya sorry mate but this is the correct command...
here are the docs: https://www.npmjs.com/package/serverless-domain-manager


How to iterate a select_list from Page Objects in Ruby

Question: I have a page object that has a list item of locations.
select_list(:locations, :id => 'locations)

And I would like to have a list of locations and then select one of them.
Something like:
def select_item_different_than d_item
 list_items = :locations.items #This is wrong, but you get the point
 list_items.each do |item|
   if item != d_item
     item.select
     return
   end
 end
end

Thanks a lot :)
Comment: Please, edit with example and expected result, it will help people to help you.
Comment: Done!I think it's clearer now :)
Answer: The select list elements have an options method that returns an array of its option elements. You could iterate over the array and compare them to the d_item.
The method could be:
def select_item_different_than d_item
  list_items = locations_element.options
  list_items.each do |item|
    if item.text != d_item
      item.click
      return
    end
  end
end

Note that the following changes were required:

The select list element is retrieved by locations_element instead of :locations.
The list of options is retrieved by options instead of items.
In the if statement item != d_item was changed to item.text != d_item. My assumption is that you want to compare the option's text and d_item is a string.
Option elements do not have a select method. Instead, use the click method.

Personally, I think the method might be more clear as:
def select_item_different_than d_item
  locations_element
    .options
    .find{ |option| option.text != d_item }
    .click
end


Função assíncrona com FutureBuilder retorando uma lista de Widgets

Question: Minha função obtinha dados de um sistema e montava os widgets. Ela era síncrona e funciona perfeitamente.
  children: _confere
      .obterDados(data)
      .map(
        (d) => Conferencia(
          dados: d,
        ),
      )
      .toList()

Agora surgiu a necessidade de torná-la assíncrona. Aí surgiu a dor de cabeça com FutureBuilder.
Tentei de várias formas iterar sobre o resultado e retornar uma lista de wigets, mas sem sucesso.
O mais próximo que consegui foi com o código abaixo:
children: <Widget>[
FutureBuilder(
  future: _confere.obterDados(data),
  builder: (_, AsyncSnapshot<ObservableList<Dados>> snapshot) {
    if (snapshot.hasData) {
      return Conferencia(dados: snapshot.data[2]);
    } else {
      return (Text('consultando'));
    }
  },
  ),
],

Obviamente, neste código só é retornado um único resultado. Gostaria de saber como retornar o resultado da iteração utilizando FutureBuilder. A maioria dos exemplos que vi só retornam widget único e nunca, uma lista.
Comment: Se seu `snapshot.data` é uma lista e vc espera também uma lista, vc poderia criar uma variável nova dentro da função do builder e com um laço de repetição percorrer o snapshot e populando a variável. Depois poderia retornar dentro do seu widget essa lista. Pensou em algo do tipo?
Comment: @LeonardoPaim tentei, mas quanto tento retornar uma lista mostra o err: _The return type 'List' isn't a 'Widget', as required by the closure's context.` acredito que devido `[_

Se removo o `` e deixo retorno como `List`
_The argument type 'FutureBuilder>' can't be assigned to the parameter type 'List_
Comment: @LeonardoPaim encontrei uma solução com base na sua informação, porém criando uma novo função `Future> _widgets() async {`, vou aguardar caso queira postar uma resposta, senão eu coloco a solução que encontrei.
Comment: Sem problemas, poste a solução que funcionou pra você. Inicialmente a minha sugestão era algo genérico para que pudesse direcionar a vc na resposta específica do seu problema. Como o Stack preza pelas respostas efetivas para problemas específicos, o melhor é que vc deixe para a comunidade a solução que vc aplicou e solucionou o problema que inicialmente vc estava.
Answer: Vi que você já encontrou uma solução, mas só pra deixar mais uma possibilidade de como pode ser feito:
FutureBuilder(
  future: _conferencia.obterDados(data),
  builder: (_, AsyncSnapshot<ObservableList<Dados>> snapshot) {
    if (!snapshot.hasData)
      return Center(child: Text("Carregando dados!"));

    return SeuWidget(
      children: snapshot.data.map((item){
        return Conferencia(dados: item);
      }).toList()
    );

  },
),

Explicação
O FutureBuilder tem a função de aguardar os dados de alguma fonte e depois quando possuir os dados ele irá re-construir, mas enquanto os dados não chegam você pode informar ao usuário que algo está acontecendo, então é por isso que faço a seguinte validação
if (!snapshot.hasData) {
  return Center(child: Text("Carregando dados!"));

Então enquanto os dados não chegarem, informamos o usuário que estamos esperando ou carregando as informações!
Comment: Oops! Falha minha, não vi a chave aberta ali, só remover ela. ~~ Não cheguei a testar, estou sem Flutter na máquina.
Comment: Exatamente isso!
Mas esse `return Container();` tem alguma função?
Comment: O future vai construir apenas quando tiver dados... Então enquanto não tiver nenhum dado ele vai construir um espaço em branco, ou melhor tu pode por o teu `Text("Carregando...")` para informar que está esperando algum dados. Ajustei a resposta, de uma olhadinha!
Comment: Está faltando o else no `if (!snapshot.hasData) {` ou não está fechando a `{` para retornar `return SeuWidget(`


Posicionando um FORM na página

Question: Estou tentando colocar dois SELECT MENU um ao lado do outro na minha página. Porém, quando coloco o primeiro ele aparece, quando coloco o segundo e aparece na posição trocada. Se eu inverto e coloco o segundo primeiro ele some na exibição do navegador.

<?php

    if($centraliz = "S"){

?>

Titulo

    <form id="frmCad" name="frmCad" method="post" action="../inc/processa.php?modo=incluir&fnc=<?php echo $fnc; ?>&ans=<?php echo $linha; ?>">

        <input name="emp" type="hidden" value="<?php echo $lj; ?>" />
        <input name="projeto" type="hidden" value="Budget" />
        <input name="exercicio" type="hidden" value="<?php echo $basebud; ?>" />
        <input name="linhabud" type="hidden" value="<?php echo $linha; ?>" />
        <input name="usuario" type="hidden" value="<?php echo $usuario; ?>" />

Anterior:
<?php

include("../libraries/anterior.php");
?>

        <fieldset style="padding:8px; margin:15px 0px 25px 0px;">
            <form method="get" name="tBand" id="cBand" style="float:left;margin-top:0px;">
            <select name="menu1" onChange="MM_jumpMenu('parent',this,0)">
                <option value="">Selecione a Bandeira</option>
<?php
      $qry="SELECT sjy_empresas.bandeira AS id_bandeira, sjy_bandeira.bandeira
            FROM kcb_tbstates
            INNER JOIN sjy_bandeira
            INNER JOIN sjy_grupo
            INNER JOIN sjy_empresas ON sjy_grupo.id_grupo = sjy_empresas.grupo
            AND sjy_bandeira.id_bandeira = sjy_empresas.bandeira
            AND kcb_tbstates.ID = sjy_empresas.estado
            WHERE sjy_empresas.grupo = '$grupo'
            GROUP BY sjy_empresas.bandeira, sjy_bandeira.bandeira";
      // Executa a consulta OU mostra uma mensagem de erro
      $rs = $MySQLi->query($qry) OR trigger_error($MySQLi->error, E_USER_ERROR);

      // Faz um loop, passando por todos os resultados encontrados
      while ($dt = $rs->fetch_object()) {
            $band       = $dt->id_bandeira;
            $bandeira   = $dt->bandeira;

            echo "<option value='preorc.php&fnc=". $fnc . "&and=" . $linha . "&bandorc=" . $band . "'>" . $bandeira . "</option>";
    }
?>
            </select>
        </form>
        <form method="get" name="tLoja" id="cLoja" style="float:left; padding-left:15px;margin-top:0px;">
            <select name="menu2" onChange="MM_jumpMenu('parent',this,0)">
                <option value="">Selecione a loja</option>
            <?php
    $qry="SELECT sjy_empresas.id_empresa, sjy_empresas.nick, sjy_empresas.bandeira AS band, sjy_bandeira.bandeira
            FROM sjy_bandeira
            INNER JOIN sjy_empresas ON sjy_bandeira.id_bandeira = sjy_empresas.bandeira
            WHERE sjy_empresas.grupo = $grupo
            AND id_bandeira = $bandorc";
      // Executa a consulta OU mostra uma mensagem de erro
      $rs = $MySQLi->query($qry) OR trigger_error($MySQLi->error, E_USER_ERROR);

      // Faz um loop, passando por todos os resultados encontrados
      while ($dt = $rs->fetch_object()) {
            $band       = $dt->band;
            $bandeira   = $dt->bandeira;
            $nick       = $dt->nick;
            $emp        = $dt->id_empresa;
            echo    "<option value='premorc.php&fnc=". $fnc . "&ans=" . $linha . "&emp=" . $lj . "'>" . $nick . "</option>";
            }

            ?>

            </select>
        </form>

            </fieldset>

<?php
} else {   // Se a gestão do setor não é centralizada

echo "Outro código";}

Comment: adicione o `css`
Comment: Editei a publicação @MagicHat
Answer: Nesse caso, recomendo aplicar uma classe no primeiro elemento, e edita-la com CSS com float: left.

article.form {
  margin: 15px;
  padding:15px;
  border: 1px #90ac6e solid;
  border-radius: 6px;
  -webkit-box-shadow: 1px 1px 3px #000;
  -moz-box-shadow: 1px 1px 3px #000;
  box-shadow: 1px 1px 3px #000;
  background: #ffffff;
  width: 500px;
  transition: background-color .4s, border-color .4s;
  float: left;
}
.left{
float: left;
}

Titulo

    <form id="frmCad" name="frmCad" method="post" action="../inc/processa.php?modo=incluir&fnc=<?php echo $fnc; ?>&ans=<?php echo $linha; ?>">

        <input name="emp" type="hidden" value="<?php echo $lj; ?>" />
        <input name="projeto" type="hidden" value="Budget" />
        <input name="exercicio" type="hidden" value="<?php echo $basebud; ?>" />
        <input name="linhabud" type="hidden" value="<?php echo $linha; ?>" />
        <input name="usuario" type="hidden" value="<?php echo $usuario; ?>" />

Anterior:

        <fieldset style="padding:8px; margin:15px 0px 25px 0px;">
            <form method="get" name="tBand" id="cBand" style="float:left;margin-top:0px;">
            <select name="menu1" onChange="MM_jumpMenu('parent',this,0)" class='left'>
                <option value="">Selecione a Bandeira</option>
        </select>
        </form>
        <form method="get" name="tLoja" id="cLoja" style="float:left; padding-left:15px;margin-top:0px;">
            <select name="menu2" onChange="MM_jumpMenu('parent',this,0)">
                <option value="">Selecione a loja</option>
               </select>
Comment: Olá Magno. Obrigado pela resposta. Exatamente esse problema. Está vendo que está vindo primeiro o segundo e o primeiro vem em seguida? Não consigo colocar isso na ordem certa...

Posicionando um FORM na página


SQL server casting string to integer checking value before casting

Question: I have a table with a field named MINIMUM_AGE.  The values stored in this field are of type nvarchar:
17 years
54 years
N/A
65 years

I would like to apply a WHERE clause on the column to check for a certain age range.  To do that I need to parse out the age from the field values.
So, I think I need to select the first two characters, then cast them into an integer.  Also, some fields may not contain numbers for the first two characters.  Some may simply be N/A.  So, I will need to check for that before casting.
Can someone explain how to accomplish this?
Answer: Here is the SQL Fiddle that demonstrates the below query:
SELECT CASE
  WHEN MINIMUM_AGE <> 'N/A'
  THEN CAST(LEFT(MINIMUM_AGE, 2) AS int)
  ELSE 0
  END
FROM MyTable

Note: the CASE expression can only return one data type.  So, in the example above if the MINIMUM_AGE is N/A then it returns 0.
If you would rather have it return null, then use the following:
SELECT CASE
  WHEN MINIMUM_AGE <> 'N/A'
  THEN CAST(LEFT(MINIMUM_AGE, 2) AS int)
  END
FROM MyTable


I have a mib file how can I see the oid for a specific "object"?

Question: I have seen some related questions here but they don't seem to answer my doubt.
I have several MIB files I'm reading them using a text editor (know any good free mib reader?)
I see the descriptions but don't know witch oid is using so I can place it on my snmpwalk query.
Answer: In Linux an OK browser is mbrowse..
http://sourceforge.net/projects/mbrowse/


Segfault on JNI_CreateJavaVM

Question: I am trying for the first time to load a JVM from C++ via JNI but I can't seem to get it to work. I get a segfault when I call JNI_CreateJavaVM.
The code is pretty straight forward (copied mostly from an online example):
#include<stdio.h>
#include<jni.h>

using namespace std;

int main(int argc, char** argv) {

    printf("Initializing JVM\n");
    JavaVM *jvm;
    JNIEnv *env;

    printf("Setting up args\n";
    JavaVMInitArgs vm_args;
    JavaVMOption* options = new JavaVMOption[1];
    options[0].optionString = "-Djava.class.path=.";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;

    printf("Attempting to create JVM\n");
    jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

    if(rc != JNI_OK) {
        printf("didn't work :(\n");
    }
    else {
        printf("JVM load succeeded!\n");
        jint ver = env->GetVersion();
        printf("Version: %i.%i\n", (ver>>16)&0x0f, ver&0x0f);

        printf("Cleaning up\n");
        delete options;
        jvm->DestroyJavaVM();
    }
    printf("Done\n");
}

My LD_LIBRARY_PATH contains /usr/java/jdk1.6.0_45/jre/lib/amd64/server which is the path containing a libjvm.so library. There are a few other libjvm.so libraries on my system, but most of them are for java 1.4. There is only one other jdk 1.6 libjvm.so and I tried using it as well with the same results.
I compile with:
g++ -g -c src/jniExpCppPart.cpp -I/usr/java/jdk1.6.0_45/include -I/usr/java/jdk1.6.0_45/include/linux -o obj/jniExpCppPart.o
g++ obj/jniExpCppPart.o -L/usr/java/jdk1.6.0_45/jre/lib/amd64/server -ljvm -o exe/jniExp

And when I run it within gdb, I get the first three print statements, followed by:
Program received signal SIGSEGV, Segmentation fault
0x0000003249479e27 in strncmp () from /lib64/libc.so.6
(gdb) bt
#0 0x0000003249479e27 in strncmp () from /lib64/libc.so.6
#1 0x00002aaaaacd8c10 in Arguments::process_sun_java_launcher_properties(JavaVMInitArgs*) () from /usr/java/jdk1.6.0_45/jre/lib/amd64/server/libjvm.so
#2 0x00002aaaab2cfe7d in Thread::create_vm(JavaVMInitArgs*, bool*) () from /usr/java/jdk1.6.0_45/jre/lib/amd64/server/libjvm.so
#3 0x00002aaaaafcc800 in JNI_CreateJavaVM () from /usr/java/jdk1.6.0_45/jre/lib/amd64/server/libjvm.so
#4 0x0000000000400761 in main(argc=1, argv=0x7fffffffe568) at src/jni/ExpCppPart.cpp:22

My guess is that the issue has more to do with how my environment is set up or how I built the executable rather than the code. Its been a few years since I really dealt with linking shared libraries, so its definitely possible that I messed something up.
Any ideas what I might be doing wrong?
Update
I tried loading the library using dlopen instead (because I saw it in some Linux code that uses JNI). It didn't make difference, but I thought I'd include it here to see if it gives anyone a hint of what I may be doing wrong.
Once again I'm copying this by hand from a system that isn't connected to the internet, so there may be some typos.
#include<stdio.h>
#include<jni.h>
#include<dlfcn.h>

using namespace std;

//Create type for pointer to the JNI_CreateJavaVM function
typedef jint (*CreateJvmFuncPtr) (JavaVM**, void**, JavaVMInitArgs*);

//New method returns pointer to the JNI_CreateJavaVM function
CreateJvmFuncPtr findCreateJvm() {
    CreateJavaFuncPtr createJvm = NULL;

    void* jvmLib = dlopen("libjvm.so", RTLD_LAZY); //Get handle to jvm shared library
    char* error = dlerror(); //Check for errors on dlopen

    if(jvmLib = NULL || error != NULL) {
        printf("FailedToLoadJVM\n");
    }

    //Load pointer to the function within the shared library
    createJvm = (CreateJvmFuncPtr) dlsym(jvmLib, "JNI_CreateJavaVM");

    error = dlerror();
    if(error != NULL) {
        printf("Success\n");
    }

    return createJVM;
}

int main(int argc, char** argv) {

    printf("Initializing JVM\n");
    JavaVM *jvm;
    JNIEnv *env;

    printf("Setting up args\n";
    JavaVMInitArgs vm_args;
    JavaVMOption* options = new JavaVMOption[1];
    options[0].optionString = "-Djava.class.path=.";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;

    printf("Attempting to create JVM\n");
    //Old code: jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    //New code:
    CreateJvmFuncPtr createJVM = findCreateJvm();
    printf("findCreateJVM() returned 0x%x\n", createJVM);

    jint rc = createJVM(&jvm, (void**)&env, &vm_args);
    //End new code

    if(rc != JNI_OK) {
        printf("didn't work :(\n");
    }
    else {
        printf("JVM load succeeded!\n");
        jint ver = env->GetVersion();
        printf("Version: %i.%i\n", (ver>>16)&0x0f, ver&0x0f);

        printf("Cleaning up\n");
        delete options;
        jvm->DestroyJavaVM();
    }
    printf("Done\n");
}

The output (similar to before) shows that everything is successful until it throws a segfault from within the JNI_CreateJavaVM method.
Initializing JVM
Setting up args
Attempting to create JVM
Success!
findCreateJVM() returned 0xc1e70780
Segmentation fault

So it seems that at the very least the program can find the library/function just fine. But something goes wrong when it's called. To me this indicates that it could either be just a simple API misunderstanding (I'm passing it something other than what I should be) or there's something weird with the shared library. Could this be caused perhaps if the shared library was compiled for an architecture/word size different than my program was compiled for? If so, how can I check the target architecture for both my program and the library?
Comment: hmm it was made for windows which might be a problem with low level calls being used
Comment: That could be the issue. I'll try to look for some Linux examples and see what differences there are.
Comment: with segfault i have a feeling the code you are using has a logic error. since a segfault is trying to access memory that is not there, like when you go over the bounds of an array. also makes sense you get the first three print statments since fails at the line `jint rc = JNI_CreateJavaVM(&jvm, (void**)&&env, &vm_args);`
Comment: what command do you use to run the program? also compile with -Wall and -Werror
Comment: I run with just ./exe/jniExp
Or with gdb, gdb exe/jniExp followed by run
Comment: in that case i think it might be trying to read an expected argument that is not there. i mean it is hard to read with no comments so i could be wrong.
Comment: Here's the example code I was looking at with more comments: http://www.codeproject.com/Articles/993067/Calling-Java-from-Cplusplus-with-JNI
Answer: Well this is embarrassing...
I finally found out my problem and there's no way anyone on stack overflow could have fixed it because the code I posted in the question is actually correct, but it is not the same code as what I was running.
As I mentioned, I am running this code on a standalone system without internet access, so I had to copy the code by hand. In copying it, I corrected my mistake.
The code that is on my standalone system, includes the following lines:
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-Djava.class.path=.";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = false;

Which you'll notice is not the same as the code I posted in the question. Because it is missing the line:
vm_args.options = options;

So of course it would cause a segfault because vm_args.options was never set to anything.
Answer: The bug you're getting is on this line:
jint rc = JNI_CreateJavaVM(&jvm, (void**)&&env, &vm_args);

You're asking for the address of the address of a pointer to the env; whereas if you look at the reference example source:
#include <jni.h>       /* where everything is defined */
...
JavaVM *jvm;       /* denotes a Java VM */
JNIEnv *env;       //

Segfault on JNI_CreateJavaVM


2 Datatables to 1

Question: Let's say i have Datatable1 that has "Colum1" , "colum2"
and another table, Datatable2 with "Colum3" , "colum4"
I need to create Datatable3 that will contain all the columns "Colum1" , "colum2", "Colum3" , "colum4"
I need something smart, like the DefaultView.ToTable() method that does it for one table.
Thanks
Comment: How do you expect to join the rows?  How do you plane to determine what row from Datatable1 matches Datatable2?
Comment: Both tables?  Which column in each table is the primary key?
Comment: Database? Memory? Ado? Excel? JDBC? Access? Word? Provide at least some tags to specify the technologies you are using.
Comment: Datatable and DefaultView.ToTable are from ADO.NET - looks like a request to combine two .NET Datatables - no SQL or particular DB
Comment: Yes, but that is us assuming stuff...
Answer: As you didn't mention any language or DB server type, here's something that might work (not tested really) on SQL Server 2005:
<code>CREATE TABLE #temp (col1 <type>, col2 <type>, col3 <type>, col4 <type>)
INSERT INTO #temp
(
    SELECT t1.Column1, t1.Column2, t2.Column3, t2.Column4
    FROM Datatable1 t1 INNER JOIN Datatable2 t2 ON t2.<PrimaryKeyField> = t1.<PrimaryKeyField>

    UNION

    SELECT t1.Column1, t1.Column2, t2.Column3, t2.Column4
    FROM Datatable2 t2 INNER JOIN Datatable1 t1 ON t1.<PrimaryKeyField> = t2.<PrimaryKeyField>
)

SELECT * FROM #temp
</code>
Comment: Hello. Sorry i meant the .net object Datatable. I would like to do it in the c# code, not in the DB level.

2 Datatables to 1


Xamarin Android: Cannot choose compile version

Question: If I want to choose an Item from the "Compile using Android Version" Dropdown, the only item I can choose is "Use latest Platform".

I installed the following SDK packages:

Shouldn't the program give me other options?
Answer: It seems like Visual Studio doesn't recognize your Android SDK.
Check the path of your Android JDK, SDK, NDK under Tools > Options > Xamarin > Android Settings, and make sure you point them to their correct locations.
Comment: All of them seem fine to me
Comment: You should try reinstalling JDK & SDK then
Comment: Also all packages or only the program itself?
Comment: @DieterMüller I would recommend everything, including the JDK, SDK and the packages.
Comment: Ok, I'll try it
Comment: I have the same problem. Did this answer work as accepted, or did you have to do something else too?


how can i display a productlist in a listbox based on the category button i click on?

Question: I have a menu with buttons, each button has a category on it. Next to the menu i placed a listbox. This listbox is linked to a productlist in the database. I want that whenever I press a categorybutton, the products linked to that category (with a categoryID) will display in the listbox.
Im using the following code to display the products in the listbox
var productslist = from products in db.products select products;
prodlb.ItemsSource = productslist;

Comment: Didn't you try using where to filter the products `from product in db.products  where product.CategoryId = selectedCategoryId select product`
Comment: Doesnt work, product.categoryId gets red underlined
Comment: Don't just copy paste the code. Understand the logic. What property do you have in product object to represent category of it?
Comment: I didnt copy paste, but the where clause doesnt work
Comment: There was a slight error in my code. The updated one is `from product in db.products where product.CategoryId == selectedCategoryId select product`. Try this. If there is an error, share the exact error here.
Answer: private void Buttonproducts_OnClick(object sender, RoutedEventArgs e)
    {
        var productslist = from products in db.products select products;
        prodlb.ItemsSource = productslist;
    }

private void ButtonCustomers_OnClick(object sender, RoutedEventArgs e)
    {
        var Customerslist = from Customers in db.customers select customers;
        prodlb.ItemsSource = Customerslist;
    }


Esconder e mostrar senha com JavaScript

Question: Estou tentando fazer o efeito de ao clicar no input check Mostrar Senha a senha digitada pelo usuário apareça para ele visualizar.
Semelhante ao desse formulário do Google.
O meu html está assim:

LOGIN

        <form class="div-container">
            <fieldset>

                        <legend>Matricula:</legend>
                            <input type="text" placeholder="Ex: 20201SI0068" class="input">
                            <legend>Senha:</legend>
                            <input type="password" placeholder="No mín. 8 caracteres, . , ; @ # % e etc" class="input">

                                <input type="checkbox" class="check" checked="checked" />
                                Mostrar senha

                                    <button id="butao-entrar">Entrar</button>

         </fieldset>
     </form>

Eu quero que quando o check estiver checked apareça a senha, mas até agora ainda não consegui desenvolver.
Comment: mas @Carolina posta teu js... não é só alterar **password** para **text**, tem ação do checkbox.
Comment: Basta você trocar o `type="password"` para `type="text"` quando quiser mostrar e reverter o processo quando quiser esconder.
Answer:

Esconder e mostrar senha com JavaScript