Composição: usar @class ou #import?

Question: Recentemente tive um problema de Unknow type name 'Class', pois estava fazendo import no header de 2 classes. Descobri que esse é um erro clássico de headers importando headers.
Fui orientado a mudar o import de uma das classes para @class e na classe de implementação (.m) fazer a importação.
Minha pergunta é: quando usar @class ou #import? Eu poderia apagar os imports de todas minhas classes que fazem referência a outras classes e simplesmente escrever @class e aí sim importá-las no implementation file?
Answer: Aqui vai uma resposta sumariada (e não 100% correcta). Este assunto é bastante extenso para explicar num post, se não ficares satisfeito terás de ser tu a pesquisar para aprofundar a questão. Só quero dar-te uma ideia simples, aconselho que aprofundes mais o assunto.
Mas primeiro, vou supor que não sabes C e dar uma breve explicação em como o código é transformado em app.
Podemos dizer que existem 3 passos (na verdade são mais, mas conhecer estes três é o suficiente para ter uma boa noção do processo):
1) Pré-compilação
Isto é quando o código é preparado para compilação, quando as directivas #define, #ifdef, etc. são processadas. Ou seja, se tivermos um #define MyDef 3, ao fim deste passo todos os sítios do código com MyDef terão 3.
É também este passo que gere as redefinições de macros, por exemplo, se tivermos os ficheiros a.h
#define MyDef 3

e b.h
#define MyDef 4

Quando usarmos o MyDef, o seu valor dependerá na ordem em que incluímos os headers.
#import "a.h"
#import "b.h"
// MyDef == 4

#import "b.h"
#import "a.h"
// MyDef == 3

2) Compilação
Este é o sumo de todo o processo, por isso é que se chama de compilação também aos três passos juntos, porque este é o principal.
É este passo que transforma o código em linguagem máquina. Este passo resulta em ficheiros binários como código executável. Tem os bytes que o processador irá interpretar durante a execução para saber o que fazer.
Estes binários parciais têm também referências para os outros binários parciais e bibliotecas do iOS (as .framework).
3) Linking
Este é o último passo. É quando todos os binários parciais resultantes do 2 são juntos num só executável.
É também aqui que os recursos são adicionados ao binário final.

Ao usar a directiva @class estamos a dizer ao compilador que a classe existe e que não é preciso verificar a sua existência, delegando essa verificação para o linking.
Por exemplo:
@class XPTO;
@interface YPTO : NSObject
    @property (strong, nonatomic) XPTO *xpto;
    //...
@end

Este .h diz ao compilador não te preocupes com a XPTO isso será tratado no linking.
Isto tem um problema, não tendo uma referência para a classe, o compilador não a sabe usar. Por isso, no .m adicionamos o #import:
#import "YPTO.h"
#import "XPTO.h"
@implementation YPTO
    - (void)yMethod
    {
        [xpto xMethod];
    }
    //...
@end

Sem o #import, o compilador não sabe qual a referência do método xMethod a usar quando criar o binário parcial do YPTO. Isto pode ser visto da seguinte maneira. A directiva @interface cria as referências, se o compilador não lê a @interface não sabe quais as referências a usar.
O que acontece é que o compilador (e também o pré-compilador) quando percorre o YPTO.m irá i) ler o YPTO.h, ii) ler o XPTO.h e ii) ler a @implementation YPTO.

Quando usar @class ou #import?

Usa o @class quando não precisas do #import.
Pessoalmente, tento ter o mínimo de #imports nos .h possível. Usando o exemplo das classes XPTO e YPTO. Imagina que mais tarde criamos uma classe ZPTO que usa a YPTO, mas não precisa da XPTO. Ao fazermos o #import "YPTO.h", o compilador não perderá tempo a ler o XPTO,h nem os #imports dele.
Outra vantagem é que reduzimos a possibilidade de termos, por exemplo,
a.h
#import "b.h"

b.h
#import "a.h"

Onde ao ler o a.h, o compilador iria ler o b.h, que por sua vez faria o compilador ler o a.h, b.h, a.h, ad infinitum.

Eu poderia apagar os imports de todas minhas classes que fazem referência a outras classes e simplesmente escrever @class e aí sim importá-las no implementation file?

Vou supor que quando falas em apagar das classes te referes aos .h.
A reposta parece ser "sim, podes". Mas há duas coisas a ter em atenção.
Primeiro, não é boa ideia.
Sei que parece ir em contradição com o que respondi à outra questão, mas o que disse foi que pessoalmente tento ter o mínimo de #imports nos .h possível.
Por vezes é preferível ter #imports no .h.
Voltando ao exemplo das classes XPTO e YPTO. Imagina que todos os métodos da YPTO recebem e/ou retornam instâncias de XPTO. É muito provável que quem importe o YPTO.h também queira importar o XPTO.h, viste que YTPO tem uma relação de dependência da XPTO. Neste caso fará sentido que o #import "XPTO.h" esteja no YPTO.h.
Segundo, não podes.
Embora pareça que sim, existem situações onde tal não é possível.
@class Super
@interface Class : Super
    //...
@end

Neste exemplo, o compilador não terá uma referência para a classe Super e não saberá como resolver a herança.

Como extra, quero avisar que se quiseres fazer algo semelhante ao @class para protocolos, podes fazê-lo com o @protocol.
Por exemplo,
@protocol Delegate;
@interface Class : NSObject
    @proprety (weak, nonatomic) id<Delegate> delegate;
    //...
@end

No entanto, não é possível fazer
@protocol Delegate;
@interface Class : NSObject <Delegate>
    //...
@end

pois o compilador não terá a referência do protocolo.
Answer:
Minha pergunta é: quando usar @class ou #import?

@Class: É usado quando queremos declarar um objeto de uma classe qualquer.
// File: CadastroAnimal.h
@class Animal;
@interface CadastroAnimal : UIViewController {
    Animal*   _animal;
}
@end
import: É usado quando queremos usar os métodos de qualquer classe ou queremos definir o delegado para esta classe.
//File: CadastroAnimal.h
import Animal.h
@interface CadastroAnimal : UIViewController
{
   Animal*   _animal;
}

Eu poderia apagar os imports de todas minhas classes que fazem referência a outras classes e simplesmente escrever @class e aí sim importá-las no implementation file?

Fazendo isso quer dizer que não queremos usar os métodos da classe "Animal" neste momento, nem queremos definir o delegado de classe "Animal.h". Daí podemos usar isso para aumentar a velocidade do compilador.
Se usar o #import "Animal.h" e não for definir o delegado da classe é melhor fazer a importação somente no implementation file, já que utilizaremos seus métodos apenas neste arquivo.
Answer: No seu header file, quando você precisa se referenciar a uma classe você usa o @class, já dentro do seu source você vai utilizar a classe e não somente referenciá-la, então você usa #import

Composição: usar @class ou #import?


Query para devolver apenas os registos das ultimas 24h (Codeigniter)

Question: Olá
Necessitava fazer uma query que me retorna-se os valores de apenas das ultimas 24h
eu tenho a seguinte query:
            $date = date("Y-m-d H:i:s");
            $this->db->select('*');
            $this->db->from('inscricoes');
            $this->db->where('data <', $date);
            $this->db->where('data >', $date-1);
            $query = $this->db->get();

mas está a retornar todos os valores
Comment: Dois Where? é conflito, faça 1 variavel para juntar texto where blablabla e depois `$this->db->where(variavel);`
Answer: Se você quer as últimas 24 horas contando a partir da hora e dia atual, você pode usar a função strtotime e subtrair 24 horas da data atual.
Você pode adicionar BETWEEN na sua query:
$maxDate = date("Y-m-d H:i:s");

$minDate = date("Y-m-d H:i:s", strototime('-24 hours');

$this->db->where(
     "data BETWEEN $minDate AND $maxDate", NULL, FALSE
);

Agora se você quer as atividades apenas dentro do dia atual, você pode fazer assim:
 $maxDate = date('Y-m-d H:i', strtotime('now 23:59:59'))

 $minDate = date('Y-m-d H:i', strtotime('now 00:00:00'));

Referência foi tirada da resposta do Stackoverflow Inglês e adaptada por mim.


How to change 'text-decoration' property with jQuery?

Question: I have table with following structure:

        Element11
        Element12
        <input type="checkbox" class="check" />

        Element21
        Element22
        <input type="checkbox" class="check" />

I want, after check <input class="check" ... /> the value of the property text-decoration to make 'underline' on the following row.
$('.check').click(function(){
   $('infoRow').css("text-decoration", "underline");
});

This code change all rows.
Thanks in advance.
Answer:
...to make 'underline' on the following row.

(My emphasis).
To underline it on the following row, you'd want to go up to the checkbox's parent row, then to its sibling row, then apply css to that:
$(this).closest('tr').next('tr').css('text-decoration', 'underline');

Separately, you probably want to test whether the checkbox is being checked or unchecked, e.g.:
$('.check').click(function(){
    $(this).closest('tr').next('tr').css(
        'text-decoration',
        this.checked ? 'underline' : 'none'
    );
});

Live example
Comment: Nice answer.

My 2 cents - it is a better practice to add a `class` (and style it accordingly in the stylesheet) to the effected element instead of changing the style directly using the `.css()` method.


Como limpar resultados de pesquisa em uma lista após clicar em um botão?

Question: tenho uma lista de itens e um campo de pesquisa que filtra essa lista à medida em que algo é digitado nesta mesma caixa. Tenho também um botão de reset que limpa a caixa de pesquisa e foca nela, mas não limpa os resultados filtrados com base no que foi digitado.
P.S: Refiro-me a esta página: http://einconformado.blogspot.com.br/p/textos.html
Segue o código que estou usando:

$(function() {
    $("#myInput").keyup(function() {
      $("#body-post p").css("display", "none");
      var texto = $(this).val().toUpperCase();
      $("#body-post li").css("display", "block");
      $("#body-post li").each(function() {
        if ($(this).text().toUpperCase().indexOf(texto) < 0)
          $(this).css("display", "none");
      });
    });
  });
#myInput {
  background: url('http://w3schools.com/css/searchicon.png') 10px 6px no-repeat #fff;
  width: 50%;
  font-size: 13px;
  font-family: Open Sans;
  color: #000;
  padding: 8px 40px;
  border: 1px solid #bbb;
  transition: all 0.3s;
  margin: 6px 0;
  margin-left: 6px
}

#myInput:hover,
#myInput:focus {
  box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.08)
}

#myInput:focus {
  border: 1px solid #D80000
}

#rst {
  height: 36px;
  color: #2d2d2d;
  border: none;
  background: transparent;
}

#rst:hover {
  color: #D80000
}

<form>
  <input id='myInput' placeholder='Pesquisar texto...' title='Digite algo...' type='text'>
  <input id='rst' value='×' type='reset' onclick="document.getElementById('myInput').focus();">
</form>

207 Quando a tristeza e a revolta resolvem marcar um encontro dentro de mim

206 Sete Ensinamentos de Números 11

205 Tenha e Mantenha

Desde já, agradeço! =]
Answer: Faltou implementar o código para o botão de reset que coloca os resultados todos de novo:
$("#rst").on("click", function(){
  $("#body-post li").css("display", "block"); //mostrar tudo
  $("#myInput").focus(); //colocar o focus na caixa de texto
});

Com esta implementação para o evento de click do reset deixa de ser necessário de ter o atributo onclick na etiqueta, podendo ficar apenas:
<input id='rst' value='×' type='reset'>

Veja a funcionar no exemplo completo:

$(function() {
    $("#myInput").keyup(function() {
      $("#body-post p").css("display", "none");
      var texto = $(this).val().toUpperCase();
      $("#body-post li").css("display", "block");
      $("#body-post li").each(function() {
        if ($(this).text().toUpperCase().indexOf(texto) < 0)
          $(this).css("display", "none");
      });
    });

    $("#rst").on("click", function(){
      $("#body-post li").css("display", "block");
      $("#myInput").focus();
    });
  });
#myInput {
  background: url('http://w3schools.com/css/searchicon.png') 10px 6px no-repeat #fff;
  width: 50%;
  font-size: 13px;
  font-family: Open Sans;
  color: #000;
  padding: 8px 40px;
  border: 1px solid #bbb;
  transition: all 0.3s;
  margin: 6px 0;
  margin-left: 6px
}

#myInput:hover,
#myInput:focus {
  box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.08)
}

#myInput:focus {
  border: 1px solid #D80000
}

#rst {
  height: 36px;
  color: #2d2d2d;
  border: none;
  background: transparent;
}

#rst:hover {
  color: #D80000
}

<form>
  <input id='myInput' placeholder='Pesquisar texto...' title='Digite algo...' type='text'>
  <input id='rst' value='×' type='reset'>
</form>

207 Quando a tristeza e a revolta resolvem marcar um encontro dentro de mim

206 Sete Ensinamentos de Números 11

205 Tenha e Mantenha

Comment: Perfeito, Isac! Muito obrigado mesmo, cara! Deus te abençoe! Abraços!
Comment: @Vitor De nada. Estamos cá para ajudar :)


Como chamar uma função dentro do método setTimeOut() passando parâmetros?

Question: Por exemplo, abaixo tenho dois botões que quando clicados exibem conteúdos diferentes:

let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");

btn1.onclick = () => {
    console.log("BOTÃO 1");
};

btn2.onclick = () => {
    console.log("BOTÃO 2");
};
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>

Mas, se eu quiser chamar o método log() após alguns segundos com o método setTimeout() passando parâmetros na função a ser chamada no método setTimeout(), isso não vai funcionar:

let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");

btn1.onclick = () => {
    setTimeout(msg("BOTÃO 1"), 1000);
};

btn2.onclick = () => {
    setTimeout(msg("BOTÃO 2"), 1000);
};

function msg(txt) {
    console.log(txt);
}
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>

Isso porque estou chamando a função msg() imediatamente, pois informei os parênteses. Como eu posso passar parâmetros para função a ser chamada no método setTimeout()?
Answer: Exatamente assim, certo?
btn1.onclick = () => {
    setTimeout(() => msg("BOTÃO 1"), 1000);
};

btn2.onclick = () => {
    setTimeout(() => msg("BOTÃO 2"), 1000);
};

https://jsfiddle.net/5sgwnk0u/
O setTimeout espera uma função de callback, mas a função msg não retorna nada (void) e vai dar erro dizendo que ele espera uma função como callback.
Answer: Os dois melhores jeitos de resolver para resolver esta questão são: primeiro criando uma function no setTimeout() e que essa function chama a function na qual que você quer que ela exerce, nesse caso a msg(txt).
Já o segundo jeito, na qual é o que mais recomendo e o mais prático é, o setTimeout recebe um terceiro parâmetro que é enviado como parâmetro para a function ao final do cronômetro. *Porém você terá de criar uma variável ou envia a String como parâmetro no final do setTimeout sem problemas.
Exemplo:
setTimeout(function, 1000, param1, param2, parametros...);

OPÇÃO 1:

let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");

btn1.onclick = () => {
     setTimeout(()=> { msg("BOTÃO 1")}, 1000);
};

btn2.onclick = () => {
    setTimeout(() => { msg("BOTÃO 2")}, 1000);
};

function msg(txt) {
    console.log(txt);
}
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>

OPÇÃO 2:

let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");

btn1.onclick = () => {
    var txt = "BOTÃO 1"
    setTimeout(msg, 1000, txt);
};

btn2.onclick = () => {
    var txt = "BOTÃO 2"
    setTimeout(msg, 1000, txt);
};

function msg(txt) {
    console.log(txt);
}
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>

O que também poderia ser na Opção 2:
    btn1.onclick = () => {
    setTimeout(msg, 1000, "BOTÃO 1");
};

btn2.onclick = () => {
    setTimeout(msg, 1000, "BOTÃO 2");
};

Espero ter ajudado.


Teclado Touchscreen - Limitar o número de caracteres inseridos em javascript

Question: Estou trabalhando em um teclado touchscreen, coloquei os números de 0 a 9, tecla limpar e entrar. Conforme os números são clicados eles aparecem em um display.
Para capturar os números clicados estou usando a seguinte função:
function addNumber(e){
    var v = $( "#PINbox" ).val();
    $( "#PINbox" ).val( v + e.value );
}

Como faço para limitar em 5 a quantidade de números capturados?
Ex.: 12345 e não aceita mais números.
Desde já agradeço pela atenção.
Comment: Você está usando algum framework? Somente html + javascript?
Answer: Você pode verificar se o campo já contém o limite de caracteres definido a cada iteração.
function addNumber(e){
    var v = $( "#PINbox" ).val();
    if( v.length < 5 )
        $( "#PINbox" ).val( v + e.value );
}

Caso esteja trabalhando com HTML também pode tentar definir um range para o campo (não tenho certeza que vai funcionar neste seu caso). Assim você pode adicionar um atributo max que irá especificar o maior número possível que você pode inserir.
<input type="number" max="99999" />

Se você adicionar um max e um min, poderá especificar o intervalo de valores permitidos:
<input type="number" min="1" max="99999" />

Comment: O `<=` está incorreto. Deveria ser apenas `<`, senão vai aceitar 6 caracteres.
Comment: Verdade @Sam, corrigi a resposta.
Comment: Cara, nem precisa do `else return false`... só o `if` já resolve.
Answer: Uma forma é usar um operador ternário no .val(). Se o número de caracteres for menor que 5, irá concatenar o valor atual + o número clicado, caso contrário irá manter os 5 números alcançados:

function addNumber(e){
   var v = $( "#PINbox" ).val();
   $( "#PINbox" ).val( v.length < 5 ? v + e.value : v );
}

<input id="PINbox" type="text" readonly>

<button value="1" onClick="addNumber(this)">1</button>
<button value="2" onClick="addNumber(this)">2</button>
<button value="3" onClick="addNumber(this)">3</button>
<button value="4" onClick="addNumber(this)">4</button>
<button value="5" onClick="addNumber(this)">5</button>
<button value="6" onClick="addNumber(this)">6</button>
<button value="7" onClick="addNumber(this)">7</button>
<button value="8" onClick="addNumber(this)">8</button>
<button value="9" onClick="addNumber(this)">9</button>
<button value="0" onClick="addNumber(this)">0</button>

<button onClick="$('#PINbox').val('')">Limpar</button>


RStudio "Hit  to see next plot:"

Question: SORRY Thanks for everyone's help. I was a dick in the comments. Sorry about that.
For the life of me I cannot get RStudio to stop telling me to "Hit  to see next plot:"
MWE:
data(women)
fit = lm(weight ~ height, women)
plot(fit)

plot(fit) should print a 2x2 plot, but instead I have to view each subplot one by one.
What is driving me crazy is that I set par(ask=FALSE) and devAskNewPage(ask = FALSE). I even downloaded the latest R and Rstudio. Nothing works.
Is this a bug? Or am I missing something really obvious?
UPDATE. I started from scratch. I deleted R and RStudio. I deleted all my .R history files and cache. Re-downloaded R and Rstudio. But still: "Hit  to see next plot:"
EDIT. I should also point out that I had never before seen the message "Hit  to see next plot:". Suddenly it appeared and it won't leave.
Answer: Edit
Fixed answer to account for 2x2 layout:
fit = lm(weight ~ height, women)
par(mfrow = c(2, 2))
plot(fit, ask=FALSE)

Edit:
This is the behaviour as documented by lm's plot method. The second example mentions the 2x2 plot. It's not a bug but the intended behaviour of plot.lm.
Comment: @invictus *"`plot(m)` of a model m should already show a `2x2` plot"* That is not correct. `plot.lm` will show 4 separate plots, asking for  to see the next plot. That's the default behaviour. If you did get a `2x2` plot before my guess is you set `par(mfrow = c(2, 2))` somewhere earlier in your script/code.
Comment: Nope. Tried that. It still plots each subplot one by one.
Comment: Ok, you deleted your original answer, which my first comment addresses. Re: your second comment, I know you can use `par(mfrow = c(2, 2))`, but `plot(m)` of a model `m` should *already* show a 2x2 plot. (My MWE is just some example I took from a stats intro lecture.) Besides, I don't need to `ask=F` inside `plot()`, since `par(ask=F)` is set globally.
Comment: Yes. I edited my answer to account for the 2x2 layout requirement. Maybe I still do not understand your question? Does this not fix your problem? No need to uninstall RStudio... sorry if this is not helping
Comment: try enlarging your plot window
Comment: @ChirayuChamoli tried, doesn't work. machine working fine otherwise. everything else in R and Rstudio working normally.
Comment: im getting Hit to see next plot if dont use `par(mfrow = c(2, 2))`. if i use that i get 2*2 plot.
Comment: I added a link to `?plot.lm`. The behaviour you are seeing is as intended.
Answer: It took me a day to figure this out!!  I ended up calling par(), and setting ask to false:
par(ask = FALSE)

By the way, I did not invoke this change to the parameter so that it is TRUE.  I have no idea how I did that, as I had not known about it until now.
Cheers,
Jason :-)
21 February 2022 1249(AWST)

RStudio "Hit  to see next plot:"


How can I store name/value pairs in a file with Ruby where the values can be also multiline text?

Question: How can I store name/value pairs (also called hashes) in a file with Ruby where the values can be also multiline text? Of course I want to code the most simple way.
I have seen such text files earlier in Windows:
[name]
Dr. Hash Mark

[biografy]
Bla bla bla
bla bla bla
bla bla bla

[works]
The big red one (1923)
The little black zero (1926)

Is there any library or gem for Ruby to handle this kind of files? Maybe I could use XML and the XMLSimple gem:
<man>
 <name>Dr. Hash Mark</name>
 <biografy>
  Bla bla bla
  bla bla bla
  bla bla bla
 </biografy>
 <works>
  The big red one (1923)
  The little black zero (1926)
 </works>
</man>

Both of them would be good for me, but I also need a handy application to fill in a bunch of this kind of text files with data, I have no clue which application to use to generate such text files which later will be readable with Ruby. I think of a relational database application  - but I am not sure - in which I can define my data structure (the name, biografy, works) and then I get text fields to fill in with data, and then save the data in the given format in text files. Can anybody help me how to achieve this?
Answer: YAML is a good choice, there is a lib for it in the stdlib, it is human readable/editable, it's fairly widely used (e.g. settings files in Rails), it supports multiline strings:
require 'yaml'

filename = 'hash.yaml'
original_hash = {'a' => 'b', 'c' => "d\ne"}
File.write filename, YAML.dump(original_hash)

puts "FILE LOOKS LIKE: #{File.read filename}"
puts "-" * 10

resulting_hash = YAML.load File.read(filename)
puts "READ BACK IN: #{resulting_hash.inspect}"

puts "ARE THEY THE SAME? #{original_hash == resulting_hash}"

Comment: and a visual editor application which can export to YAML format?
Comment: I don't really know what that means, but YAML is a plain text format, and both of the text editors I use (vim and TextMate) will automatically recognize and highlight it when I open it (you'll probably have to configure this in vim if you haven't used it before).


Concurrency involving two tangents and a secant of a circle

Question: I found out this problem while fooling around with Geogebra.
Let $(O)$ be a circle in the plane, $A$ be a point lies outside of the circle. From $A$, draw two tangents $AB, AC$ to $(O)$ ($B, C\in (O)$). A line $d$ passing through $A$ ($O\not\in d$) intersects $(O)$ at two points $E, F$. $BC$ and $EF$ intersects at $K$; $CE, CF$ intersects the line $AO$ at $X, Y$ respectively.
a. Prove that $CK, FX, EY$ are concurrent.
b. Let $D$ be the intersection of $BO$ and $(O)$. $DE, DF$ intersect $AO$ at $M, N$ respectively. Prove that $DK, EN, FM$ are concurrent.

What I have proved so far:

$AEMC, AFCN$; $EMYF, EXNF$ are inscribed.
$OM = ON$.

Indeed, since $\widehat{CEM} =\widehat{EBD}$ and $\widehat{OBE} = \widehat{BAM}=\widehat{MAC}$ then $AEMC$ is inscribed. Similarly, $AFCN$ is inscribed.
Now since $\widehat{AME} = \widehat{ECA}$ and $\widehat{ECA} = \widehat{EFC}$ then $\widehat{EMY}+\widehat{EFY} = \pi$, thus $EMYF$ is inscribed. Similarly, $EXNF$ is inscribed.
Note that $MNDC$ is an isosceles trapezoid, then $BMDN$ is a parallelogram thus $O$ is the midpoint of $MN$.
Experimenting on Geogebra shows that the above results are true, however Still I can't prove them. Please help me, thanks.
UPDATE: I've edited my post to include my attempts. And thanks to Reza Rajaei and D S solutions, I still love to see a solution without using trigonometric Ceva theorem. Thanks for answering my questions.
Comment: @anomino I have also proved $IJ || AO$ in an edit.
Comment: In addition, with the above configuration, can we prove that $IJ\parallel AO$?
Comment: that will take some work. Moreover, my Lemma 4 does not use the fact that $C$ and $D$ lie on the same circle, so it may be true, nor the fact that $D$ is the antpode of $B$.
Answer: First, note that $BECF$ is a harmonic quadrilateral. This directly implies $K = BC \cap EF$ is the harmonic conjugate of $A$ w.r.t $E,F$.
Then note that if $J = EY \cap FX$, then $CJ \cap AF$ must be the harmonic conjugate of $A$ w.r.t $E,F$, by the construction of harmonic conjugate. Hence, $CJ \cap AF = K$.

The second part follows by a similar reasoning.

If the terminology is too technical, you can proceed using the following lemmas.

Lemma 1: Given tangents $BA$ and $CA$ to the circumcircle of $\Delta BCE$, point $F \neq E$ which is the intersection of $AE$ and the circumcircle, the following holds:
$$\overline{BE}\cdot\overline{CF} = \overline{BF}\cdot\overline{CE}$$

This should be doable by sine rule alone.

Lemma 2: Given tangents $BA$ and $CA$ to the circumcircle of $\Delta BCE$, point $F \neq E$ which is the intersection of $AE$ and the circumcircle, the following holds:
$$\frac{AE}{AF} = \left( \frac{AB}{AF}\right)^2 = \left(\frac{EB}{BF}\right)^2$$

This can be done by the power of point $A$ and sine rule.

Lemma 3: Given tangents $BA$ and $CA$ to the circumcircle of $\Delta BCE$, point $F \neq E$ which is the intersection of $AE$ and the circumcircle, and $K = EF \cap BC$, the following holds:
$$\frac{KE}{KF} = -\left(\frac{EB}{BF}\right)^2$$

You will need the sine rule and lemma 1 here.

Lemma 4: Given three collinear points $A, E, F$ (not necessarily in that order, but here the order is the same), an arbitrary point $T$ outside this line, another line $l$ passing through $A$ such that $l \cap ET = P$ and $l \cap FT = Q$, let $H = EQ \cap FP$. Then, if $TH \cap EF = K'$, the following holds:
$$\frac{AE}{AF} = -\frac{K'E}{K'F}$$

You will need Ceva's theorem and Menelaus's Theorem here.
Note that lemma 2 and 3 together imply
$$\frac{AE}{AF} = -\frac{KE}{KF}$$
Then, for part 1, put $l = AO$, $T = C$, $P = X$, $Q = Y$, $H = J$, and in part 2, put $l = AQ$, $T = D$, $P = M$, $Q = N$, $H = I$, to conclude $K = K'$ in both cases. Done!

To prove $IJ \mid \mid AO$:

$$\measuredangle JEI = \measuredangle YEN = \measuredangle YEF - \measuredangle NEF = \measuredangle YMF - \measuredangle NXF = \measuredangle NMF - \measuredangle NXF = \measuredangle XFM = \measuredangle JFI$$
So that $E,J,I,F$ are concyclic.
Then
$$\measuredangle EIJ = \measuredangle EFJ = \measuredangle EFX = \measuredangle ENX \implies IJ \mid \mid AO \tag*{$\blacksquare$}$$
Comment: As an aside, we can show $ IJ \parallel CD \parallel AO $ by Menelaus on the lines $EJY, EIN$ in the triangles $KCF, KDF$. We get that $ KJ/JC = KE/EF \times FY/YC = KE/EF \times FN/ND = KI/ID$.
Comment: Your solution requires some technical knowledge. I have to review those Wiki pages!
Comment: All of them have simple proofs though, @RezaRajaei. Maybe I will add them.
Comment: Lemma 4 uses only normal version of Ceva's theorem
Comment: I checked out the wiki page [+1]. Just by using the definition and showing that $K$ is the harmonic conjugate of $A$, everything is clear. That was helpful. Of course, in spirit, both solutions are using sort of well-known concurrency theorems!
Answer: For Part $(a)$:
Step $1$:

Show that: $$\frac{FY}{YC}=\frac{AF}{AC} \times \frac{\sin \angle YAF}{ \sin \angle YAC}.$$

Step $2$:

 Show that: $$\frac{XC}{XE}=\frac{AC}{AE} \times \frac{\sin \angle YAC}{ \sin \angle YAF}.$$

Step $3$:

Show that: $$\frac{EK}{KF}=\frac{EB}{BF} \times \frac{\sin \angle CBE}{ \sin \angle CBF}=\frac{EB}{BF} \times \frac{CE}{CF}.$$

Step $4$:

 Show that $\frac{EB}{BF}=\frac{AB}{AF}$ and $\frac{CE}{CF}=\frac{AE}{AC}$.

Step $5$:

 Conclude that $\frac{FY}{YC} \times \frac{XC}{XE} \times \frac{EK}{KF}=1$. Now, note that the claim follows from Ceva's theorem.

For Part $(b)$:

 Do exactly the same process.
Comment: @anonimo You're welcome.
Comment: @DS You're right. However, I posted an incomplete solution. At least I tried to post hints and a general idea rather than a detailed solution. Maybe without Ceva's theorem, this could be a really hard problem.
Comment: this is a two-liner, I think I will post my solution now
Comment: Thank you @RezaRajaei, I really love to see a solution without using trigonometric Ceva theorem.
Comment: @anonimo what is the reason for your aversion to the trigonometric form? You have included the tag contest math; there are many problems from various olympiads that either use it or its proof in disguise for all their solutions.
Comment: I just think a more elementary solution would bring more insights into the problems. The more simple the apparatus, the more creative the solution, I think.


Adding a search box to the homepage of a website built on Sylius

Question: Could someone please explain how I can add a search box to the homepage of my website built on Sylius?
I have tried using the SyliusSearchBundle but that seems to be very out of data and the sample config settings throw errors.
I'd be grateful for any help.
Answer: Disclaimer
Steps below work at the time I'm writing. SyliusElasticSearchBundle plugin is in a heavy development state, some of the things crash now, but will be fixed for sure.
I've created a demo repository here: https://github.com/mheki/sylius-search-demo
You need running ElasticSearch and a SyliusElasticSearchBundle plugin.
Follow installation instructions from readme: https://github.com/Lakion/SyliusElasticSearchBundle
Just bear in mind to install sylius dev-master (circular dependency...)
Import bundle's config, routing, enable it in AppKernel.
At the moment I'm writing the bundle needed filter_sets config, otherwise it crashed
So start with the simple search by product name:
lakion_sylius_elastic_search:
    filter_sets:
        default:
            filters:
                name:
                    type: string

Populate elastic index with:
bin/console fos:elastic:pop

Override original routing for lakion_elastic_search_shop_product_index - use filter_set: for your channel code.
lakion_elastic_search_shop_product_index:
    path: /products
    methods: [GET]
    defaults:
         _controller: lakion_sylius_elastic_search.controller.search:filterAction
         _sylius:
            template: "@LakionSyliusElasticSearch/Product/index.html.twig"
            resource_class: "%sylius.model.product.class%"
            filter_set: default
    requirements:
        slug: .+

Original product index page was failing for me and I had to remove
{{ form_row(form.search) }}

from it. So copied @LakionSyliusElasticSearch/Product/index.html.twig into Resources directory:
Resources\LakionSyliusElasticSearchBundle\views\Product\index.html.twig and made that change.
Now the last thing is to create a form, for example copying the file _security.html.twig from SyliusShopBundle. Add something like this:

        <form action="{{ path('lakion_elastic_search_shop_product_index') }}" method="get">

                <input type="text" placeholder="{{ 'sylius.ui.search'|trans }}..." name="filter_set[name]" />
                <button type="submit" class="ui button mini">

                </button>

        </form>

and here we go :)
Comment: Thanks, I realised ProductPriceRange worked out of the box, but for product name match you have to add a little bit more code. Please have a look at: https://github.com/mheki/sylius-search-demo/commit/8fb6a98 where I basically copied SearchController from Lakion bundle and used SearchType form type.
Comment: ,I have tried to implement the search box as you have explained, but when I search for a product, it show all the products and not the particular product I have search in the search box.
Comment: Thanks It works nicely. Now I will try to make it autocomplete with ajax.
Answer: Alternatively, if you don't want to use the SyliusElasticSearchBundle plugin, you can implement a simple search on your own (which search inside the product name, description and category name) :
Create a classic html search form, for example:
<form role="search" method="get" action="{{path('app_search_results') }}">
    <input type="search" id="site-search" name="q"
           placeholder="{{ 'walrus.search.input.placeholder'|trans }}"
           aria-label="{{ 'walrus.search.aria.label'|trans }}">
    <button>{{ 'walrus.search.aria.button'|trans }}</button>
</form>

Create a controller action for the route 'app_search_results' in order to get the search request sent by your search form :
<?php

namespace AppBundle\Controller;

use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use \Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class SearchController extends Controller
{

/**
 * @var LocaleContextInterface
 */
private $locale;
/**
 * @var ChannelContextInterface
 */
private $channelContext;
/**
 * @var RepositoryInterface
 */
private $productRepository;

public function __construct(
    LocaleContextInterface $locale,
    ChannelContextInterface $channelContext,
    RepositoryInterface $productRepository
)
{
    $this->locale = $locale;
    $this->channelContext = $channelContext;
    $this->productRepository = $productRepository;
}

/**
 * @Route("/search", name="app_search_results")
 */
public function searchAction(Request $request) : Response
{

    $searchTerm = $request->query->get('q');

    $channel = $this->channelContext->getChannel();
    $localeCode = $this->locale->getLocaleCode();

    $products = $this->productRepository->findByTerm($channel, $localeCode, $searchTerm);

    return $this->render(
        '@App/search/searchListProducts.html.twig',
        [
            'products' => $products
        ]
    );
}

}

Don't forget to manually wire the dependency injected through the constructor.
Override the product repository in order to implements the findByTerm() method :
<?php

namespace AppBundle\Repository;

use Sylius\Bundle\CoreBundle\Doctrine\ORM\ProductRepository as
BaseProductRepository;
use Sylius\Component\Core\Model\ChannelInterface;

class ProductRepository extends BaseProductRepository
{

public function findByTerm(ChannelInterface $channel, string $locale, $searchTerm): array
{
    $qb = $this->createQueryBuilder('p')
                ->addSelect('translation')
                // get the translated product for the product regarding the current locale
                ->innerJoin('p.translations', 'translation', 'WITH', 'translation.locale = :locale')
                ->orWhere('translation.name LIKE :searchTerm')
                ->orWhere('translation.description LIKE :searchTerm')
                // get the taxons of the product
                ->innerJoin('p.productTaxons', 'productTaxon')
                ->innerJoin('productTaxon.taxon', 'taxon')
                // get the translated taxon
                ->innerJoin('taxon.translations', 'taxonTranslation', 'WITH', 'taxonTranslation.locale = :locale')
                ->orWhere('taxonTranslation.name LIKE :searchTerm')

                ->andWhere(':channel MEMBER OF p.channels')
                ->andWhere('p.enabled = true')
                ->setParameter('searchTerm', '%'.$searchTerm.'%')
                ->setParameter('locale', $locale)
                ->setParameter('channel', $channel)
                ->getQuery();

    return $qb->getResult();

}

}

You just need now to create the page rendering the list of product (the @App/search/searchListProducts.html.twig). And to tell Sylius to use your custom HomepageController instead of the original one. Same goes for your Product Repository. This can be done inside the services.yml file of you app folder :
services:
    sylius.controller.shop.homepage:
        public: true
        class: AppBundle\Controller\Shop\HomepageController
        arguments:
            - '@templating'
            - '@sylius.context.locale'
            - '@sylius.repository.taxon'

sylius_product:
    resources:
        product:
            classes:
                repository: AppBundle\Repository\ProductRepository


xlsxwriter format currency - problem with cents quantity

Question: i have no problem in formatting columns as currency, i did with this function:
def style_excel_currency(writer):
    wb = writer.book
    ws = writer.sheets['Fatture']
    money_fmt = wb.add_format({'num_format': '€#.###,##0'})
    ws.set_column('A:A', 10, money_fmt)

if __name__=='__main__':
   filename='attempt.xlsx'
   with pd.ExcelWriter(filename) as writer:

    df.to_excel(writer,
                 sheet_name='Fatture',
                 index=False,
                 engine='openpyxl')
    style_excel_currency(writer)

The issue is that some very low number get rendered weirdly in excel.
For example numbers in the hundreds or thousands of euros works well:

it fails to format correctly number in the cents area: ( 0,06 and 0,66)

I don't get if something is wrong with my formatting.
Example datasets:
df = pd.DataFrame(data={'col1':[100,101,200,0.06,0.66]})

Thanks
Comment: This is how you can 'num_format': '€#,##0.000'
Answer: The issue is that number format needs to be in a US style format since that is the way it is saved in the xlsx file. The number format you are looking for is probably "€#,##0.00". Something like this:
import pandas as pd

def style_excel_currency(writer):
    wb = writer.book
    ws = writer.sheets['Fatture']
    money_fmt = wb.add_format({'num_format': '€#,##0.00'})
    ws.set_column('A:A', 10, money_fmt)

if __name__=='__main__':
    filename='attempt.xlsx'
    with pd.ExcelWriter(filename) as writer:

        df = pd.DataFrame(data={'col1': [1234.567, 100, 101, 200, 0.06, 0.66]})

        df.to_excel(writer,
                    sheet_name='Fatture',
                    index=False,
                    engine='xlsxwriter')
        style_excel_currency(writer)

Output:

Although it is displayed on my system as €1,234.57, as shown in the image, on another Windows locale where the decimal and thousands separators are reversed (such as in Italy) it will be displayed as €1.234,57. Here is the same file with the locale changed to Italy:

This is explained in more detail in the XlsxWriter docs in the section on Number Formats in different locales.


Sum on simultaneous equation

Question: Solving this simultaneous equation is little bit hard.
The equation
$$\frac{1}{y-2} - \frac{1}{x+2}=\frac{1}{60}$$ and
$$\frac{1}{x} - \frac{1}{y}=\frac{1}{60}.$$
How to solve it please explain.
Comment: It is: $(\frac{1}{y}-2)-(\frac{1}{x}+2)=\frac{1}{60}$ ? Or  $(\frac{1}{y-2})-(\frac{1}{x+2})=\frac{1}{60}$ ?
Answer: Given equations:
\begin{equation}
\dfrac{1}{y-2} - \dfrac{1}{x+2} = \dfrac{1}{60} \tag{1}
\end{equation}
and
\begin{equation}
\dfrac{1}{x} - \dfrac{1}{y} = \dfrac{1}{60} \tag{2}
\end{equation}
From (1), we have
\begin{align}
& \dfrac{1}{y-2} - \dfrac{1}{x+2} = \dfrac{1}{60} \notag \\
\implies & \dfrac{(x + 2) - (y-2)}{(y-2)(x+2)} = \dfrac{1}{60} \notag \\
\implies & 60 x - 60 y +240 = xy +2y -2x -4 \tag{by cross multiplication} \\
\implies  & xy + 62y - 62 x -244 = 0 \tag{3}
\end{align}
Furthermore, from (2) we have
\begin{align}
& \dfrac{1}{x} - \dfrac{1}{y} = \dfrac{1}{60} \notag \\
\implies & \dfrac{1}{x} = \dfrac{1}{60} + \dfrac{1}{y} = \dfrac{y + 60}{60 y} \notag \\
\implies & x = \dfrac{60y}{y + 60} \tag{4}
\end{align}
Putting the value of $x$ from (4) to (3) yields,
\begin{align}
& \left( \dfrac{60 y}{y + 60}\right) \times y + 62 y - 62 \times \left( \dfrac{60 y}{y + 60}\right) - 244 = 0 \notag \\
\implies &60 y^{2} + 62 y(y + 60) - \left(62 \times 60\right) y - 244 (y + 60) = 0 \notag \\
\implies & 122 y^{2} - 244 y - (244 \times 60) = 0 \notag \\
\implies & y^{2} - 2y - 120 = 0 \notag \\
\implies & y^{2} - 12y + 10y - (12 \times 10) = 0 \notag \\
\implies & y (y - 12) + 10 (y - 12) = 0 \notag \\
\implies & (y + 10) (y - 12) = 0 \notag \\
\implies & y = -10, 12 \tag{5}
\end{align}
Using (4) and (5), the value of $x$ can be found as,
\begin{align}
x = \dfrac{60 \times (-10)}{-10 + 60}, \, \dfrac{60 \times 12}{12 + 60} = -12, 10
\end{align}
Answer: It's
$$xy=62x-62y+244$$ and
$$xy=60y-60x,$$ which gives
$$62x-62y+244=60y-60x$$ or
$$y=x+2$$ and I hope the rest is smooth.
I got $(10,12)$ and $(-12,-10)$.
Answer: from the second equation we get by multiplication with $$xy\ne 0$$
$$y-x=\frac{1}{60}xy$$ solving for $x$ we obtaine
$$x=\frac{y}{\frac{1}{60}y+1}=\frac{60y}{y+60}$$
plugging this in the first equation we obtain 8after symplifications
$$61y^2+122y+120=0$$
solving this we obtain
$$x=-12,y=-10$$ or $$x=10,y=12$$
Comment: You meant to write $y - x = \frac{1}{60}xy$.

Sum on simultaneous equation


diff for binary files

Question: I have a folder with one big file. This is a file that changes each day. Using tar for incremental backups is not a good idea as that big file (each file that is changed is saved) will be copied each day that an incremental backup is made.
Is there an application that makes a diff of two binary files (a differential backup)?
Thanks.
Answer: Look into duplicity as a way to do incremental backups.
Comment: What do you precisely mean?
Answer: rsync will make a full backup, but by copying only changes (if you don't care so much for storage space, its I/O that matters to you).
Alternatively, there's rdiff or xdelta that will work for binary files, your mileage may vary depending on where the changes occur inside the binary file to result in efficient changes or not. XDelta should work well for you though.
Answer: I found bsdiff here but I have never tried it and according to the developer it's a very memory hungry app...
Hope it helps you and let me know how it works out for you.

diff for binary files


Matlab linprog constraints: how to stop charge and discharge storage at same time?

Question: I'm having issues with matlab linprog code. The optimisation function is the overall cost for the 24 period, just considering fuel costs of the boiler.
Purpose of simulation:
Optimisation of the charge/discharge behaviour of a Thermal Energy Storage (TES) for a 24h operation of a system consisting of a boiler, heat demand, and the TES. The price of the gas are time-varying.
Problem:
If the TES is ideal (efficiency=100%), I have no constraint that stops the system from charging and discharging at the same time. I CANNOT use one variable to describe charge and discharge. I do need them separated
At the moment I have the following constraints to describe the min/max charge/discharge rates (and of course some others):
maxChargeThermalTES>=ChargeThermalTES<=0
maxDischargeThermalTES >= DischargeThermalTES <=0

is it possible to realise the following logical rule within the constraints of linprog?
if ChargeThermalTES<0,
   DischargeThermalTES=0
end

all approaches, e.g. with a binary variable (to describe if the system is charging or discharging) do not work, as the binary variable always depends on the output of the optimisation.
Answer: You cannot enforce such logical rule in linear programming.
However, what you can do is the following :
1\ solve your linear program, without this constraint. Get the optimal cost of your objective function (lets name it OldCost).
2\ Then change your linear program this way :

add a constraint : old objective function should be between OldCost * (1-Epsilon) and OldCost * (1+Epsilon)
the new objective function to minimize is ChargeThermalTES + DischargeThermalTES.

Cheers
Answer: Yes, it is possible. You can add your If-Then condition to linprog using one 0-1 binary variable and Big-M.
To realize the Logical rule:
if ChargeThermalTES<0,
   DischargeThermalTES=0
end

Condition: If ChargeThermalTES<0, then   DischargeThermalTES=0
Let's introduce a binary variable y
So we can rewrite the condition as
ChargeThermalTES - M y < 0

which implies that
if y = 0, then DischargeThermalTES must be = 0
if y=1, DischargeThermalTES can be anything

Let's split the equal to constraint into two inequalities
DischargeThermalTES < M y
DischargeThermalTES > -M y

If y=1, the above two are essentially non-binding.
If y= 0, it will force   DischargeThermalTES to become 0.
So with the following constraints combined, you can enforce your logical constraint to the Linear Program.
 ChargeThermalTES - M y < 0
 DischargeThermalTES < M y
 DischargeThermalTES > -M y
 y = {0,1} binary, M is a large number.

Hope that helps.


Verificar se todo $_POST foi enviado sem utilizar muitos ifs

Question: Bom dia,
Tenho que verificar se todos os campos do form, enviado como $_POST, não foram em branco, isto até que resolvi. Mas eu queria ver uma maneira de não precisar usar muitos if/elif para checar cada index do $_POST iria:
if(empty($_POST['nome'])){?>

Campo NOME em branco

<?php}
elif(empty($_POST['cpf'])){?>

Campo CPF em branco

<?php}
elif(empty($_POST['endereco'])){?>

Campo ENDERECO em branco

<?php}
...
else{

$nome = $_POST['nome'];
$cpf = $_POST['cpf'];
$endereco = $_POST['endereco'];
?>

Eu tentei apenas utilizar if(empty($_POST)) mas não funcionou, deixava passar mesmo com os campos em branco.
Answer: Pode simplificar consideravelmente a lógica, se utilizar um array auxiliar para os campos em que está interessado. Nesse caso pode iterar os campos com um foreach e testar se cada um está definido em $_POST, e mostrar o respetivo texto de campo em branco quando não está.
Exemplo:
$valido = true;
$campos = Array("nome", "cpf", "endereco");

foreach ($campos as $campo){
    if (empty($_POST[$campo])){
        echo "
Campo $campo em branco
";
        $valido = false;
    }
}

if ($valido){
    $nome = $_POST['nome'];
    $cpf = $_POST['cpf'];
    $endereco = $_POST['endereco'];
    //resto do código
}

Desta forma mesmo que tenha mais campos a verificar se estão preenchidos, apenas precisa de os acrescentar no array $campos.
Answer: Você pode fazer isso com um foreach, ficaria mais ou menos assim:
foreach ($_POST as $key => $value){
    if (empty($value)){
        echo "
Campo ".$key." em branco
";
        exit;
    }
}

$nome = $_POST['nome'];
$cpf = $_POST['cpf'];
$endereco = $_POST['endereco'];

Se dentro da variável $_POST for encontrado algum campo vazio, exibe uma mensagem e finaliza o programa.
Answer: Tenta alem de verificar se o valor é vazio, pois mesmo não preenchido ele vai retornar null e nulo já é considerado um valor, verifica também se existe, colocando o !isset.
Ficaria assim: if ( !isset( $_POST ) || empty( $_POST ) )
Answer: A partir do php5.5 empty() passou a avaliar expressões e não somente variáveis. Uma forma de resolver o problema é conectar todos os campos através de conjunções (vulgo E lógico) e deixar que o if cuide do resultado da expressão.
Importante: caso algum dos valores contenha zero ele será avaliado como false o que vai gerar um falso positivo, que atento a esse detalhe.
$_POST = array('id' => '', 'nome' => 'fulano', 'email' => 'email@example.com');

if(!empty($_POST['id'] && $_POST['nome'] && $_POST['email'])){
    echo 'campos válidos';
}else{
    echo 'campos inválidos';
}

echo "
";
print_r($_POST);

Exemplo - ideone
Comment: Obrigado! Vai me ser bem útil!
Answer: Eu trabalho da seguinte forma em meus projetos:

1 - Deixo o input de forma obrigatória, colocando o required:
<input type="text" name="nome" placeholder="Nome" required>

Assim, o form não é enviado sem este campo preenchido.

2 - No meu arquivo PHP que recebe o valor, faço da seguinte maneira:
$nome = $_POST['nome'] ? $_POST['nome'] : NULL;

Uso uma condicional ternária. Se meu arquivo PHP estiver recebendo o campo nome, atribui o valor para a variável, se não receber, atribui NULL.

Você também pode usar o isset do PHP. Que verifica se a variável foi iniciada:
$nome = isset($_POST['nome']) ? $_POST['nome'] : NULL;


Solve $\ell=\lim _{x \rightarrow \frac{\pi}{2}} \frac{(1-\sin x)\left(1-\sin ^{2} x\right) \ldots\left(1-\sin ^{n} x\right)}{\cos ^{2 n} x}$

Question: $\ell=\lim _{x \rightarrow \frac{\pi}{2}} \frac{(1-\sin x)\left(1-\sin ^{2} x\right) \ldots\left(1-\sin ^{n} x\right)}{\cos ^{2 n} x}$
I have tried pinning it between $ \frac{(1-\sin x)^n}{\cos ^{2 n} x}$ and $ \frac{(1-\sin^nx)^n}{\cos ^{2 n} x}$ but the limits differed. Tried substituting ${x}$ for ${y}={x}-\pi/2$, no results. The derivative seems too complicated to use L'Hopital, so I'm out of ideas.
Comment: I would factor the numerator using $A^n - B^n = (A-B)(A^{n-1} + A^{n-2}B + \cdots +AB^{n-2} + B^{n-1})$
Answer: We take the limit $\lim\limits_{x \to \frac{\pi}{2}} \frac{1 - \sin^n{x}}{\cos^2{x}}$. We can evaluate this by $\lim\limits_{x \to \frac{\pi}{2}} \frac{1 - \sin^n{x}}{\cos^2{x}} = \lim\limits_{x \to \frac{\pi}{2}} \frac{1 - \sin^n{x}}{1 - \sin^2{x}} = \lim\limits_{u \to 1} \frac{1 - u^n}{1 - u^2}$, which we evaluate to $\frac{n}{2}$ by L'Hopital's rule.
So $\lim\limits_{x \to \frac{\pi}{2}} \frac{(1 - \sin{x}) \cdot ... \cdot (1 - \sin^n{x})}{\cos^{2n}{x}} = \lim\limits_{x \to \frac{\pi}{2}} \prod\limits_{j = 1}^n \frac{1 - \sin^j{x}}{\cos^2 {x}} = \prod\limits_{j = 1}^n \lim\limits_{x \to \frac{\pi}{2}} \frac{1 - \sin^j{x}}{\cos^2 {x}} =
\prod\limits_{j = 1}^n \frac{j}{2} = \frac{\prod\limits_{j = 1}^n j}{\prod\limits_{j = 1}^n 2} = \frac{n!}{2^n}$.


Erro NullPointerException, onde está o erro?

Question: Eu queria saber onde está o erro. Eu li que o erro NullPointerException é quando tentamos acessar uma variavél que não foi inicializada, só não achei esse erro no meu código.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public  class NovoJFrame extends javax.swing.JFrame {

     PreparedStatement stl;
     ResultSet rs;
     Connection con;

    public NovoJFrame() {
        initComponents();

        IniciarBD();

        this.PrencherComboBox();

        jPanel3.setVisible(false);
    }

    public void PrencherComboBox(){
        String sql = "Select * from ALUNO";
        try {

               stl = con.prepareStatement(sql);
               rs = stl.executeQuery();

               while(rs.next()){
                   jComboBox1.addItem(rs.getString("NOME"));
               }
           } catch(SQLException ex){
               JOptionPane.showMessageDialog(null,ex);
           }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox<>();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(java.awt.Color.blue);

        jPanel1.setBackground(new java.awt.Color(0, 51, 255));
        jPanel1.setForeground(new java.awt.Color(204, 255, 51));

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/liceu terras.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(265, 265, 265)
                .addComponent(jLabel6)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(33, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addGap(31, 31, 31))
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 0));

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton1.setText("Visualizar Tempo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/med grande.png"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel7)
                .addGap(40, 40, 40)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(100, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(61, 61, 61))
        );

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Aluno:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setText("Quantidade:");

        jComboBox2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton2.setText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 255, 0));
        jLabel5.setText("Com Sucesso");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(0, 255, 0));
        jLabel4.setText("Operação Realizada");

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simbolo dinheiro.png"))); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(115, 115, 115))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(51, 51, 51))))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addContainerGap(30, Short.MAX_VALUE))
        );

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton3.setText("Status");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(116, 116, 116))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3))
                        .addGap(32, 32, 32)))
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        jPanel3.setVisible(true);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        med frame = new med();

        frame.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

            java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NovoJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JComboBox<String> jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration

    private void IniciarBD(){

        try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
    } catch ( ClassNotFoundException e){
            System.out.println("Erro :" + e.getMessage() );
    }

    String url = "jdbc:derby://localhost:1527/bd" ;
    String user = "root" ;
    String pass = "senha" ;

        try {
            Connection con = DriverManager.getConnection( url, user, pass );

            Statement stmt = con.createStatement();

            System.out.println("Conexão Realizada com Sucesso");
        } catch (SQLException e) {
            System.out.println("Erro :" + e.getMessage() );
        }

}
}

StackTrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NovoJFrame.PrencherComboBox(NovoJFrame.java:43)
at NovoJFrame.<init>(NovoJFrame.java:33)
at NovoJFrame$3.run(NovoJFrame.java:280)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Comment: Nem tem como reproduzir o problema com esse código que postou. Então, em que linha é apontada a exceção?
Comment: Exato. É necessário informar o stack trace da exceção, com a linha onde ocorre o erro. À primeira vista, a exceção pode estar ocorrendo por conta das variáveis "con", "jPanel3" ou "jComboBox1", que não temos certeza se foram inicializadas. Outra coisa, seu SQL está com o "*" colado no "from", dê um espaço no meio deles.
Comment: "*li que o erro `NullPointerException` é quando tentamos acessar uma variavél que não foi inicializada*" - Não exatamente, veja mais [nesta minha resposta](http://pt.stackoverflow.com/a/63736/132). Além disso, o seu código está incompleto e não tem o stacktrace, e por causa disso faltam informações essenciais na sua pergunta para que alguém possa dar alguma resposta satisfatória a ela. Peço-lhe que edite a pergunta acrescentando o stacktrace e o resto do seu código, inclusive os métodos `initComponents()`, `IniciarBD()` e `PreencherComboBox()`.
Comment: Qual é a linha 43?
Comment: @VictorStafusa Pronto, mudei
Comment: @GuilhermeNascimento     stl = con.prepareStatement(sql);
Comment: tem como postar o NovoJFrame.java inteiro, incluindo os imports?
Answer: O seu principal problema é que no método PreencherComboBox, você não inicializa a conexão.
A solução mais simples seria fazer isso:
    public void PrencherComboBox(){
        String sql = "Select * from ALUNO";
        try {
               con = DriverManager.getConnection(url, user, pass);
               stl = con.prepareStatement(sql);
               rs = stl.executeQuery();

               while(rs.next()){
                   jComboBox1.addItem(rs.getString("NOME"));
               }
           } catch(SQLException ex){
               JOptionPane.showMessageDialog(null,ex);
           }

    }

Entretanto, já que estamos aqui, podemos analisar quais outros problemas temos no seu código. E há vários deles:

Você esqueceu o modificador private em alguns atributos da classe. A visibilidade de pacote provavelmente não é o que você quer.
Você abre conexões, Statements e ResultSets mas não os fecha adequadamente. Isso é uma má prática que pode levar a desperdício no consumo de memória ou na manutenção de conexões abertas que já não são mais úteis. A forma mais prática de lidar com esse problema é usando a sintaxe do try denominada try-with-resources.
Você mistura lógica de visualização (swing) com lógica de acesso aos dados (JDBC). Para que o código fique organizado, é melhor separá-las.
Você não está seguindo corretamente as convenções de nomenclatura da linguagem Java. Métodos devem ter o seu nome iniciados com letra minúscula.

Vamos então resolver esses problemas todos:
public class AcessoDados {
    private final String url = "jdbc:derby://localhost:1527/bd";
    private final String user = "root";
    private final String pass = "senha";

    static {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Erro :" + e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }

    public AcessoDados() {
        this.url = "jdbc:derby://localhost:1527/bd";
        this.user = "root";
        this.pass = "senha";
    }

    public AcessoDados(String url, String user, String pass) {
        this.url = url;
        this.user = user;
        this.pass = pass;
    }

    private Connection conectar() {
        return DriverManager.getConnection(url, user, pass);
    }

    public List<String> listarNomesDeAlunos() throws SQLException {
        List<String> lista = new ArrayList<>(10);

        String sql = "SELECT nome FROM ALUNO";
        try (
            Connection con = conectar();
            PreparedStatement stl = con.prepareStatement(sql);
            ResultSet rs = stl.executeQuery();
        ) {
           while (rs.next()) {
               lista.addItem(rs.getString("NOME"));
           }
        }
        return lista;
    }

    public void testarConexao() throws SQLException {
        try (
            Connection con = conectar();
            Statement stmt = con.createStatement();
        ) {
            System.out.println("Conexão Realizada com Sucesso");
        }
    }
}

public class NovoJFrame extends javax.swing.JFrame {

    private final AcessoDados acesso = new AcessoDados();

    public NovoJFrame() {
        initComponents();
        jPanel3.setVisible(false);

        try {
            acesso.testarConexao();
        } catch (SQLException e) {
            System.out.println("Erro :" + e.getMessage());
        }

        this.prencherComboBox();
    }

    public void prencherComboBox() {
        List<String> nomes;
        try {
            nomes = acesso.listarNomesDeAlunos();
       } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, ex);
       }

        for (String nome : nomes) {
            jComboBox1.addItem(nome);
        }
    }

    // ... Resto da classe...
}

Ainda há mais um sério problema que você deve resolver. Você está manipulando o banco de dados na mesma thread do swing. Isso pode deixar a aplicação não-responsiva. O motivo é que o banco de dados pode demorar um pouco para fazer a requisição, e durante esse período, a sua tela ficará congelada. Para resolver isso, procure utilizar a classe SwingWorker de forma a não deixar o swing travar por estar fazendo operações no banco de dados.
Entretanto, para propor uma solução a isso usando o SwingWorker, seria necessário mudar muita coisa na estrutura da sua aplicação, muito mais do que apenas o trecho do que você postou na pergunta. Além disso, esse assunto já é uma outra conversa bem longe do propósito inicial do que está delineado na pergunta. Caso tenha interesse, sugiro que faça uma nova pergunta acerca deste tópico.
Comment: `Class.forName("org.apache.derby.jdbc.ClientDriver");` essa chamada é opcional se ele estiver usando jdk 7+.
Comment: Como complemento a resposta do Victor, [aqui](http://pt.stackoverflow.com/a/130504/28595) tem um exemplo do uso do swingworker com uma barra de progresso. Claro que você precisará adaptar o doInBackground e o publish para sua necessidade.
Comment: @diegofm Sim, mas considerei três coisas: (1) isso já estava no código original do OP; (2) é inofensivo no caso de a aplicação não ter problemas com o classpath e denuncia eventuais problemas se houverem e (3) eu respondi uma pergunta aqui há uns dias atrás onde o OP tinha conseguido bagunçar com isso ao usar um driver antigo no classpath. Assim sendo, acho melhor deixar. Caso o autor da pergunta quiser, ele poder retirar o bloco `static { ... }` e deverá/deveria funcionar do mesmo jeito.
Comment: É verdade, agora que reparei que no código já estava assim.
Answer: Connection con = null;

stl = con.prepareStatement(sql); // con = null

caso IniciarBD() esteja inicializando a variável con, então:
rs = stl.executeQuery();
jComboBox1.addItem(rs.getString("NOME"));

Se a execução da query falhar, rs = null.
Comment: Amigo, não fui eu quem negativou a sua resposta, mas confesso que não entendi exatamente o que você está propondo que o autor da pergunta faça.


Performing searches on JSON data in Elasticsearch

Question: I have mapped JSON data into Elasticsearch via Logstash which has worked, it has imported the data in and I can see it in Elasticsearch-Head.
My problem is querying the data. I can run a search for a field but it returns the entire type within the index as a single search result. I have tried a few variations but have not had any luck.
Here is the logstash shipper file:
input {
   exec {
     type => "recom_db"
     command => "curl -s -X GET http://www.test.com/api/edselastic/recom_db.json"
     interval => 86400
     codec => "json"
   }
   exec {
     type => "recom_ki"
     command => "curl -s -X GET http://www.test.com/api/edselastic/recom_ki.json"
     interval => 86400
     codec => "json"
   }
   exec {
     type => "recom_un"
     command => "curl -s -X GET http://www.test.com/api/edselastic/recom_un.json"
     interval => 86400
     codec => "json"
   }
}
output {
        elasticsearch {
                host => localhost
                index => "lib-recommender-%{+yyyy.MM.dd}"
                template_name => "recommender-template"
        }
}

and the Elasticsearch index is in the following form:
{
    "_index": "lib-recommender-2015.06.11",
    "_type": "recom_un",
    "_id": "qoZE4aF-SkS--tq_8MhH4A",
    "_version": 1,
    "_score": 1,
    "_source": {
        "item": [{
            "name": "AAM219 -- reading lists",
            "link": "http://www.test.com/modules/aam219.html",
            "description": "AAM219 -- reading lists",
            "terms": {
                "term": ["AAM219"]
            }
        },
        {
            "name": "AAR410 -- reading lists",
            "link": "http://www.test.com/modules/aar410.html",
            "description": "AAR410 -- reading lists",
            "terms": {
                "term": ["AAR410"]
            }
        }
        ...

Anyway so I have tried querying the data the various ways I have seen in the Elasticsearch documentation but am unable to a desired result. Here is one of the many queries I have tried:
curl -XPOST "http://localhost:9200/lib-recommender/recom_un/_search" -d'
{
    "fields": ["item.name", "item.link"],
    "query":{
        "term": {
                "item.terms.term": "AAM219"
                        }
                }
        }
}'

but it returns the entire type within the index (with the correct fields selected but disjointed and all of them):
{
    "took": 13,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.006780553,
        "hits": [{
            "_index": "lib-recommender-2015.06.11",
            "_type": "recom_un",
            "_id": "qoZE4aF-SkS--tq_8MhH4A",
            "_score": 0.006780553,
            "fields": {
                "item.link": ["http://www.test.com/modules/aam219.html",
                "http://www.test.com/modules/aar410.html",
                "http://www.test.com/modules/ac1201.html",
                "http://www.test.com/modules/aca401.html",

I am after the following result:
{
    "took": 5,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.006780553,
        "hits": [{
            "_index": "lib-recommender-2015.06.11",
            "_type": "recom_un",
            "_id": "qoZE4aF-SkS--tq_8MhH4A",
            "_score": 0.006780553,
            "_source": {
                "item": [{
                    "name": "AAM219 -- reading lists",
                    "link": "http://www.test.com/modules/aam219.html",
                    "description": "AAM219 -- reading lists",
                    "terms": {
                        "term": ["AAM219"]
                    }
                }
            }
        }
    }
}

What am I missing? Is the mapping of the index wrong for this kind of search (so should I manually make a mapping file for elasticsearch before importing data). Is there a parameter I am missing in the query? I have been looking for an answer but feel like I am running around in circles now, I am guessing it is something simple that I am overlooking but not sure.
Answer: Yes, for this kind of use case to work you need to create a custom mapping and make sure your item structure is of type nested otherwise all the fields in your item will be collapsed together as you saw in the results you showed.
So the mapping needs to be like this:
{
  "recom_un": {
    "properties": {
      "item": {
        "type": "nested",
        "properties": {
          "name": {
            "type": "string"
          },
          "link": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "terms": {
            "properties": {
              "term": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}

Then you can modify your query a bit to use a nested query instead like this. Also note I'm including the inner_hits so your results only include the matching nested document:
curl -XPOST "http://localhost:9200/lib-recommender/recom_un/_search" -d'
{
  "fields": [
    "item.name",
    "item.link"
  ],
  "query": {
    "nested": {
      "path": "item",
      "query": {
        "term": {
          "item.terms.term": "AAM219"
        }
      },
      "inner_hits": {}
    }
  }
}'

Comment: Is `item` the only property of your document or are there others? In the former case, why not simply indexing each single item as a standalone document so you could get rid of the nested type altogether?
Comment: I have tried that but am now getting no results. I have double checked the mapping and template and the "item" objects now have the "type": "nested" parameter. Is there anything else I can try or could I have a configuration issue perhaps?
Comment: Yes you are right about indexing of `item`, it will be the only property. I wanted to do a nested search without changing the data much as I will have to search nested data anyway (`item.terms.term for example`). For the record your answer above is correct but i needed to change the `"term"` to `"match"`. Your way would work if I had the index for the field set to `"not_analyzed"`.
Comment: Actually I needed to set the nested type for `terms` also. I will post the full solution I have below to help guide other people who have the same issue in future. Thanks Val for pointing me in the right direction.
Answer: Props to Val's answer above. It was mostly what but with another level of nesting.
Here is the mapping:
{
  "recom_un": {
    "properties": {
      "item": {
        "type": "nested",
        "properties": {
          "name": {
            "type": "string"
          },
          "link": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "terms": {
            "type": "nested",
            "properties": {
              "term": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}

The search query I used to get what I wanted:
curl -XPOST "http://localhost:9200/lib-recommender/recom_un/_search" -d'
{
  "_source": false,
  "query": {
    "filtered": {
      "filter": {
        "nested": {
          "path": "item",
          "query": {
            "nested": {
              "path": "item.terms",
              "query": {
                "match": {
                  "term": "AAM219"
                }
              }
            }
          },
          "inner_hits": { }
        }
      }
    }
  }
}'


Portal authorization to other portal's Dashboard

Question: There is a portal that a company's users are familiar with, and we will put a link to login to a different portal on a different machine. This process would not require username/password check, just hitting the link will log them in.
How can this two delivered in secured way? We don't want that anyone with the link to be able to log in, how can we make this to work between the two platforms?
Comment: So, user has already logged in, inside main site. You want that login information carry on, onto another site server, when its clicked, so new server will know, that this is authorised user?
Answer: I'm presuming the two portals aren't able to share sessions/cookies.  If they are you can just use those to keep track of who is logged in where.
In the situation where that's not possible, you could use an authentication API, which you could query to see if a given user_id is logged in on that portal.  This could be a very simple API which returns a yes or no, or you could develop it to be more complex.
Additionally keep in mind that there are Open Source choices out there.  Open ID is a system that stackoverflow uses, for example.
Answer: Easiest method would be script on main site, that waits for session ID in POST/GET input, if session exists, it outputs user name. The new site server, when user comes in, reads in cookie with session ID, sends a request to main site server script and asks if session ID exists, if exists, uses that user name, for new site server.


What's the rails way to include a field in a join model when listing an association?

Question: So if I have the following relationship
class Item < ActiveRecord::Base
   has_many :item_user_relationships
   has_many :users, :through => :item_user_relationships
end

class User < ActiveRecord::Base
   has_many :item_user_relationships
   has_many :items, :through => :item_user_relationships
end

class ItemUserRelationship < ActiveRecord::Base
   belongs_to :item
   belongs_to :user

   attr_accessible :role
end

What's the rails way to include the role attribute when listing all the Users of an Item?
@users = @item.users # I want to include the role as part of a user

Thanks!
UPDATE: I'm still having trouble with this. My goal is to get an array of User models that have their role included in the attributes.
Comment: What I ended up doing was `@users = @item.users.all(:joins => :item_user_relationships, :select => "users.*, item_user_relationships.role")`
Answer: I'm note sure if I understand you correctly, but maybe this is what you want?
@users = @item.users
@users.each do |user|
  puts user.item_user_relationships.first.role
end


Não consigo fazer um elemento ter um wrap em um layout responsivo

Question: Boa tarde, estou tentando tornar um layout responsivo mas não consigo fazer a descrição do produto ir para debaixo da imagem quando o espaço disponível for pequeno demais. Já tentei com display:flex e com float mas nenhum funcionou.
Segue o link da página em questão:
http://www.hominumstore.com.br/pd-489292-direito.html?ct=&p=1&s=1
Comment: Você precisa demonstrar o problema na própria pergunta (favor [edit]), em vez de postar esses links. Veja [Posso mostrar só um link pro meu site com problemas?](http://meta.pt.stackoverflow.com/q/1913/74) e as [dicas sobre exemplo mínimo](/help/mcve). Obrigado.
Answer: Você precisa usar uma media querie para controlar a tela, segue exemplo:
<code>@media screen and (max-width:992px) {
     //controlar as classes
     .logo {
         font-size: 20px;
     }
}
</code>
Nas imagens use max-width: 100%;


Loading properties from JSON, getting "message sent to deallocated instance"

Question: So I load my custom object from a web service and am trying to store the properties as NSStrings but keep running into this error:
-[CFString _cfTypeID]: message sent to deallocated instance 0x100d3d40
-[CFString retain]: message sent to deallocated instance 0x100d3d40

I enabled zombies, but that's not really showing me a solution.
My properties are defined as:
@property (strong, nonatomic) NSString *title;
@property (assign, nonatomic) NSString *ID;
@property (strong, nonatomic) NSString *redLabel;
@property (strong, nonatomic) NSString *greenLabel;

Then I create an instance of my object and call the webservice
QuickList *list = [[QuickList alloc] init];
[list loadLatestQuickList];

And finally, inside loadLatestQuickList...
NSURLRequest *request = // create a GET request...
[NSURLConnection sendAsynchronousRequest:request queue:notMainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
    NSError *parsingError;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parsingError];
    if (!parsingError && [json isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dataDictionary = [json objectForKey:@"data"];
        NSDictionary *quickListDictionary = [dataDictionary objectForKey:@"QuickList"];

        NSString *ID = [quickListDictionary objectForKey:@"id"];
        NSString *title = [quickListDictionary objectForKey:@"name"];
        NSString *redLabel = [quickListDictionary objectForKey:@"red_label"];
        NSString *greenLabel = [quickListDictionary objectForKey:@"green_label"];

        self.ID = ID;
        self.title = title;
        self.redLabel = redLabel;
        self.greenLabel = greenLabel;

        // tell a channel that everything is loaded
    }
    else {
        NSLog(@"%@",parsingError);
    }
}];

Now whenever I try to access list.ID or some other property I get the "deallocated instance" error. Any thoughts as to why I'm getting this error?
Answer: Your ID property should be strong as well.


Panels page variant that targets a single node

Question: I am a little new to Panels, but I am using it to manage layouts for different content types and it is working out really well. However I want to be able to create a page variant that will only target a single node. Is there any way to do this based on the node's id?
Answer: Assuming you already have the node override Panel enabled:

Edit the panel page for the node override (node_view for node/%node)
Make a new variant, enable selection rules
For the selection rule, choose String: Url Path
In the criteria, keep Allow access on the following pages selected
In the textarea, add the internal node paths for this nid(s) you want.  To target nid 1234, use
node/1234
Configure the test of the panel as needed.

Just make sure this comes before any less-specific rules, like matches on content type.
Comment: Bah! How could I not have thought of that? +1
Comment: @Letharion I had to double check this on a few sites.  I haven't done this in a while, and was a little baffled that there isn't a node selection plugin that just lets you pick a node or enter a nid directly.
Comment: Please, check out another solution: http://stackoverflow.com/questions/2356356/drupal-panels-use-variants-according-to-nid
Answer: What you probably want to do is use Panelizer.
Page manager itself can do it to, but I don't see a builtin rule to match on node ids. Copying an existing rule, such as ctools/access/node_language.inc would probably be the best way to solve that. See What are Ctools plugin (content type, access, etc), and how does one create them? for more details.


Guide to Art of the Fugue?

Question: I'm looking for a thorough, perhaps measure-by-measure, analysis of Bach's Art of the Fugue (Die Kunst der Fuge, BWV 1080). Is there a book, journal article, thesis, or dissertation which does this?
Comment: Ah. Bach lacked excellence? I'm curious about those developments since, especially in opera. I'm fairly familiar with contrapuntal writing up to, say, Dallapiccola. I would have said that there was very little new in contrapuntal technique, and none of it any better handled than in Bach (although not necessarily handled worse), but I can stand to learn something new.
Comment: @Ricky It's **considerably** more than one fugue...
Comment: Just for information: Apparently Douglas Hofstadter's book "Gödel, Escher, Bach"... has a lot to say about this piece. But it's not a conventional analysis as such, and goes into many other things apparently unconnected with music...
Comment: http://store.doverpublications.com/048649764x.html, maybe.
Comment: What's to analyze? It's a fugue.
Comment: @Andy: Okay, it's a bunch of fugues. It's still just an exercise in contrapuntal composition. There's been some major developments in that area since then, especially in opera. Precedence isn't the same as excellence.
Answer: Laurence Dreyfus, Bach and the Patterns of Invention (Cambridge, MA: Harvard University Press, 1996)
David Yearsley, Bach and the Meanings of Counterpoint (Cambridge: Cambridge University Press, 2010)
Peter Schleuning, Johann Sebastian Bachs Kunst der Fuge: Ideologie, Entstehung, Analyse (Munich: DTV, 1993)
Heinrich Adel, Bach's Die Kunst der Fuge: a living compendium of fugal procedures, with a motivic analysis of all the fugues (Lanham, MD: University Press of America, 1993)
Göncz, Zoltán; Laki, Péter; Mészáros, Erzsébet, Bach's testament: On the philosophical and theological background of The art of fugue (Lanham, MD: Scarecrow Press, 2013)
For hundreds more citations, visit http://www.rilm.org, the international catalog of literature about music.
Comment: And don't forget Donald Tovey's Companion - he was very shrewd about how the counterpoint worked.
Answer: if you are looking for something you can source, maybe https://www.ocf.berkeley.edu/~repercus/wp-content/uploads/2011/08/repercussions-Vol.-9-No.-1-Markham-Michael-The-Usefulness-of-Such-Artworks.pdf
a website that might be informative, http://www.flagmusic.com/aof.php?r=aof_c_ii

Guide to Art of the Fugue?


Join para 2 tabelas

Question: Como faço para usar o metodo Join para dar um include de um valor de outra tabela? Neste caso eu ia usar a tabela ChamadaMusicas e a tabela MusicaVotadas
var chamadaMusicas = db.ChamadaMusicas
                       .Include(c => c.Chamada)
                       .Include(c => c.Musica)
                       .Where(c => c.Chamada.PessoaID.Equals(id)).Where(i => i.Chamada.Ativa.Equals(true))
                       .Join(db.MusicaVotadas)
                       .ToList();

Comment: Qual é o problema?
Comment: Esse join não funciona. Da um erro quando eu uso esse join. Então devo estar usando de maneira errada.
Comment: Posta o erro. Um desenho mostrando o relacionamento entre as classes irá ajudar no entendimento do problema.
Answer: No caso o seu join está escrito de forma errada.
Segue abaixo como seria +- a forma correta, a depender de como estão suas entidades:
var chamadaMusicas = db.ChamadaMusicas
   .Include(c => c.Chamada)
   .Include(c => c.Musica)
   .Where(c => c.Chamada.PessoaID.Equals(id)).Where(i => i.Chamada.Ativa.Equals(true))
   .Join(db.MusicaVotadas,
        ChamadaMusicas => ID, //Informa a PK (primeira parte da clausula on do sql)
        MusicaVotadas => ChamadaMusicasID //Informa a FK(segunda parte da clausula on do sql)
        (ChamadaMusicas, MusicaVotadas) = > new {ChamadaMusicas = ChamadaMusicas, MusicaVotadas = MusicaVotadas}// novo objeto formado pelo join
   ).ToList();

Segue também um link explicando como funciona o join
http://theburningmonk.com/2010/02/linq-lambda-expression-vs-query-expression/

Join para 2 tabelas


Listening, mixing, and understanding on multiple playback devices?

Question: A common question that people ask me when I begin mixing their music (I mainly deal with drumsets), is something like, "Where will you mix my music? Will you use more than one device to listen?"
Now, assuming that there are good machines and sound devices, and infinite possibilities, "How important is it for a good mix to use multiple devices for listening? Which one do you suggest to be mandatory?"
The question, although becomes slightly different, can also be expressed in non-mixing terms: "Is it important to hear music from different sources to understand it?"
Comment: Are you asking about studio monitors? Headphones?
Comment: Both, actually. Even car speakers, and other types of sources
Comment: I've found that it can be very easy to get lazy with your levels when listening on studio monitors or headphones. Things that seem audible enough/not too loud can be revealed as very wrong on worse speakers. That's not to say you should mix in your car, but it's worthwhile to check for compatibility and see if it reveals issues.
Answer: You should at least use (good) headphones and a standard stereo arrangement (speakers with several meters distance apart, and the listener at a similar distance from their middle).  Be sure to use suitable speakers: live monitors tend to cut out a whole lot of bass since its direction can't be focused away from the audience and would interfere with the PA.
The listening experience of headphones and stereo speakers is quite different.  You don't get an "inside head location" problem with stereo speakers.  Mix intransparency is less of a problem with headphones.
Of course, with enough experience you know how to distribute instrument microphones for the basic panning work (most relevant for the speaker mix) and a stereo pair for the ambient capture (relevant for the headphones) and what delays to employ to blend their effects well.
Once you got your basic procedures pat, you'll be able to do most of your work with just headphones, and the speaker mix will end up fine.
I am not convinced one also needs a "sucky smartphone mix" but there obviously is a sizable market for that as well by now.  When working with your DAW on a laptop, the builtin speakers might be a good approximation.
Answer: I think it's most important to get really familiar with the sound of good music on whatever devices you do the bulk of your mixing work. Make sure to know, or find out, what sonic weaknesses each one has, and use other devices to fill in the gaps to check your mix and fix those areas. If the end product will be used in a specific listening environment, it might be a good idea to check your mixes in an environment as close to that as you can reasonably replicate.
If you mix mostly on headphones, check out Inner Fidelity's headphone measurements to see a graph of the frequency response for the make/model of headphones you have -- this will help identify potential problem areas.
There are also plugins out there designed to cancel the frequency response curve of various models of headphones, so that what you end up hearing is completely flat. (Once you have the frequency response graph, you can try doing this manually with an EQ as well.) I haven't tried any of these solutions, but some people swear by them. My biggest issue with this type of system is that music you listen to normally (without the plugin) would sound different, and so you wouldn't really "learn your headphones." There are advantages and disadvantages.
I think learning a good pair of headphones is mandatory. Headphones remove almost all the variables associated with the (usually poor) sonic characteristics of the room in which you're working, and also gives you a consistent sound no matter where you are. What if you like to travel and have to do work on the road? What if you move to a different house/apartment? It's basically impossible to take the sound of a room along with you.
For checking mixes on small speakers, I've found that a good substitute is to put a high-pass filter on the master fader at around 115 Hz (add this to your mixing template so it's right there to be turned on/off when needed), and then listen to make sure elements such as the kick drum and bass can still be heard from only their mid and high frequency content.
Answer: An experienced mixer can use studio monitors in a well-treated room to make mixes that sound good on anything from a hi-fi to an iPod.  (Maybe an alternative mix for tracks destined to be pushed through a bass-heavy club system.)    He got to BE experienced by checking his work on anything and everything from a boom-box to a car radio to a domestic hi-fi.  A good trick is to listen from the room NEXT to your studio with the door half-closed - a too-heavy or too-light bass balance can be very apparent.
And even the most experienced mixer still runs their work in the car now and again, just to keep 'tuned in'.
But you know all this already, as a mixer for hire!