Why does this naive prime-number algorithm fail?

Question: I am attempting to implement this "find the nth prime number" algorithm in Ruby 2.1.
I've tagged it 'algorithm' as well because I think the question is language-agnostic, and that the Ruby code written is simple enough to read even if you're unfamiliar. I've used descriptive variable names to help it.

Iterate over the whole number system, ignoring even numbers greater than 2 (2, 3, 5, 7, …)
For each integer, p, check if p is prime:

Iterate over the primes already found which are less than the square-root of p
For each prime in this set, f, check to see if it is a factor of p:
i. If f divides p then p is non-prime. Continue from 2 for the next p.
If no factors are found, p is prime. Continue to 3.

If p is not the nth prime we have found, add it to the list of primes. Continue from 2 for the next p.
Otherwise, p is the nth prime we have found and we should return it.

Sounds simple enough. So I write my method (function):
    def nth_prime(n)
        primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

        primes[-1].upto(Float::INFINITY) do |p|
            return primes[n-1] if primes.length >= n-1
            possible_prime = true
            primes_to_check = primes.select{|x|x<=Math.sqrt(p)}
            primes_to_check.each do |f|
                if f%p==0
                    possible_prime = false
                    break
                end
            end
            primes << p if possible_prime
        end
    end

The intent is to say nth_prime(10) and get the 10th prime number.
To explain my logic:
I start with a list of known primes, since the algorithm requires that. I list the first ten.
Then I iterate over the entire number system. (primes[-1]+2).upto(Float::Infinity) do |p| will offer each number up from the last known prime plus two (since +1 will result in an even number and evens over 2 cannot be prime) to infinity to the indented block as p. I have not skipped even numbers and have
The first thing I do is return the nth prime number if the list of known primes is already at least n elements long. This works for the known values -- if you ask for the 5th, you'll get 11 as a result.
Then I set a flag, possible_prime, to true. This indicates that nothing has proved it to be not a prime yet. I'm going to do some tests and if it survives those without the flag being changed to false, then p is proven to be prime and is appended to the known-primes array. Eventually that array will be as long as n and return the nth value.
I create an array, primes_to_check, containing all known primes <= the square root of p. Each one gets tested in turn as f.
If f can cleanly divide p, I know that p is not prime, so I change the flag to false, and break, which brings us out of the primes-to-check loop and back in the upto-infinity loop. There's only one statement left in that loop, the one that appends to the known-primes array if the flag is true, which it isn't so we restart the loop with the next number.
If no fs can cleanly divide p then p must be prime, which means it survives to the end of the primes-to-check loop with the flag still set to true, and reaches the final 'append p to known primes' statement.
Eventually this will make the primes array sufficiently longer to answer the question "What is the nth prime?".
Problem
Asking for the 10th prime does get me 29, the last prime I pre-supplied. But asking for 11 gets nil, or no value. I've gone over the code a hundred times and can't imagine a case in which no value gets returned.
What have I done wrong?
Answer: return primes[n-1] if primes.length >= n-1

For primes to have an element at index n-1, it must have length at least n.
if f%p==0

This checks whether a known prime is divisible by the candidate, not whether the candidate is divisible by a known prime.
primes[-1].upto(Float::INFINITY) do |p|

This starts the loop at a prime already in the list (29). 29 is correctly found to be prime, so it is added to the list again. You'll want to start the loop at a number after 29.
Comment: Hmm. Good catch, I think I was thinking zero-indexed or something there. But changing it to `n` rather than `n-1` introduces a new bug: the 11th prime returns the 10th, and and every additional number just returns the next integer in line, not the next prime.
Comment: @GreenTriangle: Found some more bugs. If there are still more, try to find them yourself before asking again.
Answer: Algorithm for testing prime no.s:
1)Input num
2)counter= n-1
3)repeat
4)remainder = num%counter
5)if rem=0 then
6)broadcast not a prime.no and stop
7)change counter by -1
8)until counter = 1
9)say its a prime and stop

Comment: How does this answer `What have I done wrong?`? Does this `find the nth prime number`? Is it as efficient as, say, starting from 2 and going upwards?
Comment: Yes when you enter a number, it tells you whether it is a prime or not.
Comment: The nth prime number is something else: if you enter 5, you shouldn't answer true (or false), 2, 3, 5, 7, or 9, but `11`, as it is the fifth prime number. (Anyway, GreenTriangle's question still reads `What have I done wrong?`)


Slide div from x,y to x,y?

Question: When someone click on my fields on my virtual game, i get my current left and top cordinates with this:
 function moveDiv(fromSeat, toSeat){
    var fromTop  = $('#seat-' + fromSeat).css("top");
    var fromLeft = $('#seat-' + fromSeat).css("left");

    var toTop  = $('#seat-' + toSeat).css("top");
    var toLeft = $('#seat-' + toSeat).css("left");

    /** Move a div from point {"fromTop", "fromLeft"} => {"toTop", "topLeft"} **/
  }

I am stuck here, i tried to make a $('...').animate({}); but could not get it working.
I want div "#test" to move from point {"fromTop", "fromLeft"} => {"toTop", "topLeft"}
Comment: You would not need the origin unless there is no origin and you wanted to move to two separate points. Otherwise, `$('#seat-' + fromSeat).animate({ top: toTop, left: toLeft}, duration);` will handle all the calculations for you.
Comment: probably need to add tops together and add lefts and use totals for animation
Answer: You likely need to add the top values and add the left values and do animation using the totals
function moveDiv(fromSeat, toSeat){
    var fromTop  = $('#seat-' + fromSeat).css("top");
    var fromLeft = $('#seat-' + fromSeat).css("left");

    var toTop  = $('#seat-' + toSeat).css("top");
    var toLeft = $('#seat-' + toSeat).css("left");

     var position={ top: fromTop+ toTop, left: fromLeft+toLeft}

     $('#seat-' + fromSeat).animate( position);

  }

EDIT: need to convert values from string containing px to number to add them. Can use parseInt() to do it

Slide div from x,y to x,y?


Is it possible to disable the menu bar for the popup window?

Question: I need the user to choose either choice on the decision box before they go for next page. Right now the problem is if the user click close "X" on popup box, they can proceed for next page without choosing the choice. How can i do validate from here? Any help would be appreciated. Thanks

Javascript Code
var winConfirm = null;

function showConfirm() {
    var windowWidth = 250;
    var windowHeight = 100;
    var locX = (screen.width - 150 - windowWidth) / 2;
    var locY = (screen.height - 50 - windowHeight) / 2;
    var windowFeatures = "width=" + windowWidth + ",height=" + windowHeight + ",screenX=" + locX + ",screenY=" + locY + ",left=" + locX + ",top=" + locY;

    if ((winConfirm != null) && !winConfirm.closed) {
        winConfirm.close();
    }

    winConfirm = open("menubar = no", "winConfirm", windowFeatures);

    var theHTML = '' + '' +
   '' + 'Please choose ?' + '<FORM NAME="buttonForm">

     ' + '<INPUT TYPE="button" NAME="buttonname" VALUE="YES" STYLE="WIDTH:60;HEIGHT:30;FONT-WEIGHT:BOLD;" ONCLICK="self.close();opener.buttonClicked(0);">' + ' ' + '
     <INPUT TYPE="button"  NAME="buttonname" VALUE="NO" STYLE="WIDTH:60;HEIGHT:30;FONT-WEIGHT:BOLD;"  ONCLICK="self.close();opener.buttonClicked(1);">' + '

</FORM>';

    winConfirm.document.writeln(theHTML);
}

function buttonClicked(buttonChoice) {
    var CONTACT_ID = "<%=CONTACT_ID%>";

    switch (buttonChoice) {
        case 0:
            winConfirm.close();
            break;
        case 1:
            popupWindow('/eascb/common/search/pop_contact_update_0.jsp');
            break;
        default:
            popupWindow('pop_covernote_add_0.jsp');
    }
}

Answer: You can't remove the window options, BUT you can create your own pop up box in your page using JavaScript. Just have Javascript generate a DOM with two clickable buttons. Besides, that way you have complete control over the aesthetic as well.
I'm on mobile right now, but I'll write you an example tomorrow morning if no one else beats me to it.
EDIT - Adding example
Instead of having javascript generate them I just used html and css classes, but it should still display what I was trying to get at. If you don't have access to the html or css I could help you write some javascript that does actually generate the DOM.
http://jsfiddle.net/fcpxrkh0/

Click Me!

Please select Yes or No

YES

NO

Comment: Thanks @steely. I'll try the method that you had just mentioned while waiting for your solution.
Comment: There are about a thousand solutions to this problem (simulating a modal in the DOM): http://stackoverflow.com/questions/288867/how-to-code-a-javascript-modal-popup-to-replace-ajax , http://github.hubspot.com/vex/docs/welcome/ , http://bootboxjs.com/ , and so on.
Comment: Edited to add example. Hope it helps!
Comment: @user3835327 , did my answer help? Please select the best answer if you would. ;)
Answer: You can also use confirm to display a native modal popup window, where the user must choose OK or Cancel; How to create a dialog with "yes" and "no" options? .
Comment: native modal popup window only return true or false, which the button shows only "OK" and "CANCEL" instead of  "Yes/ No".hmm..
Answer: check out the fiddle demo. all I did was add a simple flag to hold the status if a button has been clicked, you can modify to your problem accordingly.
the flag name is somethingChosen, it is set to true once button is clicked, else would stay false and keep requesting for window to open.


O que é syntax sugar e como ela funciona?

Question: Tenho visto em alguns blogs o uso do desse termo e gostaria de saber:
1) O real significado dessa expressão e;
2) Como funciona uma syntax sugar como a do exemplo abaixo na linguagem java?
for (Foo foo : listFoo) {
    //CÓDIGO AQUI
}

Comment: Você quer saber o que significa "syntax sugar" ou quer saber como funciona esse exemplo de sugar? Se for os dois, você está fazendo duas perguntas completamente não relacionadas e deveriam ser separadas.
Comment: Então separe em duas perguntas diferentes. Syntax sugar é uma coisa, como o for funciona não tem nenhuma relação e não pode estar na mesma pergunta.
Comment: Mas ainda assim são coisas separadas, não sei porque ter as duas informações em páginas diferentes possa complicar a compreensão. Já a organização do site fica prejudicada com duas perguntas não relacionadas no mesmo lugar.
Comment: As duas coisas. Vou enumerá-las para demonstrar melhor a minha necessidade.
Comment: Perdão, @bigown, mas acredito que uma definição associada a um exemplo venha facilitar a minha compreensão sobre o termo.
Answer: Literalmente, syntax sugar é um tipo de construção feita para "adocicar" o código, ou seja, fazer algo de maneira mais simples.
Considerando o seu exemplo do for-each. Antes do Java 5, da nova construção "adocicada" e da introdução de genéricos na linguagem, eis um código equivalente:
for (Iterator i = listFoo.iterator(); i.hasNext(); ) {
    Foo foo = (Foo) i.next();
    // CÓDIGO AQUI
}

A versão com o for-each é com certeza mais simples e menos suscetível a falhas.

Fontes:

SOE: Which is more efficient, a for-each loop, or an iterator?
Java Language Specification: 14.14.2. The enhanced for statement
Answer:
Em ciência da computação, açúcar sintático é a sintaxe dentro de uma linguagem de programação que foi concebido para tornar as coisas mais fáceis para ler ou expressar. Isso torna a linguagem "mais doce" para uso humano: as coisas podem ser expressas de forma mais clara, de forma mais concisa, ou em um estilo alternativo que alguns podem preferir.

Traduzido de: http://en.wikipedia.org/wiki/Syntactic_sugar
Este for itera sobre todos os elementos de listFoo, colocando a cada iteração o elemento corrente dentro da variável foo.
Comment: Mas é que nem café: tem gente que prefere sem açúcar, e tem gente que usa mais açúcar que café.
Comment: Aí vai da filosofia de cada um. Por um lado, fazer uma coisa de várias maneiras pode complicar. Por outro, melhora o poder de expressão da linguagem.


/arm64/Image to zImage or boot.img

Question: Hello everyone I have been trying to figure out how to make my android kernel a zImage or boot.img.
I tried to figure it out with no luck. I was told that zImage isnt possible for my device because its a arm64 kernel but I thought I would ask again.
if that's the case I'm trying to get the boot.img compiled so I can fastboot it.
This is for the LG v10.
Thanks,
Zach
Comment: Have you tried to create `boot.img` from `Image` file using `mkbootimg` tool?
Comment: Just for the reference: this question is connected to [this](http://stackoverflow.com/questions/35631171/error-while-trying-to-compile-android-kernel-in-ubuntu/35656183?noredirect=1#comment59050834_35656183) question.
Comment: @SamProtsenko thanks I should have added that. I tried the link you gave me but I couldn't get it to work and I tried to do a boot.img and couldn't get it to work either.  Lol this has been difficult :p
Comment: @SamProtsenko yeah i don't know what I'm doing wrong with the mkbooting tool but it keeps not working
Comment: What do you man "not working"? It's not able to produce `boot.img`, or produced `boot.img` won't boot?
Comment: @SamProtsenko it's probably a user error haha I'm going to try again tonight and see if I can't get it.
Comment: @SamProtsenko I can't figure out were to put the mkbooting tool files and when I think I figured out and do the command it work do it I'm going to try again tonight and see if I'm missing something or just completely doing it wrong haha
Comment: Ok. As I see it, first of all you need to figure out where your kernel *should* be flashed for your device. Can you observe partitions table in some way? You should look if you have partition called `boot` on your device. And (desirable) look what is the size of that partition. If it's in place, then create `boot.img` from `Image` file and `ramdisk.img` (from Android your AFS build) using `mkbootimg` tool (there may be some subtle pitfalls, though). Once `boot.img` is created, see if it fits into `boot` partition. If it is, flash it using `fastboot flash boot boot.img` or in any other way.
Comment: Ok i just watched a video of how to view and get the boot.img from the device using adb. But if I make the Image a boot.img and flash with fastboot it would it replace the rest of the boot.img on the device because I just want to flash the kernel. Or would it just put the kernel files into the existing boot.img on my device?
Comment: You can try to use `make bootimage` target for Android sources. See [this](https://source.android.com/source/building-kernels.html#building). It will use `mkbootimg` automatically for known (built) ramdisk and the kernel image you specify.
Comment: `boot.img` consists of kernel image **and** ramdisk. So flashing `boot.img` will replace both kernel and ramdisk. You need to be sure that `boot.img` was generated correctly (correct kernel image, ramdisk and other options). Otherwise you risk to brick your device. I'd recommend you to use `make bootimage` rule in Android sources tree (after building both AFS and kernel).
Comment: Also I guess `boot.img` **may** contain device tree (from kernel build). I'm not sure if you need one in your case, and where it should be put (into `boot.img` or into separate partition). Unfortunately, you don't have clear instructions for your device, so it's always a risk. I advice you to prepare some way to restore things, before you start flashing (very likely you will brick your device on first attempt). And I advice you to figure out the partition table for your device first, to get a clue about DT (device tree) destination.
Comment: Sounds good. Thanks for all the help i jumped into some deep waters haha. I have my whole system backed up so I can just go into recovery and restore everything if it bricks. In sort of confused about the ramdisk and AFS could I just copy those from the boot.img I pull from my device and just through in the Image file?
Comment: Yes, you can unpack your `boot.img`. Just google for `unpack boot.img ubuntu` or something like that, there are a lot of working answers out there.
Comment: Ok sound good I'll see what I can do from there. Yeah it just seems when I try to find working answers I can never find any lol
Comment: The thing is what you really need is working instructions (how to build and flash kernel + Android) for your board. But there isn't. So you have a lot of questions, one triggers another. So you either should ask for instructions on LG open source (or XDA developers forum), or ask someone who have LG v10 to come up with instructions and share it. Or you can figure out those instructions by yourself. All options seem quite painful, but we can't help you because we just don't have LG v10 :)
Comment: Yeah I understand lol. Most devs gave up not the v10 but I'm going to keep pluging away. I figure I'll find out how sooner or later :p. Thanks for the help I'll keep you posted how it goes
Answer: There is no way to do that other than to hack the naming convention inside your kernel.
64 bit arm kernels will be compiled under name of "Image"
32 bit arm kernels will be compiled under name of "zImage"
Comment: @SundeepBorra It's more than just convention. `zImage` is self-extracted archive, and `Image` is just plain not packed kernel image. arm64 kernel doesn't have decompressing capacity, hence result file is `Image`. See linked question for details.
Comment: Thanks for the response! So if I change the 64 bit in the naming convention inside my kernel to zImage it should compile as a zImage? Also where would I find the naming convention in my kernel?
Comment: Thanks to Sam
@Zach, you need to hack through this(Zipping thing) too, as per Sam.
But, doing so many hacks doesn't seem worth the change unless the requirement is so tempting and mandatory. More explanation of your use case would attract better answers.
Why not the Image work for you?

/arm64/Image to zImage or boot.img


Practical Applications of the Fréchet Derivative

Question: I understand the definition of the Fréchet derivative. However, outside of functions on $\mathbb R^n$, I've never encountered an application where it was particularly useful.
Can anyone share examples of (or references to) uses of the Fréchet derivative, especially ones where other methods would not have worked?
Optimisation problems are preferred, but nice applications elsewhere would also be appreciated. As suggested above, I am looking for examples where the domain is not $\mathbb R^n$.

Some Background
For example, on the odd occasion where I've had to find the optimizer of some functional defined on a Banach space, I always try to calculate the Fréchet derivative to see if it would help. I usually end up with a condition on variations that I don't really know how to make use of, and end up resorting to other methods to solve my problem.
It doesn't help that the references I turn to almost exclusively only have examples of the use of the Fréchet derivative on finite-dimensional spaces. If not, then they were actually optimising over a space of appropriately smooth functions, so Euler-Lagrange would have done the trick.
I suppose this is just a lack of education on my part, but I do think it's noteworthy that the Wikipedia article I link to above only features examples in the form of calculating the derivative of specific functions. It says very little about why I might want to calculate it, aside from passing references in the introduction, or, how, once I've calculated it, I might be able to make use of it.
Comment: Weird comment but maybe appropriate, but I only truly understood the Jacobian in terms of normed spaces. And this naturally comes from Fréchet differentiability. This in turn motivates the notion of Banach bundles, which is used in PDE theory for say evolution equations. But this is not the greatest application.
Comment: Frechet is just differential calculus for vector spaces (Banach spaces) where traditional derivative makes no sense: you can't take quotients in VS. Everything in physics can be described nicely and has "support"
Answer: The books Introduction to Mechanics and Symmetry and Manifolds, Tensor Analysis and Applications discuss some applications to physics of the Fréchet derivative outsise $\mathbb{R}^{n}$. The latter uses Fréchet derivatives in the context of Classical Field theory and variational problems. The former uses some of these concepts in classical mechanics.


Why does DTD error "White spaces are required between publicId and systemI" occur with Spring XSD

Question: In my application context file Eclipse shows the error:
Referenced file contains errors (http://www.springframework.org/schema/integration). applicationContext.xml     line 1  XML Problem
looking at the error detail in Eclipse I see:
            White spaces are required between publicId and systemId

According to other people with this problem it's related to the DOCTYPE which apparently must have a SYSTEM identifier.
Why in 2014 when DOCTYPE's are pretty much obsolete since we all use XSD instead of DTDs and there is no DOCTYPE in http://www.springframework.org/schema/integration (or should there be) does this error occur?
          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:mvc="http://www.springframework.org/schema/mvc"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:p="http://www.springframework.org/schema/p"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:jee="http://www.springframework.org/schema/jee"
          xmlns:int="http://www.springframework.org/schema/integration"
          xmlns:mail="http://www.springframework.org/schema/integration/mail"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                       http://www.springframework.org/schema/mvc
                       http://www.springframework.org/schema/mvc/spring-mvc.xsd
                       http://www.springframework.org/schema/integration/mail
                          http://www.springframework.org/schema/integration/mail/spring-integration-mail-3.0.xsd
                       http://www.springframework.org/schema/jee
                       http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/integration
                       http://www.springframework.org/schema/integration/spring-integration-3.0.xsd
                       http://www.springframework.org/schema/context/spring-context.xsd">

Thanks
Answer: You have to move spring-context.xsd to its id:
<beans
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-3.0.xsd">

Comment: Thanks. Any thoughts on why we get a DTD error with an XSD ?
Comment: Because any XSD (it is XML anyway) relies on DTD, as any XML document


Executar DELETE somente quando retornar o SELECT

Question: Tenho uma rotina onde atualizo a base de dados local com os dados de outra base.
Simplesmente executo um DELETE e em seguida um INSERT INTO tblX (SELECT * FROM tblY (tblY é uma tabela vinculada)), como abaixo.
O problema é que há um tempo entre o DELETE e o INSERT pois o SELECT demora muito tempo em alguns casos e eu queria diminuir ao máximo a possibilidade de o usuário solicitar registro de uma tabela que esteja no meio desse processamento.
Gostaria de saber se há algum mecanimo para que eu realize o DELETE somente quando o SELECT retornar.
conn = new OleDbConnection(Conexao.getConexaoPainelGerencialLocal());

conn.Open();

OleDbCommand cmd = new OleDbCommand(" DELETE * FROM tblClienteContato; ", conn);

cmd.ExecuteNonQuery();

cmd = new OleDbCommand(" INSERT INTO tblClienteContato " +
                       " SELECT * FROM tblClienteContatoVinculada;", conn);

cmd.ExecuteNonQuery();

Answer: Sugiro que utilize Transações para efetuar essa sequência de comandos. Desta forma, você irá garantir um acesso único a tabela:
OleDbConnection.BeginTransaction
Inicia uma transação no banco de dados com a possibilidade de especificar o tipo de isolamento da transação.
Modo de Isolamento
  - IsolationLevel.Serializable = Impede que outros usuários atualizem ou insiram linhas no intervalo de está sendo alterado até que a transação seja concluída.
Código
using (OleDbConnection conn = new OleDbConnection(Conexao.getConexaoPainelGerencialLocal())) {
    OleDbCommand cmd = new OleDbCommand();
    OleDbTransaction transaction = null;

    cmd.Connection = conn;

    // Abre a conexão e inicia a transação
    try {
        conn.Open();

        // Inicia uma transação
        transaction = conn.BeginTransaction(IsolationLevel.Serializable);

        cmd.Connection = conn;
        cmd.Transaction = transaction;

        cmd.CommandText = "DELETE * FROM tblClienteContato";
        cmd.ExecuteNonQuery();

        //nesse meio tempo, NINGUÉM poderá efetuar qualquer operação na tabela tblClienteContato até que a transação seja finalizada

        cmd.CommandText = " INSERT INTO tblClienteContato " +
                          " SELECT * FROM tblClienteContatoVinculada;";

        cmd.ExecuteNonQuery();

        // Efetiva a transação
        transaction.Commit();
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message); //exibe no console o erro
        try {
            // Se der algum erro (no delete ou insert) desfaz as alterações
            transaction.Rollback();
        }
        catch {

        }
    }
    //Aqui a conexão já estará fechada
}

Leitura altamente recomendada
Mensagem de erro "Contagem de bloqueios de compartilhamento excedida..." durante o processamento de uma transação grande
Transações e simultaneidade
Comment: Dos diferentes tipos de isolamento, temos que encontrar o ideal para este cenário. O Serializable que informei, permitiria a leitura nas demais partes da tabela, como não é suportado (precisa se investigar) use o meio de isolamento que permite a leitura dos dados limpos - ReadCommitted. Se quiser permitir ler mesmo a parte que está sendo alterada, utilize o ReadUncommitted.
Comment: Olá Ismael, estou recebendo essa mensagem quando executo o BeginTransaction: "Neither the isolation level nor a strengthening of it is supported".
Comment: Retire o IsolationLevel. Deixe apenas `conn.BeginTransaction();`
Comment: Funcionou, porém tenho o problema de o usuário não poder sequer fazer uma consulta. Preciso que a consulta fique disponível durante esse processo.
Comment: Acredito que essa seria a melhor opção porém recebi a mensagem "Neither the isolation level nor a strengthening of it is supported" para os outros tipos de transaction, deve ser o Access. Acabei criando tabelas temporárias.

Obrigado Ismael.
Answer: Após testar as opções da resposta do Ismael e obter o retorno: "Neither the isolation level nor a strengthening of it is supported", acredito por se tratar do MS Access, acabei criando uma tabela temporária local para receber os dados da rede e depois transferir para a tabela definitiva, assim sendo, a transferência entre tabelas locais ocorre de maneira quase que instantânea.
Answer: O comando apos o método "cmd.ExecuteNonQuery();" só sera executado depois que o método  ExecuteNonQuery obter a resposta da base de dados, então você pode usar o "try/catch" é fazer o rollback se tiver alguma exceção.
Try {
    conn = new OleDbConnection(Conexao.getConexaoPainelGerencialLocal());

    conn.Open();

OleDbCommand cmd = new OleDbCommand(" DELETE * FROM tblClienteContato; ", conn);

    cmd.ExecuteNonQuery();

    cmd = new OleDbCommand(" INSERT INTO tblClienteContato " +
                       " SELECT * FROM tblClienteContatoVinculada;", conn);

cmd.ExecuteNonQuery();

   // comando de delete aqui...
}
catch (SqlException odbcEx) {
   // erro na sql...
}
catch (Exception ex) {
   // erro no driver erro...
}

Comment: Cara, não entendi a idéia.


How to freeze the screen?

Question: In Unity, how can I freeze the screen in one scene, change scene, and then unfreeze it in the other scene? With freezing the screen I simply mean that it doesn't get updated while it's frozen. With screen I simply mean this:
I've tried to set Time.timeScale = 0, but that didn't work.
The thing is that I have different screen orientations in the scenes: portrait in the first and landscape in the other. This causes the second scene to twist/ruin the loading screen that was loaded in the first scene. The stuff being initialized in the second scene demands landscape orientation, so I can't just change the screen orientation after everything have been initialized.
I just want to freeze the screen after the loading image has loaded and then unfreeze it after the second scene has been initialized. Is this possible?
This is my code at the moment, generalized:
// Script for the first scene
class firstClass(){
    IEnumerator ChangeScene(){
        // Display loading screen in portrait orientation
        loadingScreen.SetActive(true);
        // Load the second scene
        SceneManager.LoadSceneAsync("secondScene");
    }
}

// Script for the second scene
class secondClass(){
     Start(){
         Screen.orientation = ScreenOrientation.LandscapeLeft; // twists the loading screen :(
         Init(a lot of stuff) // Needs landscape orientation to be initialized properly

         // Init done, hide loading screen
         loadingScreen.SetActive(false);

     }
}

This is how I want it to work:
class firstClass(){
    IEnumerator ChangeScene(){
        // Display loading screen in portrait orientation
        loadingScreen.SetActive(true);
        FreezeScreen();
        SceneManager.LoadSceneAsync("secondScene");
    }
}

class secondClass(){
     Start(){
         Screen.orientation = ScreenOrientation.LandscapeLeft; // doesn't affect the loading screen because the screen is frozen!
         Init(a lot of stuff);
         UnfreezeScreen();
         // Init done, hide loading screen
         loadingScreen.SetActive(false);

     }
}

Here's an illustration:
https://gyazo.com/864303465be750b7970636415ddf070d
Comment: Note that regarding ***pausing a game***. This is ***very hard indeed***.  Very, very difficult.  On large games there are whole teams of engineers that do nothing other than write the pause states for everything in the game.  Note that there is utterly no way to "freeze" the "screen" in Unity.  "screen" is meaningless.  If you mean "freeze" every GameObject in the scene, there is utterly no way conceptually to do that.  You have to write pause states for every single thing in the game.
Comment: What do you mean by freeze? You mean make orientation to stay the-same and not change?
Comment: Yes, exactly. I want the displayed things on the screen to stay the same even if i change the screen orientation.
Comment: It's totally unclear what you mean by "freeze" the screen.  You will have to remove that word.  Could it be you want to ***disable rotation*** perhaps during your loading process, and only ***enable rotation*** later?
Answer: void freezeOrientation(bool freezeOrnt = true)
{
    Screen.autorotateToLandscapeLeft = freezeOrnt;
    Screen.autorotateToLandscapeRight = freezeOrnt;
    Screen.autorotateToPortrait = freezeOrnt;
    Screen.autorotateToPortraitUpsideDown = freezeOrnt;
}

Freeze Orientation
freezeOrientation(true);

Un-freeze Orientation
freezeOrientation(false);

Comment: Thanks, but nope, it didn't work. I think my problem is more defined now, check my edit
Comment: **"I think my problem is more defined now**" I don't think so. I changed the title to make sense then you changed it back to something that doesn't make sense. The updated code you have in your question does not look like the code in my answer. Until you update your code to reflect what's in my answer, I can't tell what you are doing wrong. All my code is doing is disabling rotation is all orientation.
Answer: Use the lines below in your Start() or Awake() on an active object in the scenes that need orientation modification. Choose any of the lines regarding your intended orientation
void Awake()
{
 Screen.orientation = ScreenOrientation.LandscapeLeft;
 //OR
 Screen.orientation = ScreenOrientation.Portrait;
}

As these are logical orientations so touch coordinates change as well with current orientation.
You need to modify your second class start so that it goes landscape after initialization and disabling loading scene.
class secondClass(){
void Start()
{
         Init(a lot of stuff);

         // Init done, hide loading screen
         loadingScreen.SetActive(false);

         Screen.orientation = ScreenOrientation.LandscapeLeft;
 }
 }

Answer: As truly this is expected behavior not only in unity, but in any game engine.
Why I think so?
When you load another scene -- old scene must be destroyed :) As it's takes lot of resources :)
As I think, you need to save all info about objects settings on the scene. Load another scene. Do what do you need. And switch back to this scene and restore from settings.
or to ask your question by another way: tell about expected result and ask how to do this better :)

How to freeze the screen?


How to insert picture into excel cell?

Question: My task is to put picture from URL into certain cell in excel worksheet. I'm using NetOffice with C# to do this.
My main problem though is that I cannot find a way to insert a picture exactly into cell. When I use Sheet.Shapes.AddPicture(), I have to calculate coordinates where to put my picture. Of course, I have no problem with that (I created some kind of workaround), however, I'd like to ask whether my approach to solve this problem is right or if there is some other method where I could insert image into cell.
Here is my workaround:
var floatLeft = FloatLeftPixelsCalculation(rowNumber);
var floatTop = FloatTopPixelsCalculation(rowNumber);
Worksheet.Shapes.AddPicture(urlCellValue, MsoTriState.msoFalse, MsoTriState.msoTrue, floatLeft, floatTop, PictureWidth, PictureHeight);

public float FloatTopPixelsCalculation(int rowNumber)
        {
            float floatTop = 0;
            for (var rNumber = 1; rNumber < rowNumber; rNumber++)
            {
                var cellHeight = Convert.ToSingle(Worksheet.Cells[rNumber, ColumnIndex].RowHeight);
                floatTop = floatTop + cellHeight;
            }

            return floatTop;
        }

        public float FloatLeftPixelsCalculation(int rowNumber)
        {
            float floatLeft = 0;
            for (var columnNumber = 1; columnNumber < ColumnIndex; columnNumber++)
            {
                var cellWidth = Convert.ToSingle(Worksheet.Cells[rowNumber, columnNumber].ColumnWidth);
                floatLeft = floatLeft + cellWidth;
            }

            return floatLeft;
        }

Comment: As far as I know, images don't go directly inside of cells in a worksheet. This is evidenced by inserting an image into a spreadsheet - notice that is sorta "floats" atop the cells - same with clip art, shapes, etc.
Comment: You can't insert pics into cells.  Your approach of aligning them with the cell, by using Top and Left properties, etc., is the correct one.
Answer: Although Doug Glancy is correct in stating that Excel does not consider a picture to be "inside" of a cell, a picture can be associated with a particular cell and will act intuitively if correctly placed.
For example, say you have a list of houses.  Columns A-Y have various information about the house, and column Z has a picture of the house.  If the pictures are correctly associated with the proper cells, then when you sort, cut, copy, paste ranges, the pictures behave the way you would expect.
In order for Excel to manipulate the houses properly, they have to meet two criteria:

The picture must be entirely inside of the cell.  Using your code above, you would first place the picture as you have, and then adjust the row height and column width of the cell to be at least equal to the height and width of the picture.
The shape.Placement property must be set to either xlMove or xlMoveAndSize.  From MS documentation, the placement property can be one of the following:

    xlFreeFloating (3) Object is free floating.
    xlMove         (2) Object is moved with the cells.
    xlMoveAndSize  (1) Object is moved and sized with the cells.

If the picture is entirely inside of the cell and .Placement is set to xlMove or xlMoveAndSize, then whenever the container cell moves, the picture will move with it.  If .Placement is set to xlMoveandSize, then the picture will expand or contract whenever the cell width or height is changed.  This can be helpful because it makes sure the picture stays inside the boundaries of the cell.  If you use xlMoveandSize, you might also want to consider setting ShapeRange.LockAspectRatio = msoTrue to prevent the picture getting distorted when column widths or row heights are adjusted.
So yes, Virginia, you can place a picture in a cell.  Just make sure you place it carefully.

How to insert picture into excel cell?


Including Collider Variables in Prediction

Question: When the goal is to estimate a causal association between X and Y in the regression framework, one should not condition on (include as covariates) collider variables (common causes of both X and Y) since doing so may introduce spurious/non-causal associations that bias the coefficient estimate for X (Berkson's paradox).
My question: can including collider variables as potential predictors in a classification/machine learning framework also cause problems when accurate, generalizable, and useable prediction of Y is the goal? I.e. does the causal problem also lead to a prediction problem?
Answer: No, causal problems do not lead to prediction problems. In fact, in your case, the "problem" may actually allow us to improve our prediction!
Suppose the graph is simply $X \rightarrow C \leftarrow Y$. Then $X$ and $Y$ are d-separated, which means that they will be completely independent. Also, the effect of $X$ on $Y$ is identified without the need to condition on further variables. Estimation will show that $E[Y|do(X = x)] = E[Y|X = x] = E[Y]$. THis also means that $X$ alone is not useful to predict $Y$.
However, if we do not care about the causal effect, but merely want to predict $Y$, we will find that
$E[Y|X = x, C = c] \neq E[Y]$
because conditioning on the collider $C$ opens up a path between $X$ and $Y$. This will mean that a reliable variable selection procedure should pick up both $X$ and $C$ as relevant predictors. At the same time, conditioning on $C$ is invalid for causal inference.
One comment on wording: $E[Y|do(X = x)]$ is the mean of $Y$ if you set $X = x$ externally. Estimation of this quantity from data allows you to predict what happens when you $do(X = x)$. $E[Y|X = x]$ allows prediction of $Y$ when you see $X = x$. Both tasks may be useful, depending on the context.
Comment: Are you thinking of something like: Race and unobserved credit risk affect your location of residence, and Y = credit default is just a function of credit risk? Then a regression of default on race and location will give a non-zero race coefficient.
Comment: That is a good example of how unfairness could arise out of an unmeasured important confounder similar to the "red car" scenario in the car insurance example. Then making decisions about default would be unfair since race will play a role where it shouldn't (even if we include race or exclude). But I was wondering if a case of even measured colliders may also result in a similar unfairness result since the "effect"/weight on, say race, will change (or even flip sign) if a collider is included.
Comment: I am not sure I can follow. In the race/location example, when you compare a model with race only (zero effect, as it is d-separated) and with both race and location, the weight on race in the latter case could change dramatically, because location is a collider. In general, discrimination in algorithmic-decion making is a subtle topic. You may find p. 2043 of Zhan/Bareinboim, "Fairness in Decision-Making", helpful.
Comment: Very helpful. One clarification that may get to the reason for my worry: including C will change the weight/coefficient on X  away from the true causal value. If we then predict Y using these C and X weights to make decisions about something we care about, can't this classification lead to some negative allocation/fairness outcomes since we now allocate based off a biased X and C that wouldn't necessarily be dealt with in cross-validation?
Answer: Agree with @JulianSchuessler. You should consider causal inference if you will make inference (forgive the redundancy) on the learnt model (i.e. the variable associations). But for mere black box prediction, geenerally you may not need to find the true causal relationships.
Having said so, causal information is much more desired in most problems than associational one. Causality is the fondation for data-driven decision making. Believing in predictions obtained from some data have a lot of risks specially for generalization. Thus this would only be useful in the same distribution of your training data, which is normally violated.
Importantly, you should modify a conceptual mistake in your question. Colliders are not common causes of X and Y but common effects. Common causes are confounders. Confounders must be conditioned on to obtain the the true causal effect contrary to colliders.


Distribution of rank differences for a paired dataset

Question: I guess I have a rather simple question but I couldn't find the answer in previous posts. I have a paired dataset in which the same objects are ranked under two different conditions, here A and B:
<code>> data
      rankA  rankB
obj1  3      4
obj2  2      2
obj3  5      1
obj4  6      5
obj5  1      3
obj6  4      6
</code>
I want to know what are the objects that are showing the most significant changes between the two conditions, so to begin with I calculate a rank difference statistics, here "delta":
<code>> data
      rankA  rankB  delta
obj1  3      4      -1
obj2  2      2      0
obj3  5      1      4
obj4  6      5      1
obj5  1      3      -2
obj6  4      6      -2
</code>
Now my question is what is the distribution of this delta statistics if the ranks were generated randomly? As I said my intention is to find objects that show the most significant difference between two conditions, I want to have this randomly generated delta distribution for my null hypothesis so for each specific object I can estimate what is the likelihood that I see a delta value that extreme.
My first guess was that the distribution should be normal but when I randomly simulated dummy datasets it doesn't look normal at all and is more like a sharp smooth triangle, see here for 1 million random ranks:
<code>#set.seed(1)
list1 <- sample(1:1000000, 1000000, replace = FALSE)

#set.seed(2)
list2 <- sample(1:1000000, 1000000, replace = FALSE)

delta <- list2 - list1

hist(delta, breaks = 200)
</code>

Any idea on what is this distribution and how I can calculate my p-values? Thanks!
NOTE that I'm not using wilkoxon or signed tests as I'm not interested in comparing whether the two ranked lists are from the same population or not, I'm interested in the individual objects ranked, but I'm open to any suggestion or other methods that I could use instead! Thank you!
Comment: If the two ranks columns are uniformly distributed then their difference will be a triangular distribution.
Comment: While a given rank might be discrete uniform, the whole collection of ranks are not independent, even if the original sample values were. If there are no ties, each (unsigned) rank appears once in each sample.
Comment: Would it help to think of the distribution as where the say "7"s go on a Sudoku game, or how 8 non-attacking rooks can be placed on a chess board? Your deltas are the distance (horizontal or vertical) from the diagonal.
Comment: With these paired values (two ranks on each object), the triangular marginal distribution would apply if the two sets of ranks were such that they were no more alike than if they had been unpaired (i.e. as if the ranks were assigned each time as if the two sets of rankings had nothing to do with each other at all). This would correspond to a most strange null hypothesis but was not the thing I was concerned about. Rather it was the drawing a set of those rank differences as if they would be independent of each other (per your diagram) and then immediately asking a question about p-values...ctd
Comment: ctd... -- now there's a potential trap to avoid, though it depends on the precise hypothesis you attempt to test (and so how you should generate a p-value). I was attempting to warn you not to treat the collection of rank differences as if they were independent if you were computing a collective p-value for them (as it seemed you might if you did  a single overall test).
Comment: @Glen_b tnx, I'm not quite sure I can get your point, does it mean the distribution is not gonna be triangular?
Comment: @user2974951 thanks. So with this triangular distribution do you think it makes sense for me to estimate p-values for my delta? based on distribution parameters from this post for example?
Answer: You write

I want to know what are the objects that are showing the most
significant changes between the two conditions

I think "significant" is misused here. To establish significance, you need a hypothesis. If you mean "largest" then you can just look at delta. You then look at a distribution of differences of ranks (1 million ranks!) and ask about it. But that distribution could be used to test the significance of your own whole distribution against that distribution. E.g. if your ranks were more likely to be close to 0, then the average delta would be lower.
But you say you don't want that. So, just use delta.
Comment: Thank you Peter! This was my first question here so my apologies for not being clear. I understand your point about the largest delta and I already have those values, but what I miss here is how confident I can be about those big delta values not being a mere chance, or in other words how far down the list of these biggest delta values I can go to shortlist objects. That is why I wanted to do hypothesis testing with delta distributions from random ranks, so I can use find critical values for the delta at for example p=0.05. Is there a more statistically sound way for me to estimate that? Tnx!
Comment: The hypothesis test would be something like "is my distribution of ranks random?" or, more precisely "is the mean delta in my distribution smaller than the mean delta between two uniform distributions".

It will be. It sort of has to be, unless your pairing really stinks.

You should use a substantive reason to decide on a delta that is "too big".


How can preprocessing with PCA but keeping the same dimensionality improve random forest results?

Question: I found these sentences:

PCA before random forest can be useful not for dimensionality
  reduction but to give you data a shape where random forest can perform
  better.
I am quiet sure that in general if you transform your data with PCA
  keeping the same dimensionality of the original data you will have a
  better classification with random forest

from this page:
PCA on high-dimensional text data before random forest classification?
In my case I found this is really true, for a regression problem with a database of ~1M records and 25 predictors. The error decreases by about 10% if I use the 25 PCA as predictors instead of the 25 original predictors.
Can anyone help me in understanding and clearly interpreting this result?
Comment: In many cases, PCA before supervised method is not recommended, because PCA is not taking account to the response variable. But keep the same number of features, will increase the performance? good question..
Comment: Random forest is invariant to scaling, so all the action here would have to come from rotation and reflection in the linear transformation generated by PCA? Does random forest prefer (1) some features to be extremely predictive while others are entirely useless compared to (2) all features are somewhat predictive?
Answer: Random forest struggles when the decision boundary is "diagonal" in the feature space because RF has to approximate that diagonal with lots of "rectangular" splits. To the extent that PCA re-orients the data so that splits perpendicular to the rotated & rescaled axes align well with the decision boundary, PCA will help. But there's no reason to believe that PCA will help in general, because not all decision boundaries are improved when rotated (e.g. a circle). And even if you do have a diagonal decision boundary, or a boundary that would be easier to find in a rotated space, applying PCA will only find that rotation by coincidence, because PCA has no knowledge at all about the classification component of the task (it is not "$y$-aware").
Also, @hxd1011's caveat applies to all projects using PCA for supervised learning: data rotated by PCA may have little-to-no relevance to the classification objective.


Não consigo remover folha em árvore binária

Question: Estou tentando remover uma folha da árvore, fiz um código que aparentemente, na minha cabeça está certo, só que ele não remove o elemento que eu quero.
Aqui está minha classe No:
package arvore;

public class No {

    private No esquerda;
    private No direita;
    private int valor;

    public No(int valor) {
        this.valor = valor;
    }

    public No getEsquerda() {
        return esquerda;
    }

    public void setEsquerda(No esquerda) {
        this.esquerda = esquerda;
    }

    public No getDireita() {
        return direita;
    }

    public void setDireita(No direita) {
        this.direita = direita;
    }

    public int getValor() {
        return valor;
    }

    public void setValor(int valor) {
        this.valor = valor;
    }
}

Aqui está minha classe ArvoreBinaria:
package arvore;

public class ArvoreBinaria {

private No raiz;

public ArvoreBinaria(int valor) {
    adicionar(raiz, valor);
}

public No getRaiz() {
    return raiz;
}

public void setRaiz(No raiz) {
    this.raiz = raiz;
}

public void adicionar(int valor) {
    adicionar(raiz, valor);
}

public void adicionar(No no, int valor) {
    if (this.raiz == null) {
        raiz = new No(valor);
        return;
    }
    if (valor < no.getValor()) {
        if (no.getEsquerda() != null) {
            adicionar(no.getEsquerda(), valor);
        } else {
            no.setEsquerda(new No(valor));
        }

    } else if (valor >= no.getValor()) {
        if (no.getDireita() != null) {
            adicionar(no.getDireita(), valor);
        } else {
            no.setDireita(new No(valor));
        }
    }
}

public void preOrdem() {
    preOrdem(this.raiz);
}

public void preOrdem(No no) {
    if (no != null) {
        System.out.println(no.getValor());
        preOrdem(no.getEsquerda());
        preOrdem(no.getDireita());
    }
}

public void posOrdem() {
    posOrdem(this.raiz);
}

public void posOrdem(No no) {
    if (no != null) {
        posOrdem(no.getEsquerda());
        posOrdem(no.getDireita());
        System.out.println(no.getValor());
    }

}

public void emOrdem() {
    emOrdem(this.raiz);
}

public void emOrdem(No no) {
    if (no != null) {
        emOrdem(no.getEsquerda());
        System.out.println(no.getValor());
        emOrdem(no.getDireita());
    }
}

public void remover(int valor) {
    remover(this.raiz, valor);
}

public void remover(No no, int valor) {
    if (no != null) {
        boolean flag = false;
        if (valor == no.getValor() && no.getEsquerda() == null && no.getDireita() == null) {
            no = null;
            flag = true;
        }
        if (!flag) {
            remover(no.getEsquerda(), valor);
            remover(no.getDireita(), valor);
        }
        if (flag == false) {
            if (no.getEsquerda() == null) {
                no.setEsquerda(null);
            }
            if (no.getDireita() == null) {
                no.setDireita(null);
            }
        }

    }
}
}

Aqui está minha aplicação principal:
package app;

import arvore.ArvoreBinaria;

public class App {

    public static void main(String[] args) {
        ArvoreBinaria arvore = new ArvoreBinaria(10);
        arvore.adicionar(8);//                          10
        arvore.adicionar(12);//                 8                 12
        arvore.adicionar(12);//           6           9       11        12
        arvore.adicionar(11);//        n      7     n   n   n    11    n   15
        arvore.adicionar(11);//             n   n               n  n      n   n
        arvore.adicionar(15);//
        arvore.adicionar(9);//                      n = null
        arvore.adicionar(6);//
        arvore.adicionar(7);//
        //System.out.println(arvore.getRaiz().getDireita().getEsquerda().getDireita().getValor());

        /*System.out.println("Pré Ordem");
        arvore.preOrdem();
        System.out.println("----------------------------");
        System.out.println("Em Ordem");
        arvore.emOrdem();
        System.out.println("----------------------------");
        System.out.println("Pós Ordem");
        arvore.posOrdem();
         */
        arvore.remover(7);
        //System.out.println(arvore.getRaiz().getEsquerda().getEsquerda().getDireita().getValor());
        arvore.emOrdem();
    }
}

Comment: `if (!flag)` e `if (flag == false)` são a mesma coisa.
Comment: Sim, é que no primeiro flag se ele for true, eu não quero que ele entre naquele bloco de código, pois daria NullPointerException, já que o no.getEsquerda() seria justamente da folha, do nó que acabei de anular.
Já na segunda flag, ela só fica true quando acha a folha, quando não, ela permanece false. daí fiz esse bloco de código para o no pai, anular a referência ao nó que acabou de ser removido, quando a pilha de execução da recursividade voltar para o pai.
Comment: Você não possui nenhum código que possa modificar o valor dessa flag entre as duas comparações.
Answer: Pelo que entendi, esta é uma árvore binária de busca. Sendo assim, o algoritmo para remover um nó deve levar em conta alguns casos:

se o nó for uma folha (ou seja, não tem sub-árvore direita nem esquerda), é só removê-lo:

Ex:
  10
 /  \
5    15
    /
   12

Para remover o 12 é fácil: como ele não tem filhos, é só retirá-lo da árvore.
  10
 /  \
5    15

nó só tem um filho: substitua o nó pelo filho

Ex:
  10
 /  \
5    15
    /
   12
  /  \
 11  13

Para remover o 15: como ele só tem um filho (que é o nó 12), basta substituí-lo pelo filho.
  10
 /  \
5    12
    /  \
   11  13

se o nó tem 2 filhos:

encontre o maior dos filhos que estão na sub-árvore à esquerda
copie o valor do maior filho para o nó
remova recursivamente o filho da sub-árvore esquerda

Ex:
  10
 /  \
5    15
    /  \
   12  17
  /  \
 11  13

Para remover o 15:

encontre o maior filho da sub-árvore esquerda: no caso é o 13
substituia o valor de 15 por este maior filho:

  10
 /  \
5    13
    /  \
   12  17
  /  \
 11  13

recursivamente remova o 13 da sub-árvore esquerda (ou seja, começo a remover o 13 a partir do 12):

o algoritmo vai procurando recursivamente pelo 13, e como a busca foi feita a partir do 12, ele chega no 13 debaixo. E quando ver que ele não tem filhos, cai no caso 1 (ele é simplesmente removido):

  10
 /  \
5    13
    /  \
   12  17
  /
 11

O algoritmo acima e o código abaixo foram adaptados deste artigo. No seu caso ficaria assim:
// encontrar o maior valor a partir do nó indicado
private No maiorValor(No no) {
    while (no.getDireita() != null) {
        no = no.getDireita();
    }

    return no;
}

public void remover(int valor) {
    remover(this.raiz, valor);
}

public No remover(No no, int valor) {
    // chave não encontrada na árvore
    if (no == null) {
        return no;
    }

    // valor menor, procurar na sub-árvore esquerda
    if (valor < no.getValor()) {
        no.setEsquerda(remover(no.getEsquerda(), valor));
    } else if (valor > no.getValor()) {
        // valor maior, procurar na sub-árvore direita
        no.setDireita(remover(no.getDireita(), valor));
    } else { // valor encontrado
        // caso 1: nó é uma folha (não tem filhos)
        if (no.getEsquerda() == null && no.getDireita() == null) {
            // remove-o (seta a "raiz" deste nó para null)
            return null;
        } else if (no.getEsquerda() != null && no.getDireita() != null) {
            // caso 3: nó tem 2 filhos
            // encontrar o maior dos filhos que antecede o nó
            No maiorAntecessor = maiorValor(no.getEsquerda());

            // copia o valor do antecessor para este nó
            no.setValor(maiorAntecessor.getValor());

            // remove o antecessor recursivamente
            no.setEsquerda(remover(no.getEsquerda(), maiorAntecessor.getValor()));
        } else {
            // caso 2: nó só tem um filho
            No child = (no.getEsquerda() != null) ? no.getEsquerda() : no.getDireita();
            no = child;
        }
    }

    return no;
}

Se só quer remover as folhas (de acordo com este comentário), basta adaptar o algoritmo acima para ignorar os casos em que o nó não é folha:
public void removerFolha(int valor) {
    removerFolha(this.raiz, valor);
}

public No removerFolha(No no, int valor) {
    if (no == null) {
        return no;
    }

    // valor menor, procurar na sub-árvore esquerda
    if (valor < no.getValor()) {
        no.setEsquerda(removerFolha(no.getEsquerda(), valor));
    } else if (valor > no.getValor()) {
        // valor maior, procurar na sub-árvore direita
        no.setDireita(removerFolha(no.getDireita(), valor));
    } else { // valor encontrado
        // nó é uma folha (não tem filhos)
        if (no.getEsquerda() == null && no.getDireita() == null) {
            // remove-o (seta a "raiz" deste nó para null)
            return null;
        }
    }

    // nó não foi encontrado ou não é folha, retorna o próprio nó
    return no;
}

Comment: @GabrielHenrique Eu acho que não precisa desta flag, basta adaptar o algoritmo de remoção para ignorar os casos em que o nó não é folha. Atualizei a resposta com esta opção.
Comment: Obrigado pela resposta, vai me ajudar muito futuramente. mas no momento eu só quero remover uma folha, só estou fazendo um método remover exclusivamente pra isso.
O meu método remover funciona da seguinte maneira: ele verifica se o nó é folha, e é o nó procurado pra remover. após isso, se ele acha o nó, ele anula ele e seta a flag true. como a flag está true, ela não entra no bloco de código que aplica a recursividade: remover(no.getEsquerda(), valor); a flag evita um NullPointerException já que não entra nesse código.
Comment: Se a flag é false, quando a recursividade volta para o nó pai que foi removido, ele anula a referência ao nó que foi excluido.
Este código parece estar completo para mim, só que ele simplismente não remove o nó, não entendo o porque. Desde já agradeço por ter me respondido, após remover a folha, vou criar um método pra remover um nó que só tenha um filho, depois um nó que tenha dois, daí juntarei tudo pra fazer tudo isso em um remover só. este é um processo lento mas é necessário para eu aprender, Obrigado.
Comment: Muito obrigado, como eu marco a pergunta como solucionada ?
Comment: @GabrielHenrique É só clicar no ✓ no lado esquerdo da resposta ([aqui](https://pt.meta.stackoverflow.com/q/1078/112052) tem instruções mais detalhadas, caso vc não encontre)


Cannot get correct viewbag value after a post

Question: I need to get a record count out of a successful Ajax post.
Since the datatype is "html", I cannot check for a specific record count via json.
So, what I'm doing is trying to apply the record count to a ViewBag variable (from a Controller method) and assign it to a hidden html field that I can check after the post. If 0 records are returned, I can display a proper message to the user.
My process is as follows: I'm using MVC 5.2

In the GET for the Controller method, I set the ViewBag variable
count to 1 (for a test. Ideally, it should be 0).

The View assigns the value of the ViewBag variable to the JS variable.
In the POST, I get the record count from the records retrieved and assign it to the ViewBag property.
The View again should assign the value of the ViewBag variable to the JS variable.
When the POST finishes, the JS variable checks if the value is 0 and then would display the proper message.

However, the issue I'm having is that the initial value I set during the GET of 1, never changes.
I've verified during debugging, that when the POST occurs in the controller, the ViewBag property is set to 0 (no records returned). I purposely set the initial value to 1 (in the GET) just to see if the value has changed.
Can someone please inform me why the JS variable is not being updated to the value of 0 (step 4 above) after the POST?
Here is my code:
Controller
<code>// GET: Customers/CustomerProjects/Details
public async Task<ActionResult> Details()
        {
            ViewBag.projectCount = "1";
            ViewBag.CustomerEmail = await db.GetCustomerDDLAsync();

            return View();
        }

[HttpPost]
        // POST: Customers/CustomerProjects/Details/5
        public async Task<ActionResult> Details(short? id)
        {
            if (id == null)
            {
                return View("IDIsNull");
            }
            ViewBag.CustomerEmail = await db.GetCustomerDDLAsync();
            Customer customer = await db.GetProjectsByCustomerIDAsync(id);
            if (customer == null)
            {
                return View("ObjectModelNull");
            }

            ViewBag.projectCount = customer.Projects.Count.ToString();
            return View(customer);
        }
</code>
VIEW
<code>@Html.Hidden("projCnt", (string)(ViewBag.projectCount))
</code>
JS
<code>if ($('#projCnt').val() == "0")
</code>
Answer: Viewbag only exist for 1 view,
When you are transfered to the POST, the Viewbag is empty.
You can use TempData instead.
Check out tihs link:
Tempdata vs Viewbag...
edit:
Also, it is not that clear, maybe you're Return View occurs before you update the ViewBag? (i.e. goes into one of the if's)
Comment: I tried Tempdata. That doesn't work either...The GET & POST are using both the same View. My return View definitely occurs after I update the ViewBag. I verified it during debugging.
Comment: Strange... can you post your full code then?

You can also try using the Session object, to see if this is the problem. (i.e. Session["value"] = "1" ) then use instead of the ViewBag.projectCount;)
Comment: Ziv, I got around this issue by setting the datatype of the ajax call from 'html' to 'json' and was able to detect the count in the 'success' function to display the proper message.
Answer: try this:
<code> TempData["projectCount "] = 123;
 TempData.Keep();
</code>


How to trigger hook_form_alter() on my custom $form?

Question: I have written a custom module which builds a custom user_profile_form():
mymodule_user_profile_form($form, $form_state, $user) {
  module_load_include('inc', 'user', 'user.pages');
  $form = user_profile_form($form, $form_state, $user, 'account');
  // doing stuff with $form ...
  return $form;
}

Now, it's working as desired but I noticed a lot of contrib modules are altering the user_profile_form() calling a hook_form_alter() on the $form_id == 'user_profile_form'.
Now, I want all these modifications applied to my custom profile form, too. How to achieve that?
The hacky way would be to go through all modules and change the checks for $form_id == 'user_profile_form' || $form_id == 'mymodule_user_profile_form', but this is a no-go and I would appreaciate a clean way to do this. Any idea?

Update: drupal_get_form() is not the answer as it is not working as desired. This is only returning the $form object without re-building it which causes many issues with theming layer and $form_state['values']. I'm adding this information as requested by moderator, but this is not part of my question. This is the not working code with drupal_get_form() b6d1f1d8 and this is the working code with user_profile_form() d5d43dc0.
Answer: You should use drupal_get_form($form_id) to get the form instead of directly calling user_profile_form() and it will ensure that all the form alters are applied before you get the form.
Update:
          Can you explain why you are not using hook_form_alter()?
But if you want to proceed this way, then instead of calling drupal_get_form() you can replace that with the code from drupal_build_form(), except the call to drupal_process_form(),
Replace drupal_get_form() with the following code, copied from drupal_build-form()
$form_state += form_state_defaults();
if (!isset($form_state['input'])) {
   $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
}
$form = drupal_retrieve_form('user_profile_form', $form_state);
drupal_prepare_form('user_profile_form', $form, $form_state);

Comment: @vertoe I have tested the code, you gave, with `drupal_get_form()` and it is working fine for me.
Comment: `drupal_get_form()` is not *building* the form and is a total mess for the user profile form, for example the $form_state is not populated correctly and theming layer is broken. I need to build the form from scratch.
Comment: what do you mean by it is not building the form?, can you post your code and also the return value of `drupal_get_form()`
Comment: Reference to full code history: This is not working [b6d1f1d8](http://cgit.drupalcode.org/sandbox-donschoe-2270791/tree/user_revision_edit.module?id=b6d1f1d839bb6fdc8f99354b94bf9bc01c1b25f0#n223) with `drupal_get_form()` the `$form_state['values']` are empty after `_submit()` - and this fixed it: [d5d43dc0](http://cgit.drupalcode.org/sandbox-donschoe-2270791/tree/user_revision_edit.module?id=d5d43dc06b97fdb52e8684ade615a0905cfd4e1e#n223) calling directly the form builder. There are similar discussions on the internet.
Comment: @vertoe I'm struggling to understand - is your problem sorted? If so, would be so kind as to put an answer in detailing how you fixed it? If not, could you update the question and make it clear why the approach in the second link in your previous comment didn't work? Would be nice to get the question closed off is all; thanks
Comment: @Clive this is not solving my problem and we were discussing why. I can add this information to the original question. It's still open.
Comment: @vertoe are you using the `user_revision_edit` module that you gave? or are you using it as a reference?
Comment: @wolverine I'm using and developing it. My question is how this module can trigger all the changes from the user profile form without using the `drupal_get_form()` function.
Comment: In simple terms: reproduce drupal_get_form, but add a custom value to the $form_state before invoking drupal_build_form. Then implement hook_form_alter for the user profile form, and only make changes if $form_state contains that custom value. A little 'round the houses', but it'll work
Comment: @vertoe can you explain why you are not using `hook_form_alter()`.
Comment: @vertoe I have updated the answer


How to train factorization machines

Question: I've been interested in factorization machines for a while now, trying to get along with second order before going any higher.
After reading Rendle's original article (2010), I switched to this one : https://arxiv.org/pdf/1607.08810.pdf since the author gives more informations about high order factorization machines (at least for m=3).
I'm trying to implement the pseudocode he gave but I'm having some doubts :
1/ Section 7, he introduces the loss fuction $\textit{l}$, says it's $\mu$-smooth. What does that mean ? And more important, from where does the $\mu$ come from ? For $\beta$ for example, he said specifically that he obtained it by cross-validation but he said absolutely nothing about $\mu$.
2/ As given in this article, $$\hat{y}_{FM}(x,w,P)=<w,x>+\hat{y}_{A^2}(x,1,P)$$
The algorithm he gives provides training for $\hat{y}_{A^2}(x,1,P)$ and thus for $P$. For $w$, the article says :
"$w \in \mathbb{R}^d$ is a vector of first-order weights, estimated from training data".
Does this mean we have to go through a separated learning to get $w$ ? Why wouldn't we include it in the same algorithm running for $P$ ?
3/ At last, in the pseudo-code he gave, how can we interpret $\delta$ as an error ? I'm more used to the error (at least during the learning bit) defined as a difference between two objects and here there's this division.
Thank you all !
EDIT 1 : So I found an answer for my last question. $\delta$ is in fact $f'(\theta)/f"(\theta)$, given that we want to minimize $f$ w.r.t $\theta$.
EDIT 2 : Also found the answer to my first question. The squared loss is 1-smooth, that's why the author didn't mention $\mu$ anymore when he chose squared loss as the loss function to work with.
My second question remains unanswered though and it's giving me headach !
Answer: 2/ you can say w is part of FM parameters. normal FM have first-order、second-order and higher-order parameters
Comment: This is being automatically flagged as low quality, probably because it is so short.
At present it is more of a comment than an answer by our standards. Can you expand
on it? We can also turn it into a comment.

How to train factorization machines


How can we prove that $27$ is the largest number $χ$ such that $\sum_{i \in δ(χ^3)} = χ$?

Question: According to Stetson University, $27$ is the largest number $χ$ such that $\sum_{i \in δ(χ^3)} = χ$ where $δ(χ) =$ digits of $χ$.
I have tried proving that this is true, but do not know where to start. Could someone please help me with this question? $\because 27 = 3^3$, does this mean anything? Thanks.
PS: $i$ does not represent $\sqrt {-1}$ in this case.
Comment: @GeorgeN.Missailidis I notice that you use symbols such as $\because$ and $\therefore$ in your writing, and that you have been editing other user's questions and answers to replace their words with these symbols. You will find that in mathematics, it is often better to use words such as *therefore* or *since*, etc., rather than these symbols; using $\because$ does not make for better mathematical writing. The important thing is that the idea is clear.
Comment: $\delta(x)$ is the sum of the digits, maybe? The digits are just a collection.
Comment: Yes. Sorry bout that.
Comment: If $\delta(\chi)$ are the digits of $\chi$ then notationally the problem should be showing that $27$ is the largest $x$ such that $$\sum_{i\in \delta(x^3)} i = x$$
Comment: Thanks for that. I will get to that right away
Comment: Ok. I will put that into consideration next time.
Answer: Intuitively, the sum of digits is like a logarithm, so $\delta (x^3)$, the sum of digits of $x^3$, is something like $3 \log x$ and clearly there will be a largest $x$ that satisfies your equation.  We want to find an upper limit for $x$, then we can just search up to that and be done.
To make this precise, suppose $10^{n-1} \lt x \lt 10^n$, so $x$ has $n$ digits.  Then $x^3 \lt 10^{3n}$ so $x=\delta(x^3) \lt 27n=27 \lceil \log_{10}x\rceil$  We can ask Alpha to find that for $x \ge 45$, there is no hope because $x \gt 27 \log_{10}x$.  Then we can just search up to $45$ and discover that $27$ is the largest solution.
Comment: Thanks so much, Ross :)
Answer: The number of digits of a positive integer $x$ is $\lfloor \log_{10} x\rfloor+1$. Let $S(x)$ be the sum of the digits of $x$. Then
$$S(x)\le 9(\lfloor \log_{10} x\rfloor+1)$$
So $S(x^3)=x$ implies
$$x\le 9(\lfloor 3\log_{10} x\rfloor+1)\le9(3\log_{10} x+1)$$
For a lazy solution, plot (with google, for example) the function
$$f(x)=9(3\log_{10} x+1)-x$$
and you'll find that $f(x)\le 0$ for $x\ge 57$. For a more rigurous approach, you should differentiate $f$ and prove that $f'<0$ to guarantee that.
Comment: Thanks for the help guys. I really appreciate it. I would have given you a vote as well @ajotatxe but I have reached my limit for today.


Yum issues after upgrading MySQL from 5.0 to 5.5 on RHEL

Question: I'm running RHEL 5.6 and trying to upgrade MySQL from 5.0 to 5.5. I ran sudo yum remove mysql* to remove all the existing MySQL-related packages.
Then I installed MySQL 5.5 packages:
$ sudo yum install mysql55*
Loaded plugins: downloadonly, rhnplugin, security
Excluding Packages in global exclude list
Finished
Setting up Install Process
Package mysql55-embedded-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-server-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-test-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-devel-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-bench-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-embedded-devel-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-libs-5.5.22-1.ius.el5.x86_64 already installed and latest version
Package mysql55-debuginfo-5.5.22-1.ius.el5.x86_64 already installed and latest version

When I check the list of packages it tells me I still have 5.0:
$ sudo yum list mysql
Loaded plugins: downloadonly, rhnplugin, security
Excluding Packages in global exclude list
Finished
Available Packages
mysql.i386                             5.0.77-4.el5_6.6                           rhel-x86_64-server-5.6.z
mysql.x86_64                           5.0.77-4.el5_6.6                           rhel-x86_64-server-5.6.z

But when I check the MySQL client and server I do seem to be running 5.5:
$ mysql -V
mysql  Ver 14.14 Distrib 5.5.22, for Linux (x86_64) using readline 5.1

$ tail /var/log/mysqld.log
Version: '5.5.22-log'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  Distributed by The IUS Community Project

Q: How can I fix yum to properly reflect the newly installed packages?
Answer: Your sudo yum list mysql is showing those mysql packages as Available, not installed.  How about checking the output of yum list installed 'mysql*'
Comment: Please vote up that comment if you think my question should be removed as it's a big miss from myself rather than any problem other people could be running into.


Finding rotation and translation using (residual) vectors

Question:
As illustrated in Fig.1 I have $n$ (blue) straight lines represented by $F = \{f_1(x),f_2(x) \dots f_n(x)\}$. These lines passes through the (yellow) straight line $g(x)$. Similarly $X = \{\mathbf{x}_1, \mathbf{x}_2, \dots \mathbf{x}_n \}$ are sample points that lie on $g(x)$ and lie close to the intersecting points between $f_1(x),f_2(x)  \dots f_n(x)$ and $g(x)$. The red (residual) vectors $\mathbf{v}_1,\mathbf{v}_2  \dots \mathbf{v}_n$ are obtained by connecting the sample points with its corresponding intersecting points.
$$\textbf{v}_n = \bar{X}_n - X_n$$
$\qquad$ where $\bar{X}$ is the set of intersecting points between $F$ and $g(x)$.
All the values of the points, lines and vectors are assumed to be known.
My goal is to find $\hat{g}(x)$ (as shown in Fig.2) or in other words to rotate and translate $g(x)$ and the sample points in such a way that the size of the (residual) vectors becomes smaller after the transformation. Note that the distances between sample points remain unchanged after the transformation; that is
$$||\mathbf{x}_{n} - \mathbf{x}_{n - 1}|| = || \mathbf{x}_{n}' - \mathbf{x}_{n - 1}'|| \qquad \mathrm{where} \,\,  n = 1,2, \cdots N$$
If $X' = \{\mathbf{x}_1', \mathbf{x}_2', \cdots \mathbf{x}_n'\}$  that lies on $\hat{g}(x)$ as shown in Fig.2 is the set containing the transformed (Rotation and Translation) sample points than there exists a Rotation $\mathbf{R}$ and Translation $\mathbf{T}$ such that
$$X' =  \mathbf{R} X  + \mathbf{T}$$
Finding the best transformation here is to minimize the sum of the square of the  residual vectors. Thus
$$ \sum_i || \bar{X}_i' - (\mathbf{R} X_i  + \mathbf{T})||^2 \rightarrow \mathrm{min}$$
$\qquad$ where $\bar{X}'_i$ is the set of intersecting points between $F$ and $\hat{g}(x)$ and itself depends on $\mathbf{R}$ and $\mathbf{T}$. How would one proceed further from here?
The constraints:  the sample points  of $X$ and $X'$ are collinear and that the spacing between the sample points remain unchanged.
Is it possible to solve this problem by exploiting the information (magnitude and direction) contained in the vectors? Or in other words, is the information contained in the vectors sufficient to tell me which direction $g(x)$ must be moved so that it ends up at $\hat{g}(x)$?
Comment: This problem just has two unknown parameters. Can we see your formulation of the iterative method ? And why do you reject an iterative method ?
Comment: "the distances between sample points must be preserved" is of course impossible to achieve exactly. What scalar criterion do you want to use ?
Comment: Why is it impossible to achieve exactly? Any ridid transformation preserves the euclidian distance between the sample points, no? What exactly do you mean by scalar criterion?
Comment: Because there are more equations than unknowns.
Answer: Hint:
Assume that you fix the rotation angle $\theta$ of $g(x)$ around some fixed point. Let the coordinates of the intersection points with the lines $f_k$ be $(u_k,v_k)$ and let the slopes of these lines be $s_k$. Let the distances between the points $x_k$ and $x_{k+1}$ be $d_{k,k+1}$.
We can find an "optimal" translation of horizontal component $t$ by solving the least-squares problem
$$\min_t\sum_{k=1}^{n-1}((u_{k+1}-u_k)^2+(v_{k+1}-v_k+t(s_{k+1}-s_k))^2-d_{k,k+1}^2)^2.$$
This leads to a cubic equation, which can be solved analytically. From the value of $t$, we can draw the residual error $E(\theta)$. Then the problem is reduced to 1D minimization.

Expressing $u,v$ in terms of $\theta$, you will get linear functions of the form $a+b\cos\theta+c\sin\theta$ and the above cost function is a bivariate mixed trigonometric polynomial of degree four. This amounts to a polynomial equation of a higher degree (like eight, but I am unsure). Chances for an analytical solution are zero or less.

Other criteria than the above least-squares can be used. This will only make the resolution harder.
Comment: Cannot I exploit the information contained in the vectors to find the approximate direction of rotation and translation?
Comment: @unfinished_sentenc: if you don't want an iterative solution, an approximate direction is of strictly no use.
Comment: As illustrated in Fig.2, $\hat{g}(x)$ is not only translated about positive $x-$axis but also rotated slightly in the ccw direction in comaprision to $g(x)$. How would one compute the optimal rotation?
Comment: Thanks for your answers and Hint really..
I am somewhat new in this field. What books and authors would you recommend in order to tackle this problem?
Comment: @unfinished_sentenc: lookup "least-squares minimization".
Comment: Could you please elaborate how you came up with the expression for *optimal* translation of horizontal component $t$?
Comment: @unfinished_sentenc: means with minimum error. Read about least-squares fitting.
Comment: The idea behind least-squares fitting is in my opinion preety straight forward. Do you mean that the vectors (red arrows) do not contain ANY information about the direction in which $g(x)$ must be moved? My guess was one could use the information in the vectors as a force *pushing* $g(x)$ towards the optimal $\hat{g}(x)$ such that sum of the squares of the error is minimized.

How can one show analytically that the vectors are redundant?
Comment: @unfinished_sentenc: I said that if you don't want an ITERATIVE solution, an APPROXIMATE direction is of strictly no use. Your question WAS SAYING "... but that is exactly what I want to avoid".
Comment: "an APPROXIMATE direction is of strictly no use". I have posted an answer with a figure which might simplify the discussion.
Comment: @unfinished_sentenc: not at all. You don't seem to appreciate or care about the difference between a direct and an iterative method, nor worry about silently changing the question.


What is the benefit of soaking double reeds in water?

Question: My bassoon teacher advises me to soak my reed in water before playing. Apparently water has properties that my saliva alone doesn't. Why would this be useful?
Also I have seen Oboe players doing this, but not Clarinettists, Saxophonists (or anyone else without a double reed). Why don't they do so?
Answer: With a single reed, your saliva can contact 100% of the surface area of the reed. When you soak a double double reed in your mouth, however, you're only getting to 50% max of the surface area of the reed. Soaking in a cup of water allows you to get soak the whole reed evenly. Some single reed players soak in water instead of saliva just because it's more efficient and consistent.
Answer: I asked my father, who was Principle Bassoon in the Milwaukee Symphony Orchestra for 30+ years.  Here's a paraphrase of what he said:
"Single-reed players do moisten their reeds with water.  I actually knew a clarinetist who kept a whiskey shot glass of water attached to his music stand that he used to moisten the reed during concerts; he'd dip his finger in it and run it along the reed, and he'd do this maybe a hundred times on a typical night.
"Single- and double-reed players keep their reeds moist because they respond better that way.  Reeds are a natural material.  You can sand them all you like, but there will always be some rough places, and the water helps smooth them and maintain a more consistent surface.  I can tell you, and you can talk to 500 guys, who have played in some place dry like Aspen, and 500 of them will tell you it's a tremendous problem."
Addendum: I'll add this, which my father didn't say but is perhaps pertinent: it may be that there's no significant difference between soaking in water or soaking in saliva, but that the soaking itself is what's important.  If that's the case, you can imagine that it might be difficult to generate enough saliva to soak much of anything.
Comment: The question pertained to moistening reeds in a cup of water vs. with your own saliva, but your answer is really to the question "Why do we moisten reeds?".
Comment: @NReilingh: Seems to me the OP had two questions, the second one about why single-reed players don't soak their reeds with water.  My answer (really, my father's answer) addresses this question.  As for the OP's other question, I'll add an addendum to my answer.
Answer: Being a 2nd (out of 3) generation oboe player, I've asked (and been asked) this question from time to time.  [The most recent one was last year when my son started taking the oboe.]
The best answer I get is that about half of the oboist swear by soaking in water, and the other half swear by soaking in saliva.  The one thing they do agree upon is that there is a difference in how the reed plays if you soak it in different liquids. [My father used to swear by soaking his read in Vokda or Kirschwasser when he had a cold.]
Here are the facts that both sides acknowledge:

Saliva & Water have different densities.
The enzymes in saliva interact with the wood of the reed.
Gunk in the reed is not good

Proponents of saliva soaking will often use arguments such as

The increased density of the saliva changes the way the reed responds
Soaking in water and then switching to your mouth means the reed will change as you are playing it as the water is displaced by the saliva in your mouth.

The Opposing view (those who prefer water) argue

Saliva is gross
Reeds wear out faster when using saliva
You can't get all sides of each read using saliva [There is an opening between the reeds when you blow through it, so I don't see this one.]

Where is the truth?  [Warning, entering The Opinion Zone]
IMHO, all of these are true.  What it really comes down is what the player is used to, how they were trained, and (probably more importantly) how the reed is customized.  (Every serious double reed player ends up adjusting their reeds, even if they buy high-end pre-made ones.)
Concerning the "gunk": one thing my father did stumble upon in his 60+ years of playing the oboe was the importance of cleanliness to the survival of reeds.
First off, make sure you mouth is clean of any food before playing. [Brush your teeth just before playing!  I actually carry a toothbrush in my oboe case.]
Second, make sure you clean your reeds.  I like to clean mine under a mild stream of water from a faucet with tip pointing down so as to prevent damage and allowing water to enter the back.
My father uses an ultrasonic cleaner.  He ends up getting several times (~5x) more life out of the reeds he cleans with the ultrasonic cleaner vs. the ones he didn't.  I haven't found that much of a difference, but I never did play as much as him.  [There are also those who claim the frequency of the ultrasonics is important to how well it works.]


Font Awesome icons are not showing Impreza thme

Question: I got a client and She was looking for a WordPress website. I took the project and started the project on my server. Yesterday I completed the project and transfer the whole website to my client main domain which is gulugalmarketing.com.
Everything was working just fine on my server! but when I transferred the website I got an issue which is Font awesome icons are loading properly! AS you can see the website is showing a small square box instead of icons.
I tried to check out the console and it's giving the errors.

"Access to Font at been blocked by CORS policy"

I did try t replace the HTTPS to HTTP by using a plugin which is "Better search replace" but no luck as my client is using SSL.
Can somebody check this issue out and let me know.
Comment: Looks like the font resources not found on the server
Comment: Yes i was missing this link
Comment: Make sure you have included fontawesome css into your site.
Answer: Include Font awesome CSS link in your document file and then it works
<code><head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>
</code>
Answer: You should enqueue Font Awesome into your theme's function.php, like below:
<code>// Load Font Awesome
function enqueue_font_awesome() {

    // Font Awesome
    wp_enqueue_style ('fontawesome', 'https://use.fontawesome.com/releases/v5.2.0/css/all.css');

add_action( 'wp_enqueue_scripts', 'enqueue_font_awesome' );
</code>


rsyslog convert json to text on the fly

Question: I have application logging events in JSON format for later structured queries, etc. Now I have a task to log the same messages in plain text (CSV probably) and I really don't want to log each event twice in both formats.
Is it possible to convert within rsyslog ?
I have an option of tracing the output file and piping it to converter and then log with different tag, but that seems suboptimal.
Any other ideas ?
Thanks !
Answer: You might want to have a look at mmjsonparse.  It appears to do the sort of thing you want to do.  You'll need rsyslog 6.6 or higher (7 or higher is recommended).  The sample config found here explains it quite well:
# load needed modules
module(load="imuxsock") # provides support for local system logging
module(load="imklog") # provides kernel logging support
module(load="mmjsonparse") #for parsing CEE-enhanced syslog messages

# try to parse structured logs
action(type="mmjsonparse")

# define a template to print field "foo"
template(name="justFoo" type="list") {
    property(name="$!foo")
    constant(value="\n") #we'll separate logs with a newline
}

# and now let's write the contents of field "foo" in a file
action(type="omfile"
    template="justFoo"
    file="/var/log/foo")

You'll still need to use logger or some module of whatever language your application is written in which interacts with rsyslog to write the messages...
# logger '@cee: {"foo":"bar"}'
# cat /var/log/foo
bar

If you send an unstructured log, or invalid JSON, nothing will be added to the log.
Comment: thanks ! this is great for predefined set of fields. Is there way to extract values only from dynamic set of fields ?
Comment: Probably best to introduce some form of structure so that the template knows what to extract.  Log messages should be relatively consistent if possible.  You may want to look at projects like [Lumberjack](https://fedorahosted.org/lumberjack/) which try define a best-practice event syntax for JSON formatted log entries.  But if your fields differ considerably from each other, I can imagine that the resultant config could become quite considerable!
Comment: this is exactly the reason I'm using JSON, to store logs in ELK :). I just wanted rsyslog to catch up when format is changed, but reconfiguring field set is fine too I think. Thank you !

rsyslog convert json to text on the fly


More concise form to set a read-only `@property` in python

Question: I know that if I want to set a read-only property in python I can do the following in a class:
class Foo(object):

    @property
    def foo(self):
        return self._foo

but it seems still too long (3/4 lines) in the case I have many of properties as simple as this one.
I know I could code a system myself to create read-only properties, but I would like to avoid to reinvent the wheel.
I am wondering if there are special functions that can do something like:
create_ro_property(self,"foo","_foo",42) # where 42 is the initial value of 42

This would create a read-only property foo that can be set internally to the object via _foo.
any ideas?
Answer: You could do it as follows:
class Foo(object):

    foo = property(lambda self: self._foo)

The @ is just syntactic sugar and a lambda can replace such a trivial def for creating the getter.
Note that this doesn't set the initial value of 42; you would still have to do that e.g. in __init__. Alternatively, perhaps you could do something clever in __getattr__ to return None for missing attributes starting with _, then make the return value self._foo or 42 (or, if 0 is a valid value, 42 if self._foo is None else self._foo).


Mysql data type for multiple decimal points

Question: I need to store some data in the following format:
1.2
1.2.1
1.2.2
1.3
etc..
I highly suspect that I must use varchar for this, but my guy says that it's still some kind of int.
It's for a catalogue hierarchy system.
Google is leading me no where..
Anyone done this before?
Comment: a wild guess, you are sorting on this column?
Answer: I don't think there is a numeric format that works  for these.
Abusing a DECIMAL won't lead anywhere, as you won't be able to tell apart 1.2.11 and 12.1.1.
I would store them in a VARCHAR.
Answer: If you need to store "1.2.2" then its a string. If you had a table of "IDs" where you could have "itemID" and "ParentID" then you could do it with integers as then the Uid, for 1.2 could be the number 23, ergo would be integers, but it doesnt save you as you would then need recursive to find the full path.
Answer: When you have many of this numbers and set of numbers can be long, you can use some dictionary in other table to handle it, and carry only pointer.
But i think too VARCHAR is optimal when you DONT WANT search over this numbers eg. where second number is 13, then my solution is better.