Is it worth running nessus as well as OpenVAS?

Question: Apparently OpenVAS originated as a fork of Nessus.  It is very easy to install and use OpenVAS because it's, well, open.  However, am I kidding myself if I just use that instead of Nessus?  Should I be using both, or if I use Nessus then is OpenVAS surplus to requirements?
To break it down into non-subjective sub-questions:
 * Is openvas a superset or subset of nessus?
 * Is one updated more often than the other?
 * Does one have a bigger vulnerability database than the other?
 * ...or are there other qualitative differences that I may be missing?
Answer: I personally much prefer Nessus..
It has a better feel and management, not to mention the updates offered..
Furthermore the control of nessus via updates and usage i believe is more professional because of the proprietary model. its just easier to use
<code>OpenVAS server is a forked development of Nessus 2.2.
The fork happened because the major development (Nessus 3) changed to a
proprietary license model and the development of Nessus 2.2.x is practically
closed for third party contributors. OpenVAS continues as Free Software under
the GNU General Public License with a transparent and open development style.
</code>
Although OpenVAS was forked, since then 2008, OpenVAS has changed into something new
with new features and functions not offered in Nessus..
For a simple desktop version assesment (1 user - small amounts of checking) - i would go with Nessus
However because OpenVAS is an open source product, people are saying its scanning abilities are a little further along than nessus.. ( i cant prove this, nor do i really believe it :P )
In a nutshell choose...
quicker updates -> good scanning  = Nessus
slower updates -> better scanning  = OpenVAS
Hope this helps :D
Comment: Did this help???
Answer: It is a good idea to have the ability to use both: you can tune either Nessus or OpenVAS to run 'fast scans', and given that OpenVAS is free, this allows you to run numerous on-demand scans of any kind.
Nessus may be preferred/required by some compliance auditors you interact with in the future. Some of this may be rooted in logic, but because of the open-source nature of OpenVAS combined with the common difficulty that the general security-admin public has in installing/using/maintaining it, some auditors may view it negatively without any application of logic to their conclusion.
The two-role nature becomes more relevant considering that Nessus has a cloud offering now: so you truly have the classic "expensive, easy-to-use/maintain, commercial offering" versus the "free, harder-to-use/maintain, open-source version". Both definitely can be used together, and in a production environment this could translate into

running various multiple, recurring free OpenVAS scans for free to
tighten your system.
selected and fewer Nessus paid scans that show to the world that
your system has been properly tightened.
between Nessus "proof-to-the-world" scans you can run OpenVAS scans
on a recurring, scheduled basis to maintain confidence in the target system's
current vulnerability landscape.


TLS trace: SSL_connect:error in SSLv2/v3 read server hello A

Question: I am trying to query AD for users and tried every options available but no success
Operating System = CentoS7.5
Packages = Openldap, ldapsearch
Microsoft Active Directory
my command
ldapsearch -x -LLL -D "uid=abc,ou=Distribution Lists,dc=abc,dc=local" -H "ldaps://xxxx:3268" "uid=abc" -d 1

Following is debug trace
ldap_url_parse_ext(ldaps://xxxx:3268)
ldap_create
ldap_url_parse_ext(ldaps://xxxx:3268/??base)
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP xxxx:3268
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying x.x.x.x:3268
ldap_pvt_connect: fd: 3 tm: -1 async: 0
attempting to connect:
connect success
TLSMC: MozNSS compatibility interception begins.
tlsmc_intercept_initialization: INFO: entry options follow:
tlsmc_intercept_initialization: INFO: cacertdir = `/etc/openldap/certs'
tlsmc_intercept_initialization: INFO: certfile = `(null)'
tlsmc_intercept_initialization: INFO: keyfile = `(null)'
tlsmc_convert: INFO: trying to open NSS DB with CACertDir = `/etc/openldap/certs'.
tlsmc_open_nssdb: INFO: trying to initialize moznss using security dir `/etc/openldap/certs` prefix ``.
tlsmc_open_nssdb: INFO: initialized MozNSS context.
tlsmc_convert: INFO: trying with PEM dir = `/tmp/openldap-tlsmc-certs--8586FAF3B8E91EA51970C3CB5BDAEEAA9CEBC923901B87924ECD0CBBCD8F9C66'.
tlsmc_convert: INFO: using the existing PEM dir.
tlsmc_convert: WARN: extracted cert file is not present.
tlsmc_convert: WARN: extracted key file is not present.
tlsmc_intercept_initialization: INFO: altered options follow:
tlsmc_intercept_initialization: INFO: cacertdir = `/tmp/openldap-tlsmc-certs--8586FAF3B8E91EA51970C3CB5BDAEEAA9CEBC923901B87924ECD0CBBCD8F9C66/cacerts'
tlsmc_intercept_initialization: INFO: certfile = `(null)'
tlsmc_intercept_initialization: INFO: keyfile = `(null)'
tlsmc_intercept_initialization: INFO: successfully intercepted TLS initialization. Continuing with OpenSSL only.
TLSMC: MozNSS compatibility interception ends.
TLS trace: SSL_connect:before/connect initialization
TLS trace: SSL_connect:SSLv2/v3 write client hello A
TLS trace: SSL_connect:error in SSLv2/v3 read server hello A
TLS: can't connect: .
ldap_err2string
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

I tried by changing values in /etc/openldap/ldap.conf
First added
TLS_REQCERT never

then
TLS_REQCERT allow

then set below as mentioned here but no success
ldap ssl v2 v3 can't read server hallo A
TLS_PROTOCOL_MIN 3.3

Rebooted my server too but no success.
if i run with debug level d 2, last lines are like
tls_read: want=7 error=Connection reset by peer
TLS: can't connect: .
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

my only intentions is to run ldapsearch
EDIT:
as suggested @fission i changed port and Now i am getting below
>> cat /etc/openldap/ldap.conf
#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

BASE    dc=abc,dc=local
URI     ldaps://xxx:3269

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

#TLS_CACERTDIR  /etc/openldap/certs
#HOST you-adc1
#PORT 3268
TLS_REQCERT never

#TLS_PROTOCOL_MIN 3.3

# Turning this off breaks GSSAPI used with krb5 when rdns = false
SASL_NOCANON    on

Trace:
[root@x ~]# ldapsearch -x -LLL -D "uid=abc,ou=Distribution Lists,dc=xyz,dc=local" -H "ldaps://xxx:3269" "uid=abc" -d 1
ldap_url_parse_ext(ldaps://xxx:3269)
ldap_create
ldap_url_parse_ext(ldaps://xxx:3269/??base)
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP xxx:3269
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying x.x.x.x:3269
ldap_pvt_connect: fd: 3 tm: -1 async: 0
attempting to connect:
connect success
TLSMC: MozNSS compatibility interception begins.
tlsmc_intercept_initialization: INFO: entry options follow:
tlsmc_intercept_initialization: INFO: cacertdir = `(null)'
tlsmc_intercept_initialization: INFO: certfile = `(null)'
tlsmc_intercept_initialization: INFO: keyfile = `(null)'
tlsmc_convert: INFO: trying to open NSS DB with CACertDir = `(null)'.
tlsmc_convert: INFO: cannot open the NSS DB, expecting PEM configuration is present.
tlsmc_intercept_initialization: INFO: altered options follow:
tlsmc_intercept_initialization: INFO: cacertdir = `(null)'
tlsmc_intercept_initialization: INFO: certfile = `(null)'
tlsmc_intercept_initialization: INFO: keyfile = `(null)'
tlsmc_intercept_initialization: INFO: successfully intercepted TLS initialization. Continuing with OpenSSL only.
TLSMC: MozNSS compatibility interception ends.
TLS trace: SSL_connect:before/connect initialization
TLS trace: SSL_connect:SSLv2/v3 write client hello A
TLS trace: SSL_connect:SSLv3 read server hello A
TLS certificate verification: depth: 0, err: 20, subject: , issuer: /DC=local/DC=xxx/CN=xxx-root-CA
TLS certificate verification: Error, unable to get local issuer certificate
TLS trace: SSL_connect:SSLv3 read server certificate A
TLS trace: SSL_connect:SSLv3 read server key exchange A
TLS trace: SSL_connect:SSLv3 read server certificate request A
TLS trace: SSL_connect:SSLv3 read server done A
TLS trace: SSL_connect:SSLv3 write client certificate A
TLS trace: SSL_connect:SSLv3 write client key exchange A
TLS trace: SSL_connect:SSLv3 write change cipher spec A
TLS trace: SSL_connect:SSLv3 write finished A
TLS trace: SSL_connect:SSLv3 flush data
TLS trace: SSL_connect:SSLv3 read finished A
ldap_open_defconn: successful
ldap_send_server_request
ber_scanf fmt ({it) ber:
ber_scanf fmt ({i) ber:
ber_flush2: 76 bytes to sd 3
ldap_result ld 0x559d9b078a70 msgid 1
wait4msg ld 0x559d9b078a70 msgid 1 (infinite timeout)
wait4msg continue ld 0x559d9b078a70 msgid 1 all 1
** ld 0x559d9b078a70 Connections:
* host: xxx  port: 3269  (default)
  refcnt: 2  status: Connected
  last used: Sat Oct 20 16:46:31 2018

** ld 0x559d9b078a70 Outstanding Requests:
 * msgid 1,  origid 1, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x559d9b078a70 request count 1 (abandoned 0)
** ld 0x559d9b078a70 Response Queue:
   Empty
  ld 0x559d9b078a70 response count 0
ldap_chkResponseList ld 0x559d9b078a70 msgid 1 all 1
ldap_chkResponseList returns ld 0x559d9b078a70 NULL
ldap_int_select
read1msg: ld 0x559d9b078a70 msgid 1 all 1
ber_get_next
ber_get_next: tag 0x30 len 16 contents:
read1msg: ld 0x559d9b078a70 msgid 1 message type bind
ber_scanf fmt ({eAA) ber:
read1msg: ld 0x559d9b078a70 0 new referrals
read1msg:  mark request completed, ld 0x559d9b078a70 msgid 1
request done: ld 0x559d9b078a70 msgid 1
res_errno: 0, res_error: <>, res_matched: <>
ldap_free_request (origid 1, msgid 1)
ldap_parse_result
ber_scanf fmt ({iAA) ber:
ber_scanf fmt (}) ber:
ldap_msgfree
ldap_search_ext
put_filter: "uid=abc"
put_filter: default
put_simple_filter: "uid=abc"
ldap_send_initial_request
ldap_send_server_request
ber_scanf fmt ({it) ber:
ber_scanf fmt ({) ber:
ber_flush2: 70 bytes to sd 3
ldap_result ld 0x559d9b078a70 msgid -1
wait4msg ld 0x559d9b078a70 msgid -1 (infinite timeout)
wait4msg continue ld 0x559d9b078a70 msgid -1 all 0
** ld 0x559d9b078a70 Connections:
* host: xxx  port: 3269  (default)
  refcnt: 2  status: Connected
  last used: Sat Oct 20 16:46:31 2018

** ld 0x559d9b078a70 Outstanding Requests:
 * msgid 2,  origid 2, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x559d9b078a70 request count 1 (abandoned 0)
** ld 0x559d9b078a70 Response Queue:
   Empty
  ld 0x559d9b078a70 response count 0
ldap_chkResponseList ld 0x559d9b078a70 msgid -1 all 0
ldap_chkResponseList returns ld 0x559d9b078a70 NULL
ldap_int_select
read1msg: ld 0x559d9b078a70 msgid -1 all 0
ber_get_next
ber_get_next: tag 0x30 len 168 contents:
read1msg: ld 0x559d9b078a70 msgid 2 message type search-result
ber_scanf fmt ({eAA) ber:
read1msg: ld 0x559d9b078a70 0 new referrals
read1msg:  mark request completed, ld 0x559d9b078a70 msgid 2
request done: ld 0x559d9b078a70 msgid 2
res_errno: 1, res_error: <000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1>, res_matched: <>
ldap_free_request (origid 2, msgid 2)
ldap_parse_result
ber_scanf fmt ({iAA) ber:
ber_scanf fmt (}) ber:
ldap_err2string
Operations error (1)
Additional information: 000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1
ldap_msgfree
ldap_free_connection 1 1
ldap_send_unbind
ber_flush2: 7 bytes to sd 3
TLS trace: SSL3 alert write:warning:close notify
ldap_free_connection: actually freed

Comment: Just wondering, did you try using port 3269? Normally if doing "direct" SSL (instead of `STARTTLS`) you should use port 3269.
Comment: @fission as suggested i change port and now getting error  (trace is in main)
ldap_err2string
Operations error (1)
Answer: By changing the port to 3269, it seems you are now connecting to the LDAPS server, which is good. However, the authentication piece isn't completing. You can tell that from this error
res_errno: 1, res_error: <000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1>, res_matched: <>
You need to specify either -w passwd or -W (which will prompt for a password).
The other thing I found necessary was to specify a search base (-b option).
A complete command which worked here:
ldapsearch -x -LLL -d 1 \
  -D cn=user1,cn=users,dc=fj,dc=test -W \
  -H ldaps://winders.fj.test:3269 \
  -b dc=fj,dc=test \
  cn=user1

Comment: thanks its working now, previously i tried with -b too but port changing helps.


Pegar valor que iria para o ID e colocar em outro local e salvar no banco de dados

Question: Desejo MONITORAR o movimento do usuário a partir do APP Android, que estará configurado com o link do meu painel.
Tenho o seguinte código:

---------------------------------------------------------------------

    var geocoder;
var map;
var marker;

//PARTE PRINCIPAL
  function initialize() {
    var latlng = new google.maps.LatLng(-18.8800397, -47.05878999999999);
    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("mapa"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
    });

    marker.setPosition(latlng);
}

//PARTE 000001
if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){ // callback de sucesso
        // ajusta a posição do marker para a localização do usuário
        marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    },

    function(error){ // callback de erro
       alert('Para um melhor desempenho nas entregas, ative a sua localização!');
       console.log('Erro ao obter localização.', error);
    });
} else {
    console.log('Navegador não suporta Geolocalização!');
}
//**************************
//**************************

//PARTE 00002
window.onload = function() {
  var startPos;
  var geoOptions = {
  timeout: 10 * 1000,
  maximumAge: 5 * 60 * 1000
  }

  var geoSuccess = function(position) {
    startPos = position;
    document.getElementById('startLat').innerHTML = startPos.coords.latitude;
    document.getElementById('startLon').innerHTML = startPos.coords.longitude;
  };

  navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
};

//PARTE 00003
//ATUALIZAR NO BANCO DE DADOS
function Atualiza_Posicao(){

$.ajax({
    data: {"lat": + POSICAO-LAT-AQUI, "lng": + POSICAO-LNG-AQUI},
        type:'POST',
        dataType: 'json',
        url:"atualizar-posicao.php"});
        //******************

}

//atualiza o mapa a cada segundo predefinido
function foo() {
    //Colocar as funções aqui
    Atualiza_Posicao();

}
setInterval(foo, 4000);

//****************************************************

---------------------------------------------------------------------

Na "//PARTE 00002" do código tem isso:

document.getElementById('startLat').innerHTML = startPos.coords.latitude;
    document.getElementById('startLon').innerHTML = startPos.coords.longitude;

Ao invés de mostrar o resultado disso aí na DIV, eu quero salvar no banco de dados a LATITUDE e a LONGITUDE, mas não tô conseguindo.
No caso, o resultado seria jogado para a "//PARTE 00003", mais precisamente em "POSICAO-LAT-AQUI" e "POSICAO-LNG-AQUI"

    //ATUALIZAR NO BANCO DE DADOS
    function Atualiza_Posicao(){

    $.ajax({
        data: {"lat": + POSICAO-LAT-AQUI, "lng": + POSICAO-LNG-AQUI},
            type:'POST',
            dataType: 'json',
            url:"atualizar-posicao.php"});
            //******************

    }
Comment: Na pergunta apenas coloque conteúdo e contextualização técnica. Caso precise fazer contextualizações sociais use o campo de comentários.
Answer: Se entendi corretamente, você precisa enviar os dados que estão nos campos mencionados na requisição:
data: { lat: POSICAO-LAT-AQUI, lng: POSICAO-LNG-AQUI }
É possível resgatar os valores que deseja após ter inserido os mesmos em algum ponto anterior do seu fluxo como localStorage, sessionStorage, variável onde alguns pontos do código possuam acesso em comum, algum campo escondido na página etc. Apenas como exemplo, podemos fazer isso na sua função geoSuccess (que se entendi corretamente, é o ponto onde temos os dados desejados) utilizando sessionStorage:
  var geoSuccess = function(position) {
    startPos = position;
    sessionStorage.setItem('startLat', startPos.coords.latitude);
    sessionStorage.setItem('startLon', startPos.coords.longitude);
  };

E resgatamos antes de fazer o envio:
var startLat = sessionStorage.getItem('startLat');
var startLon = sessionStorage.getItem('startLon');
Ao final do fluxo, teríamos o objeto abaixo:
data: { lat: startLat, lng: startLon }
Você também pode resgatar os dados dos elementos que populou anteriormente e usá-los durante o envio:
var startLat = document.getElementById("startLat").textContent
vat startLon = document.getElementById("startLon").textContent
Lembre-se de que sessionStorage (caso use) vai manter os dados na sessão atual, então caso precise dados atualizados da mesma sessão, sobrescreva os valores anteriores para não ter dados antigos sendo enviados ou limpe-os em algum ponto.
Espero ter ajudado de alguma forma.
Comment: Ruan, ele quer salvar num banco de dados, tem até um ajax e tag php na pergunta, não no armazenamento local
Comment: @RicardoPontual sim, o que respondi foi como *resgatar os valores que existem em um ponto do código em outro ponto* para envio posterior, apenas o exemplo que dei foi usando `sessionStorage` como um dos caminhos para continuar tendo acesso aos dados que precisam ser enviados depois. Ao final da resposta coloquei como ficaria o resgate posterior do próprio sessionStorage e envio na requisição ajax. Edito minha resposta caso não tenha ficado claro, sem problemas.
Comment: Muito obrigado, @RuanMontelo. Era isso mesmo!


De uma tabela para outra tabela html

Question: Tenho duas tabela em uma página HTML que é o seguinte:
Uma com as minhas disciplinas selecionadas.
Outra com a lista de disciplinas pra selecionar.
PS: Estou apenas estudando, não estou usando banco de dados nem algo do tipo.
Então, as tabelas estão nesse estilo:

A lógica é a seguinte:
Vou clicar no checkbox, e, ao clicar no checkbox, a disciplina marcada vai sumir de baixo e vai pra tabela de cima.
Minha dúvida é como vou saber a linha e a coluna do checkbox atual selecionado.
Porque quero um código dinâmico, que sirva pra cada checkbox, e não criar uma função javascript pra cada checkbox.
A partir de uma só ele saber a linha, coluna e os seus valores pra adicionar na de cima.
Entendem?
Andei pesquisando, já aprendi a inserir as linhas, OK, mas pra pegar os valores e jogar na de cima está complicando.
Agraeço a todos pela ajuda. Eu tenho mais ou menos a lógica, que é pegar a linha da checkbox e guardar em variáveis os valores da carga horária, período e professor e adicionar na primeira linha da tabela de cima.
Alguém pode me dar dicas?
Obr.
Comment: Não estou conseguindo ver a imagem que postou, mas acredito que você precise apenas fazer um appendChild na outra tabela. opcionalmente, você poderia adicionar um evento de drag'n drop.
Answer: Para saberes qual o tr a que essa checkbox pertence tens de ir procurar nos elementos pai dessa checkbox até chegares a um tr. No jQuery isso pode ser feito com o .closest('tr') e no MooTools com o .getParent('tr'). Para fazer isso com JavaScript nativo podes fazer um loop que continua até encontrar um elemento com o tagName que queres. Um exemplo de tal função seria:
function getParent(el, tagName) {
  tagName = tagName.toLowerCase();
  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }
  return null;
}

Agora precisas uma função que troque de posição a linha clicada. Um exemplo seria:
function fn(e) {
    var trPai = getParent(this, 'tr')
    if (this.checked) tabelaDestino.appendChild(trPai);
    else tabelaOrigem.appendChild(trPai);
}

Exemplo online: http://jsfiddle.net/9qeL40ax/
Comment: Obrigado pela solução. Estou testando e verificando se resolvo o problema. Thanks.
Answer: Neste caso, a maneira mais fácil é atribuir um evento a todos os checkbox, neste evento você move toda a linha para a tabela desejada.

//consultando todos os input to type checkbox na pagina
//caso a sua pagina possua mais inputs deste tipo, você deve tornar o filtro abaixo mais especifico.
var adicionar = document.querySelectorAll("input[type='checkbox']");

//consultando as tabelas que irão armazenar as disciplinas disponiveis e as que o aluno está matriculado.
var matriculado = document.querySelector("#matriculado tbody");
var disponiveis = document.querySelector("#disponiveis tbody");

//definindo o evento que irá mover a linha, é importante instanciar apenas um evento para todos os checkbox.
var adicionarOnClick = function () {
    //caso o checkbox esteja marcado, mova a linha para a tabela de matriculados, caso contrario para a tabela de disciplinas disponiveis.
    var escopo = this.checked ? matriculado : disponiveis;
    //this é o checkbox que foi clickado, o parentNode dele é a celula atual, e o parentNode da celula é a linha (arvore).
    escopo.appendChild(this.parentNode.parentNode);
};

//registrando o evento criado acima para todos os checkbox.
for (var indice in adicionar) {
    adicionar[indice].onclick = adicionarOnClick;
}
table {
    box-shadow: 0px 0px 10px black;
    margin-bottom: 20px;
    width: 100%;
}

table th, table td {
    border: 1px solid black;
}

.centro {
    text-align: center;
}

.direita {
    text-align: right;
}

input[type='checkbox'] {
    float: left;
}

            Pedidos de Matricula

            Disciplina
            Carga Horaria
            Periodo
            Professor

            Selecione as Disciplinas

            Disciplina
            Carga Horaria
            Periodo
            Professor

            <input type="checkbox" name="adicionar"  />Calculo 1
            90
            2°
            Marcos Alexandre

            <input type="checkbox" name="adicionar"  />Algebra Linear
            45
            3°
            Pedro Alves

            <input type="checkbox" name="adicionar"  />Fisica II
            45
            3°
            Paulo Coelho

            <input type="checkbox" name="adicionar"  />Metodologia Cientifica
            30
            2°
            Raul Rabelo

Segue o HTML completo com script e style, note que o script está no final da pagina.

            Pedidos de Matricula

            Disciplina
            Carga Horaria
            Periodo
            Professor

            Selecione as Disciplinas

            Disciplina
            Carga Horaria
            Periodo
            Professor

            <input type="checkbox" name="adicionar"  />Calculo 1
            90
            2°
            Marcos Alexandre

            <input type="checkbox" name="adicionar"  />Algebra Linear
            45
            3°
            Pedro Alves

            <input type="checkbox" name="adicionar"  />Fisica II
            45
            3°
            Paulo Coelho

            <input type="checkbox" name="adicionar"  />Metodologia Cientifica
            30
            2°
            Raul Rabelo

Comment: Olá, Toby. Muito obrigado pela paciência pra fazer esta solução. É realmente isso que eu quero, pelo que executei no trecho de código. O problema é o seguinte: Quando vou juntar tudo na página,ele não dá certo. A princípio para testes, estou colocando os scripts e css na mesma página, usando  e  como que vc mandou. O css deu certo, mas o script não. tenho que botar em alguma função? o que faço?
Comment: Caso esteja usando o Opera ou Chrome, abra as ferramentas de desenvolvimento(`F12`) e olhe a aba `Console`, lá você pode ver se ocorreu algum erro em tempo de execução no JS.
Comment: Opa. Uso o Firefox.
Comment: É possível você juntar tudo em um código só? a página completa que vc fez? pq não sei se é problema no meu bloco de código ao fazer a integração ou o navegador. Testei no internet explorer e permiti o script. não rodou
Comment: inclui um exemplo com script e style direto no HTML, aqui funcionou normal. observe que o script está no final da pagina.
Comment: Cara, é justamente isso que eu queria! Agora só adaptar a minha solução! Não sei como agradecer. MUITO OBRIGADO MESMO! VALEUS!

De uma tabela para outra tabela html


How do I re-attach AJAX behaviours to a managed_file field?

Question: I currently have a form which is generated by the FAPI via an jQuery AJAX call, and then is inserted into the DOM.
This works fine, but the problem is that managed_file field within the newly generated form have lost all their AJAX behaviours. I've tried a couple of things to try get Drupal to reattach the behaviours after the form is generated but I'm having no luck.
Here's my code for retrieving and inserting the new form into the DOM:
$.ajax({
type: 'POST',
url: '/example-get-form',
dataType: 'json',
data: 'get=1',
success: function(response){

  //insert new form into DOM
  var newForm = response.data.form;
  $('.profile-form.edit').append(newForm);
  Drupal.attachBehaviors();
}
});

As you can see from the frontend code, we retrieve the rendered form HTML via AJAX and then insert it into our container div with the selector ".profile-form.edit". The form is rendered and inserted into the DOM correctly, but the problem is that the dyanmic form's managed_file field can either be empty or contain an image, so both the "Upload" and "Remove" buttons needs to have their AJAX behaviours reattached.
Here's the code for generating the form via the callback URL called from my jQuery script:
//generate form and send via JSON
$response['data']['form'] = drupal_get_form('mymodule_example_form');
$response['data']['form'] = render($response['data']['form']);

return drupal_json_output($response);
drupal_exit();

Any help to put me on the right track would be greatly appreciated!
Comment: Show full code like how you're retrieving the form in fronend and how you're generating the form in the backend.
Comment: Post the form generation code as well i.e. mymodule_example_form function.
Answer: The main problem is that you're not loading the form in Drupal way in the AJAX requests. When you use the normal jQuery ajax to load the form, then the necessary actions(Generating new scripts and re-attaching the behaviors) won't happen.
So you should follow the below process to achieve it.

Create a page with ajax Link/button - clicking on it should load the form(This
may change based on your need)
Create form generation callback
Create a ajax callback which will returns the form

Below is the complete example module which loads the form with the managed file field using ajax.
<?php

/**
 * @file
 * Provides File module pages for testing purposes.
 */

/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();

  $items['file/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access content'),
  );
  $items['ajax/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_page',
    'access arguments' => array('access content'),
  );
  $items['ajax/form'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_form',
    'access arguments' => array('access content'),
  );

  return $items;
}

/**
 * Generates the Test page.
 */
function file_ajax_page() {
    // Make sure Drupal Ajax framework javascript is around.
  drupal_add_library('system', 'drupal.ajax');
  $output = '';
  // Generate a Ajax Link to load the form.
  $output .= l(t('Delete'), 'ajax/form', array('attributes' => array('class' => 'use-ajax')));
  // Specify the container for the form.
  $output .= '

';
    return $output;
}

/**
 * Returns the processed file form.
 */
function file_ajax_form() {
    $commands = array();

    // Treat them in Drupal way to load the form in AJAX, so that all the necessary scripts will be loaded.
  $commands[] = ajax_command_html('.form-container', drupal_render(drupal_get_form('test_form')));
  ajax_deliver( array(
    '#type' => 'ajax',
    '#commands' => $commands,
  ));
}

/**
 * Form constructor for testing a 'managed_file' element.
 *
 * @see file_module_test_form_submit()
 * @ingroup forms
 */
function test_form($form, &$form_state, $tree = TRUE, $extended = FALSE, $default_fid = NULL) {
  $form['#tree'] = (bool) $tree;

  $form['nested']['file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Managed file'),
    '#upload_location' => 'public://test',
    '#progress_message' => t('Please wait...'),
    '#extended' => (bool) $extended,
    '#size' => 13,
  );
  if ($default_fid) {
    $form['nested']['file']['#default_value'] = $extended ? array('fid' => $default_fid) : $default_fid;
  }

  $form['textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Type a value and ensure it stays'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

/**
 * Form submission handler for file_module_test_form().
 */
function test_form_submit($form, &$form_state) {
  if ($form['#tree']) {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['nested']['file']['fid'] : $form_state['values']['nested']['file'];
  }
  else {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['file']['fid'] : $form_state['values']['file'];
  }
  drupal_set_message(t('The file id is %fid.', array('%fid' => $fid)));
}

This way Drupal will do all the works for you if you specify what/how do you want:)
I took File Test module in the core as the base for this example.
Comment: great comprehesive explanation :) thanks a lot for your time. Using the proper Drupal AJAX method of sending the form to the frontend, the managed_file field is now working correctly.


Como passar um índice para o elemento de acordo com a posição dele?

Question: Estou carregando dados de uma api externa com json e jquery,a cada solicitação ajax
uma div com a classe item,uma div com a classe more_info e um botão ver mais, que carrega o resto dos dados, e as divs criadas recebem os dados do json. A partir da linha 28 o jquery esconde a div more_info, e o botão criado com a classe bt_ver_mais recebe a função toggle, para abrir o resto da informação na mesma tela. O problema é que quando eu clico em um dos botões gerados para ver mais, todos os botões executam a função toggle, abrindo o resto das informações de todas as divs,sendo óbvio, já que todos tem a mesma classe, mas eu não quero que isso aconteça, eu quero que ao clicar em botão, ele abra a div .more_info da div dele, e não de todas as outras divs
//Carrega dados de um arquivo json
var elemento;
  $(document).on('click','#bt_prosseguir', function(){
    $.getJSON('https://upvagasweb.000webhostapp.com/api_upvagas/php_json_access/access_json_aparecida.php', function(result){
        elemento = "
";
        $.each(result, function(i, valor){
        elemento += "
";
        elemento += "
";
        elemento += "";
        elemento += "
";
        elemento += "
"+valor.setor+"
";
        elemento += "
"+valor.empresa+"
";
        elemento += "
 Por "+valor.vinculo+"
";
        elemento += "
"+valor.cidade+" - SP
";
        elemento += "
Ver mais
";
        elemento += "
";
        elemento += "
Benefícios:"+valor.beneficios+"
";
        elemento += "
Remuneração"+valor.remuneracao+"
";
        elemento += "
Nível de estágio:"+valor.nivel_estagio+"
";
        elemento += "
Inscrição:"+valor.processo_seletivo+"
";
        elemento += "
";
        //elemento += "Link:"+valor.contato+"
";
        elemento += "
";
        });
        $('#feed_vagas').html(elemento);

        //esconde a div more_info
          $('.more_info').hide();
          $('.bt_ver_mais').click( function(){
            $('.more_info').toggle();
        });
    });
});

/*$(document).on('deviceready', function(){
    load_feed();
 });*/

Answer: Altere o evento click para buscar apenas a div .more_info que possui o mesmo ancestral com a classe .item do .bt_ver_mais clicado:
$('.bt_ver_mais').click( function(){
  $(this) // elemento clicado
  .closest('div.item') // ancestral comum
  .find('.more_info') // busca o elemento que será exibido
  .toggle(); // exibe/oculta o elemento
});

Exemplo:

//Carrega dados de um arquivo json
var elemento;
$(document).on('click','#bt_prosseguir', function(){
     elemento = "
";
     for(var x=0; x<5; x++){
        elemento += "
";
        elemento += "
";
        elemento += "";
        elemento += "
";
        elemento += "
10,00
";
        elemento += "
20,00
";
        elemento += "
 Por 5,00
";
        elemento += "
SP - SP
";
        elemento += "
Ver mais
";
        elemento += "
";
        elemento += "
Benefícios:30,00
";
        elemento += "
Remuneração40,00
";
        elemento += "
Nível de estágio:50,00
";
        elemento += "
Inscrição:60,00
";
        elemento += "
";
        //elemento += "Link:"+valor.contato+"
";
        elemento += "
";
     }
     $('#feed_vagas').html(elemento);

     //esconde a div more_info
       $('.more_info').hide();
       $('.bt_ver_mais').click( function(){
         $(this)
         .closest("div.item").find(".more_info")
         .toggle();
      });
});

<button id="bt_prosseguir">Prosseguir</button>

Comment: Muito obrigado Sam, resolveu meu problema de primeira, eu estava quebrando demais a cabeça com isso kkk, tentei até o metódo eq() do jquery, valeu!


Integration involving natural logarithm

Question: I tried possible way of getting the integral of the following integrand:
$$\int_0^{\infty} \frac{\ln\left(x+\frac{1}{x}\right)}{1+x^2}~dx$$
Firstly, I tried to write $\ln\left(x+\frac{1}{x}\right)$ as $\ln(x^2+1)-\ln(x)$ and tried to apply biparts but couldn't take it to its destination solution.
Secondly, I tried to substitute $t=x+\frac{1}{x}$ and proceeded, but couldn't solve further.
Nothing seems to work. This was a question from my exam. I don't understand how I'm supposed to solve this question in a short time when I can't solve it at home. I'm guessing there has to be a short but smart solution that is pretty much not striking me.
Comment: Put $tan ^{-1} x = z $
Answer: First step is put $x=\tan (t) $ that substitution  gets rid of the denominator . Then after that we have the integral as $\int _0 ^{\frac {\pi}{2}} \log ( 1+\tan^2 (t))-\log(tan (t)) $ now use $1+tan^2(t)=sec^2 (t)$ . Now as in $0-\pi/2$ sec is positive we can write $\ln (\sec^2 (t))=2\ln (\sec (t))$ . Thus the integral is $\int _0 ^{\frac{\pi}{2}} log (\frac{\sec(t)}{\tan (t)})=\int _0 ^{\frac {\pi}{2}}-\log(\sin (t)) $ . Now I am sure you can handle this integral. The result should be $\frac {\pi}{}\log (2) $
Comment: I think the result should be $\pi \ln(2)$.
Comment: @Archis Welankar   Thanks man this helped ...but u suggested to write 2 ln(sec(x)) so in the next step It should be 2ln(sec(x))-ln(tan(x)). But i still solved as u suggested and the answer's coming out to be πln2. Thanks a lot btw
Comment: @projectilemotion thanks for the solution. I actually took the long way but your solution made me remember some important stuff I had forgotten.

Integration involving natural logarithm


Best way to model a regression with proportions as dependent variable?

Question: Consider a simple model for school graduation: there is school $i = 1,2,..., N$, each getting $y_i$ of $n_i$ students graduated. Assume $y_i\sim Binomial(n_i, \theta_i)$ where $\theta_i$ is the probability of graduation of each student at school $i$.
What is the best way to model the relationship between the individual probability of graduating $\theta_i$ and the observed characteristics $X_i$ for each school?
One possibility is to model the probability $\theta_i = X_i\beta$. Are there better ways?
Comment: There are several binomial regression models within the GLM framework. See for example, the tags for [logistic](http://stats.stackexchange.com/questions/tagged/logistic)-regression and [probit](http://stats.stackexchange.com/questions/tagged/probit)-regression (though there are other possibilities still, such as complementary-log-log models and even the identity link in some cases). You might get some value out of the wikipedia articles [Logistic regression](https://en.wikipedia.org/wiki/Logistic_regression), ... ctd
Comment: ctd... [Generalized linear model](https://en.wikipedia.org/wiki/Generalized_linear_model) (including the "binomial" row of the big table and the section on [binary data](https://en.wikipedia.org/wiki/Generalized_linear_model#Binary_data) which discusses all four link functions I have mentioned) and [Probit model](https://en.wikipedia.org/wiki/Probit_model). Depending on how you want to model things (whether you want to look at your set of schools as fixed or samples from a larger population), you may want to look at generalized linear *mixed* models (GLMMs)/hierarchical models
Answer: Proportion is the mean value of the variable where 1 represents success and 0 represents failure. So I suspect data has already been aggregated to give you proportions. For example you might have information about school graduation proportion given predictor variables such as average school grade, average aptitude test results of the school and so on. So the best way would be to use logistic regression on non-aggregated  data (predicting graduation given the pupil grades and aptitude tests). You could model the effect of higher level units (schools) by using hierarchical logistic regression.
In any case, I don't see any justification to model probability itself. It really doesn't sound statistically (or philosophically).
Answer based on a question edit:
If you only have school level data and not individual data then you don't need hierarchical regression. Also logistic regression is a binomial regression with logistic link function (in the framework of generalized linear models). So you can implement your problem in the following way:
glm(proportion ~ x1+x2, family=binomial, weights=w)

Proportion is simply $y_i/n_i$. Weights are $n_i$ and $x_{1},x_{2}$ are explanatory variables on a school level.
To clarify even further I will provide a working example. Suppose we test an insecticide effectiveness dependent on dose and sex of an insect. There are 20 insects in every experimental batch:
dose <- rep(0:5, 2)

sex <- factor(rep(c("M", "F"), c(6, 6)))

dead <- c(1, 4, 9, 13, 18, 20, 0, 2, 6, 10, 12, 16)

We calculate mortality dependent on dose and sex of the insect with interaction term:
glm(dead/20 ~ sex*ldose,family=binomial, weights=rep(20,12))

Example works flawlessly. But if we specify equivalent set of weights in the following way:
glm(dead/20 ~ sex*ldose, family=binomial, weights=rep(19, 12))

Package provides an error message: non-integer #successes in a binomial glm! But you will see that results in both cases are the same as it should be. This is because relative weights in both cases are equivalent. Program gives a prudent warning since weights are usually $n_i$ and proportion is calculated as $y_i/n_i$. So if $n_iy_i/n_i $ is not an integer program produces a warning. But if you know what you are doing you can simply ignore the warning.
I hope that solves your problem.
Comment: The `r` code you have written does not work as family binomial does not accept proportions. Perhaps, you mean `glm(success ~ x1 + x2, weights=w)`.
Comment: I changed the text trying to clarifying the question. I think what I am looking for is a "hierarchical binomial model." Could you please expand on this in your answer. Thanks
Comment: Okay @mrb I edited an answer based on your edited question.
Comment: @mrb I have provided a working example in my question edit and explained why youu can ignore a program warning. Please don't forget to upvote if the answer solves your problem.
Comment: You should maybe replace `family=binomial` with `family=quasibinomial`


Pass attribute value to view from controller in angularjs

Question: I have a  tag with the following things:

I'm calling a REST API. After calling REST API, I get the values of src, height and width. How can I pass from controller to view in angularjs?
Answer: Yes.
To controll the src you need to use ngSrc directive:

To controll the style use ngStyle directive:
$scope.myStyle = {"width":"500px", "height":"500px"};

Comment: How about height and width?
Comment: I meant height and width for  tag
Comment: Want to solve another issue: http://stackoverflow.com/questions/27426958/multi-dimensional-array-push-in-angularjs
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66671/discussion-between-dang-and-ben-diamant).


Users that exist only on slave cannot login

Question: Once I've installed bakery, users that exist only on the slave site can no longer log in. Everything else is working perfectly.
Is this by design?
Answer: Bakery doesn't pre-sync accounts, so any accounts that exist only on slave sites (sub-sites) won't be synchronized to the master site. This is because of the nature of needing an authoritative account master, the Bakery master site. During authentication (on a slave site) Bakery sends the user to the master to validate so if the account does not exist there the user cannot be authenticated.
To note, accounts that exist on the master that do not exist on the slave will be synchronized when the user authenticates and visits the slave site (administrators also have the option to "pull" accounts from the master).


Which hyperparameters should I choose to tune for different ML models?

Question: I'm applying hyperparameter tuning with techniques such as, randomized search and grid search in python. I could find important hyperparameters and tuned them for Random Forest Regressor algorithm, since there are many examples of this specific algorithm and I knew which hyperparameters are important to tune. But for other machine learning algorithms how should I choose important hyperparameters and define the space for them and tune them? I'm confused since each ML model has many hyperparameters and I know that only some of them are dominant and affect the result the most. In general, I'm wondering for different ML models which hyperparameters I should choose and tune.
Answer: For Random Forest Regressor the most important/useful parameter to tune would be n_estimators, this is how many decision trees are used in your model. Usually the default of 100 is pretty good, but it you want to try a few others you go try 10, 20, 50, 100, 200. If your dataset is really big you can try higher.
max_features is another good one to try. This is how many features to consider when making a split in the decision tree. You can try 0.25, 0.5, 0.75, 1.0 and the default of "sqrt".
You can try tune max_depth. This is the maximum depth of each decision tree. Be careful, as high numbers can cause you're model to overfit. If you think your model is overfitting reduce the max_depth, or vice versa if its underfitting you can increase max_depth.
If you're having trouble with overfitting increasing min_sample_leaf, which increases the minimum number of sample required in a leaf node, can help too
To answer your broader question, the best way to know what parameters to tune is to learn about how the model you're implementing works, and what each of the parameters does. Understanding the intricacies, strengths and weakness of different model architectures can be what separates a good data scientist from someone who throws spaghetti at the wall and sees what sticks.
In general I recommend against creating huge grid searches when hyper parameter tuning. This can often lead to overfitting. A step by step approach where you train the most influential parameter, followed by the next I find is often better. Of course there are parameters which are correlated and its good to grid search for them.
Some parameters are best left untouched unless you are having specific problems with the model eg. overfitting, underfitting and you can tune these parameters to remedy these issues.
And remember parameter tuning can't make a bad model good, it is only meant to squeeze performance (whether its accuracy or speed) out of your model
Comment: Thanks for the answer. My methodology is strange, I use grid & randomized search to find optimum hyperparameters. Then I manually play with them and improve the result!!
Comment: This is a quite comprehensive answer to a very open question (+1) - @Etemon, you might want to explain your methodology in your question and make it more specific if you are searching for a more concrete answer. It was not me who closed it, but I would not see where to begin with an answer. Btw, welcome to the site :-)


autodiscover for 2 completly different domains

Question: We got local exchange with domain karel.com. But we are part of big company maruna.com (we don't have access to this domain,  we just using it). So our primary email for answers is for example firstname.lastname@example.com. But when I want to connect my email to outlook to our local exchange where are mailboxes, I am still getting the autodiscovery for maruna.com but we need to connect to our local exchange can someone help me how to configure autodiscovery for 2 completly different domains?
Comment: Hi, i'm here to confirm the progress of your thread, is there any update? If your problem has been fixed, you could mark the best answer or share your solutions.
Answer: How did you add the domain maruna.com to your email addresses? By Email Address Policy or alternative UPN suffix?
Do you get any internal/external hostnames related with the domain maruna.com if you perform an E-mail AutoConfiguration test in Outlook?

Besides, based on the result in the Outlook, make sure the SCP and internal/external URLs/Hostnames of virtual directories aren't pointing to the domain maruna.com, you could run the following commands in the EMS to see that:
Get-OabVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-WebServicesVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-OutlookAnywhere | fl Identity, server, *Auth*, InternalHostName, ExternalHostName
Get-OwaVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-ClientAccessService | fl Identity, Name, AutodiscoverServiceInternalUri
Get-EcpVirtualDirectory| fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-ActiveSyncVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-MapiVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL
Get-PowerShellVirtualDirectory | fl Identity, server, *Auth*, InternalURL, ExternalURL


How to make user profile page display extra fields in drupal 7?

Question: I have added some extra fields to users under admin/people/ - when I click edit beside the user, I can see the extra fields I have added.
However, if I go to /user/ those fields are not displayed.
How do I display user profile fields when their profile is viewed at /user?
Answer: You most likely added the fields through this admin page:
admin/config/people/accounts/fields
To control which fields are actually displayed on the view page, go here:
admin/config/people/accounts/display
Also if you have the Field Permissions module enabled, make sure all necessary roles have the permission to view the fields you've added.
Comment: tommi, thanks for the quick answer. i made everything "inline", but still nothing is showing..
Comment: Seems you're editing the "label" setting. That only controls whether the name of the field is displayed. You need to drag your fields above the "hidden" mark: http://dl.dropbox.com/u/3093436/userfields.png
Comment: So in the image I posted only the "about" field is visible, because it's above the "hidden" mark. You can make a field (like "real name" in my pic) visible by either dragging with arrows on the left hand side or by changing the format dropdown to something other than "hidden".
Comment: tommi, they are not under the hidden mark. drupal slaps me in the face yet again..
Comment: Have you edited the template for the user page?
Comment: no I have not touched that template
Comment: Wow, that's kind of screwed up.

What type of fields are they?
Comment: so under admin/configuration/account settings/manage fields they are text fields, and checkboxes/radio buttons
Comment: Can you post pictures of your "manage fields" and "manage display" forms, a user edit form and the corresponding user view?
Comment: sorry tommi i found my mistake...i was editing the wrong user all this time so when i clicked "root" nothing was showing for me...sorry to have wasted your time and curiosity
Comment: Hahaha. Classic. No worries.
Answer: A very belated reply that might help someone else.
I had a similar problem where I was going to populate the fields from another source and so the user wasn't to be allowed to edit them. I could see the fields as an administrator but not as the user.
The cause in this case was that the fields would only display if they had data in them. Adding data as an administrator made them visible (but read-only).


typeperf.exe Intermittently Returning -1

Question: Edit: Sep. 26 2012 - I am updating this question and its tags because I have now encountered this error again, on a Server 2k8R2 VM. Still, there seems to be no authoritative information out there on the net for this, so in case I ever solve it, this page could become a valuable resource for others having the same issue.
I've Googled the hell out of this and can't find an answer.
I have a Windows Server 2003 VM. I run the following command on the server:
<code>typeperf "\Processor(*)\% Processor Time"
</code>
And here is the output:
<code>"(PDH-CSV 4.0)","\\SERVER01\\Processor(0)\% Processor Time","\\SERVER01\Processor(_Total)\% Processor Time"
"03/30/2012 11:40:13.881","0.000000","0.000000"
"03/30/2012 11:40:14.795","22.374429","22.374429"
"03/30/2012 11:40:15.807","-1","-1"
"03/30/2012 11:40:16.707","0.000000","0.000000"
"03/30/2012 11:40:17.607","18.402778","18.402778"
"03/30/2012 11:40:18.507","0.000000","0.000000"
"03/30/2012 11:40:19.407","-1","-1"
"03/30/2012 11:40:20.307","-1","-1"
"03/30/2012 11:40:21.207","-1","-1"
"03/30/2012 11:40:22.107","-1","-1"
"03/30/2012 11:40:23.007","-1","-1"
"03/30/2012 11:40:23.907","0.000000","0.000000"
"03/30/2012 11:40:24.807","-1","-1"
"03/30/2012 11:40:25.707","-1","-1"
"03/30/2012 11:40:26.607","-1","-1"
"03/30/2012 11:40:27.507","-1","-1"
"03/30/2012 11:40:28.407","0.000000","0.000000"
"03/30/2012 11:40:29.307","-1","-1"
"03/30/2012 11:40:30.207","-1","-1"
"03/30/2012 11:40:31.107","-1","-1"
"03/30/2012 11:40:32.007","-1","-1"
"03/30/2012 11:40:32.907","0.000000","0.000000"

Error: A counter with a negative denominator value was detected.
</code>
Alright, so why the intermittent negative ones? I have a thousand other systems on which this behavior does not occur, but I can't figure out why it's happening here.  Any help would be appreciated.
Answer: After six months of (off and on) searching, I have finally found the solution to this problem.
I had seen that KB mentioned by brain99 before as well. It vaguely alludes to a "hardware timing issue," but doesn't give any specifics. Since I had really only seen this on VMs, the idea of a "hardware timing issue" seemed strange, but it did make me think about how VMs communicate with their host.
These were VMware virtual machines, and in the VM Tools, there is a "Time synchronization between the virtual machine and the ESX server" setting that was checked. Unchecking that solves the problem.
All this time I never fiddled with the VMware tools and the solution was so simple. :P
Answer: According to this Microsoft KB article, the error has something to do with timing issues but does not necessarily indicate a problem. It doesn't explicitly mention the negative values, but it stands to reason that the two are connected since the article specifically mentions a problem reading the Processor Utilization counter.
Unfortunately, no specific solution is provided in the article.
Comment: I'm sorry I had to un-check you... I found the definitive answer. :)
Comment: I figured that's about as good of an answer as I was going to get. It's not a big deal - I can rebuild the counters database or even rebuild the entire operating system... I mainly just wanted to know for academic purposes how exactly it happened.


Initializing simple structs using initializer lists with clang

Question: struct E_Point {
  double x, y;
  E_Point(): x(0), y(0) {}
  E_Point(double x, double y) : x(x), y(y) {}
};

E_Point problem[] = {
  {0.3871953044519425, -0.91857980824611341}, // Error: initialization of non-aggregate type 'E_Point' with an initializer list
  {0.36139704793723609, 0.91605957361605106},
  {-0.8208980020500205, 0.52853407296583088},
  {0.36178501611208552, 0.88880385168617226},
  {-0.43211245441046209, 0.6803420222771047}
};

Compiling with clang 3.1.
I should point out that this compiles on GCC 4.6.1.
My current understanding is that problem is a non-aggregate type because it is an array of structs, making it compound and not just simply either a struct or array.
But sending the -std=c++11 flag to clang does not alleviate the problem.
Update: Okay. Looks like my version of clang is somehow flawed and can't handle this for whatever reason.
What's a more traditional way to init? Do I do it this way? This compiles, but does it produce the same code? Will it call the ctor while the original doesn't?
E_Point problem[] = {
    E_Point(0.3871953044519425, -0.91857980824611341), // 1559
    E_Point(0.36139704793723609, 0.91605957361605106), // 1560
    E_Point(-0.8208980020500205, 0.52853407296583088), // 1798
    E_Point(0.36178501611208552, 0.88880385168617226), // 1799
    E_Point(-0.43211245441046209, 0.6803420222771047) // 1800
};

Comment: @Als: That isn't a C++11 feature; this is basic C++98 stuff. That's pure aggregate initialization, and it ought to work.
Comment: Yes it does have a [additional flag](http://clang.llvm.org/docs/LanguageExtensions.html#cxx11) perhaps you have not enabled it, something like `clang++ -std=c++11 [files]`, By default clang does not enable c++11 features, You have to enable explicitly.
Comment: BTW, your understanding is incorrect, an array of aggregates is an aggregate itself. The code is correct as is and it compiles with clang++ 3.1 (tags/Apple/clang-318.0.54) [MacOX Lion]
Comment: @StevenLu: Your `struct` that in the question here is an *aggregate* in your real code is **not** an aggregate. Everything else in the question is just a lost of time, as it is based on the premise that the original type is what it is not. `E_Point` is **not** an aggregate, you cannot use *aggregate initialization*. If you are using a C++11 compiler things change, as *uniform initialization* can be used there, and the inner curly braces `{}` will be mapped to a call to the constructor. What exact version of clang++ are you using?
Comment: Time to switch the compiler? [Compiles file with gcc 4.3.4](http://ideone.com/z00cC)
Comment: Well, I want to see if clang has a flag to allow compiling this, or an explanation of why clang does not support initializer lists of non-aggregate types. I can surely make the initialization slightly more verbose so it will compile fine but that isn't getting to the bottom of the issue.
Comment: @Als, I tried adding `-std=c++11` and also tried `-std=gnu++11`, did not fix issue.
Comment: Are you using apple's version of clang? This code compiles with my version of clang 3.1. Please post the full version (`clang++ --version`).
Comment: @JesseGood Interesting. Yes I'm trying to get my code compiled on OSX 10.7.4. Does your `clang` accept it without `-std=c++11`?
Comment: You could probably check if `__has_feature(cxx_generalized_initializers)` returns a true to check if the feature is available and enabled.
Comment: @JesseGood $ clang++ --version
Apple clang version 3.1 (tags/Apple/clang-318.0.58) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin11.4.0
Thread model: posix
Comment: @NicolBolas: Yes, true and moreso because gcc 4.3.4 compiles it nice and clean,just a little confused with clang behavior(I don't use it much)so just checking out.
Comment: @StevenLu: Yes, my version (`clang version 3.1 (trunk) (llvm/trunk 155821)`) accepts the code without `-std=c++11`. I'm assuming it's a bug in your compiler.
Comment: @DavidRodríguez-dribeas Thanks for pointing that out. This is quite strange.
Comment: Updated question with a few small additional questions.
Comment: @StevenLu: Could you post the exact code which gave you the compile error?
Comment: @DavidRodríguez-dribeas I assure you I did not *mean* to lie. The fact remains I have a bunch of code which compiles on `g++` and does not on `clang++`. Let me sort this out... Here's what i've got so far in terms of isolating this error. http://ideone.com/uvHZA Also, updated OP. And point taken; in the future I will make sure to test my code snippets before posting.
Comment: output of `clang --version` is this: `Apple clang version 3.1 (tags/Apple/clang-318.0.58) (based on LLVM 3.1svn) Target: x86_64-apple-darwin11.4.0 Thread model: posix`. Is it that once the struct gets a user-defined ctor it loses aggregateness? Shouldn't c++11 flag support that though?
Comment: @StevenLu: Uniform initializers were added late in the clang 3.1 process, the clang version that ships with Xcode 4 seems not to support this form of initialization, even if the official clang++3.1 release does support it. Note that I have had Apple clang 3.1 for a few months, but clang 3.1 was just released in the last two weeks...
Comment: Could somebody take a look at my ideone program? I'm quite confused... http://ideone.com/uvHZA
Answer: That is a bug in clang++:
http://llvm.org/bugs/show_bug.cgi?id=12670
In your case you can just use the explicit call to the constructor, as you provide in the last code snippet. As of whether the semantics are really the same (will it generate the same code), in most cases it will.
The case where the different syntax will lead to different behavior is when the type being constructed has a constructor that takes a std::initializer_list<>, in which case the brace-initializer will construct that initializer list. If the type does not have such a constructor, as is your case, the brace-initializer will call the appropriate constructor.


Similaridade de Textos

Question: Boa noite pessoal,
Gostaria de uma ajuda de vcs, pois estou iniciando no R, e tenho uma demanda, onde eu tenho que sinalizar as linhas onde tem as frases parecidas. Para isso,  estou usando a biblioteca stringdist. Porem, eu só consigo fazer a comparação por palavras na mesma posição, e gostaria de saber a similaridade da frase inteira, não importando a posição das palavras.
POr exemplo, no resultado abaixo, na 3º linha é a mesma frase, só que as palavras estão em posições diferentes.  Eu deveria considerar que é frase é similiar.
                              vet1      vet2          vet3
  heber dos Santos araujo   0.0000000   0.0000000   0.3591486

  heber dos Santos araujo   0.0000000   0.0000000   0.3591486

  araujo Santos dos heber   0.3591486   0.3591486   0.0000000

  heber dos s araujo    0.1372786   0.1372786   0.3955314

O código que estou utilizando é:
library(stringdist)

library(dplyr)

dis<-read.csv2("C:/Users/heber.araujo/Desktop/Estudo Questões Duplicadas/exemploTeste.csv")

library(tm)
stp<-stopwords("portuguese") #'Lista de palavras comuns que ele retira'

dis$Nome<-as.character(dis$Nome) # Coluna para pesquisa
dis$Nome<-removeWords(dis$Nome,stp)

'#for(i in 1:nrow(dis)){
'# dis_2<-strsplit(dis$text[i]," ")  # esse comando quebra a frase por palavra
'# dis_3<-unlist(dis_2)

'#dis_3<-dis$GQUE_DS_ENUNCIADO

dis_3<-dis$Nome

res<-stringdistmatrix(dis_3,dis_3,method = "jw")

rownames(res)<-dis_3

Answer: Creio que o seguinte código responde à pergunta.
Primeiro vou ler os dados, uma vez que não temos acesso ao ficheiro exemploTeste.csv.
Nome <- scan(what = character(), text = "
'heber dos Santos araujo'
'heber dos Santos araujo'
'araujo Santos dos heber'
'heber dos s araujo'")

Agora, as distâncias vão ser calculadas por uma função, heber, que ordena os nomes antes, e só depois chama stringdistmatrix com os nomes ordenados. Assim as diferenças de ordem das palavras desaparecem.
Os originais não são alterados.
heber <- function(x, method = "jw"){
    y <- strsplit(x, "[[:space:]]+")
    y <- apply(sapply(y, sort), 2, paste, collapse = " ")
    stringdistmatrix(y, y, method = method)
}

Nome <- removeWords(Nome, stp)
dis_3 <- Nome

res <- heber(dis_3)
rownames(res) <- dis_3
res
#                          [,1]      [,2]      [,3]      [,4]
#heber  Santos araujo 0.0000000 0.0000000 0.0000000 0.0877193
#heber  Santos araujo 0.0000000 0.0000000 0.0000000 0.0877193
#araujo Santos  heber 0.0000000 0.0000000 0.0000000 0.0877193
#heber  s araujo      0.0877193 0.0877193 0.0877193 0.0000000

Similaridade de Textos


The length of the third piece in the Stick breaking process

Question: I'm reading Nonparametric Bayesian Statistics Part I: some classical results.
In page 14 and section 3.2.1 I can't understand why the length of the stick after the second break is:
$$(1-Y_1)(1-Y_2)$$
and not
$$(1-Y_1-Y_2)$$
How is the extra term $$Y_1Y_2$$ part of the remaining piece of the original length 1 stick?
Answer: That's because the authors are considering the variables $Y_k$ to be in the standard range $[0,1]$.
So $Y_1$ is the length of the first cut and $1-Y_1$ the remaining part, out of which a part having a ratio $Y_2$ of $1-Y_1$ is cut, i.e. with length $Y_2(1-Y_1), and $(1-Y_1)(1-Y_2)$ is the length remaining ...
Comment: Thanks for answering but I'm still confused can you elaborate a little bit more?
Comment: What you are saying is that after the first break we have these two ratios: $$\frac{Y_2}{(1-Y_1)}$$ and $$\frac{(1-Y_2)}{(1-Y_1)}$$ That is the two new lengths with respect to the leftover of the first break. is this correct?
Answer: Thanks to G Cab I understand what's happening. First I noticed two key words: ratio and relative. The first pointed out by G Cab and the second one from the text I referenced in my question, i.e.,

We think of the remaining mass $1 − Y_1$ as a new stick, and break it into two pieces of relative lengths $Y_2$ and $1 − Y_2$...

The word relative, which in this context is just another way of saying ratio, basically means that the new absolute lengths, let's say $a$ and $b$ (i.e. after breaking the stick the first time) can be obtained from $$Y_2 = \frac{a}{1-Y_1}$$ and $$1-Y_2 = \frac{b}{1-Y_1}$$ thus $a=Y_2(1-Y_1)$ and $b=(1-Y_2)(1-Y_1)$.
So my confusion was because I didn't pay enough attention to the word relative in the text.
Comment: yes, that is correct, ratio <=> relative (+1)


index doesn't update

Question: I'm using Drupal 8's built-in search and it will not update the index.
I have cron running every 15 minutes and even tried running it manually but the search status page always says:
"0% of the site has been indexed. There are 80300 items left to index."
Another odd thing is that some nodes appear to be indexed, even though the status report says zero, because some (but not all) nodes will appear when searched for.
Any ideas what's going on?
Answer: This issue is solved. The issue was a malformed URI that was imported from the Drupal 6 website. The search indexing failed when it encountered this content (comment).
It turns out that it was old spam comments from the D6 site. I was able to delete those and indexing is working now.

index doesn't update


Can't add ABPerson to ABGroup. No errors, just will not actually add

Question: Hey I'm trying to add an ABPerson to an ABGroup. I get no errors or anything. My output tells me the person has been added successfully.
if(ABGroupAddMember(self.group, [allContacts objectAtIndex:indexPath.row], &error))
            NSLog(@"Added person: %@ to group: %@", ABRecordCopyCompositeName([allContacts objectAtIndex:indexPath.row]), ABRecordCopyCompositeName(self.group));

if(ABAddressBookSave(self.addressBook, &error))
        NSLog(@"Commited changes.");

These two statements return the correct output.
But upon querying the group members, I get an empty array.
NSLog(@"%@", ABGroupCopyArrayOfAllMembers(self.group)); //returns null

If anybody has any ideas, I'd really appreciate it.
Answer: Wow not 5 minutes after posting, I've found the problem. After editing the group, I have to add it back to the address book like so:
ABAddressBookAddRecord(addressBook, group, &error);

if(ABAddressBookSave(addressBook, &error))
    NSLog(@"Commited changes.");

Answer: Just as an FYI, some sources (ABSource, e.g. MSExchange) do not support group creation.
There are some details and code examples on specifying sources (iOS 4+ only) here:
Obtaining Specific ABSource from ABAddressBook in iOS 4+


Why is it called a Gm7/C when C is not even in the chord?

Question: In Louis Armstrongs song "What a wonderful world", the part where he actually sings this phrase happens on what is written as a Gm7/C > C7 > F... so in other words a ii V I progression. But why is the Gm7/C not some kind of C7sus4 chord? Anyhow, I was looking and trying to understand why this voice leading works and wanted to ask if someone could help me understand it or to tell me if what I am hearing is right. So what I hear is that the F in the C7sus4 (or Gm7) chord resolves to the E in C7 and the D in the C7sus4 (or Gm7) resolves to the C of the C7 chord and this is is why this works as a progression?
Comment: See the proposed duplicate for an explanation of slash-chord naming in a case like this, and also see [What does the chord notation X/Y ("slash chord") mean?](https://music.stackexchange.com/questions/104163/what-does-the-chord-notation-x-y-slash-chord-mean) for a fuller explanation of the meaning and uses of slash chords.
Answer: Slash chords! The chord name before the slash is the main chord. The note name after the slash is the lowest note expected to be played. Often on the bass, or lowest note on piano or even guitar, if no other lower pitched instrument is available.
That note after the slash is often a chord tone, but doesn't need to be. When it is a chord tone, that symbol embodies the inversion of that chord before the slash. C/E for example, would be a C chord with E in the bass, making it a 1st inversion.
Gm7/C is basically a Gm7 chord (G B♭ D F), played as such with the exception that the lowest played note needs to be C. So a bassist, who would usually play a G note (root of chord), would instead play a C.
That makes it into a kind of Gm11, with the 9 missing - as it sometimes can be. Or it could be considered Gm7(add11), although that would put the C note at or near the top of the chord, not what's required here.
It won't be Gm7/C = C7sus4, as the former is spelled  C G B♭ D F, the latter C F G B♭ - there's no D in this one. Could call it C9sus though.
Comment: ok I understand now... can you please explain why someone would want to have a Gm7/C instead of just a Gm7? Is it because the vocal sings an F and that is a 4th as opposed to the 7th against the G in root position?  here is the sheet music http://elpregonero.info/PARTITURA/PDF/491%20-%20Louis%20Armstrong%20-%20What%20a%20Wonderful%20World.pdf
Comment: Not really. I try not to get too bogged down with the actual technical side when playing chords, writing, etc. Sometimes things just work - even though theory says otherwise, and I'd rather go with the flow and sound like I want something to, than allow things to be hindered because of 'rules'.
Comment: Agreed with Tim. Sometimes it's just that, compositionally, you want the bass to be doing something, rising or falling etc, while the chords on top move differently, and it's easier to say "a Gminor chord with the C in the bass" than writing a chord named off of the C bass that might appear odd to someone reading it. In other situations writing it as a familiar chord with a non chord tone in the bass may help someone reading the music read it easier in the heat of the moment, or may suggest the kind of voicing the composer was imagining, even though the 'true' chord made may be more complex.
Answer: This is almost a standard ii V I progression. The ii is very often varied as ii/V (the Gm7/C is equivalent to a C9sus, which resolves to C7 nicely). In this case, since the bass is coming from Db in the previous bar, C is the only bass note that makes musical sense.
Comment: Does the C9 sus resolve nicely because of what I wrote? F > E and D > C?  Also, since ii is a subdominant chord and if I put the dominant (C) in the root, is that kind of like a hybrid subdominant/dominant chord?
Comment: Yes, the F resolves to E and less importantly the D to C. It's not a subdominant though. It's a hybrid of ii and V.
Comment: @armani has a point: it *is* a hybrid subdominant/dominant chord. Its B♭, D, F make the IV chord. The chord has subdominant function in that it comes before a V-I cadence. ii (or, more fully, ii7) is just an alternative way to notate IV6 in Roman numerals; here, to say  ii rather than IV is to call G rather than B♭ the root.
Comment: @RosieF ii7 by itself functions as a subdominant. Adding the V note in the bass changes everything and puts it firmly in dominant territory.
Answer: Gm7/C could indeed be considered 'some kind of C7sus chord'.   It's the particular flavour of it which has G, B♭, D and F in the upper structure with C in the bass. And, interestingly, it DOESN'T have C in the melody or upper structure.
C7sus4 contains C, F, G and B♭ in the upper structure, C as the bass note.  It DOESN'T contain D, and C IS included in the upper structure.
Then there's Gm/C.  Same idea as Gm7/C, but there's no F in the chord.
Three chords with very much the same function but different flavours.  They deserve different names. You don't choose one or the other because it's the 'right' one, you choose it because you want THAT sound.  That's what composing music is all about, you get to choose from a wide range of possibilities.  Think about it. If there was always a 'right' next chord, there would only be one perfect song starting with a C chord!
You'll see C11 used as a chord symbol.   It might mean any of the three above chords.   (What it's very unlikely to mean is an actual C11, that's C, E, G, B&flat:, D, F.)  You'll have to work out what it means when you find it in  sheet music.  I suggest YOU don't write it.


Which Marathons to run?

Question: For many years, one of my major "running" dreams have been to run the New York Marathon - the bridges, the people and the grand background. But I recently found out that the "qualifying time standards" for the run has been changed, so there are really no chance for me going there...
The question is then, which Marathons I should aim at if not New York? What are the great Marathons out there that one must do if possible?  Like the almost impossible ones such as Marathon des Sables or the Antarctic Ice Marathon? Or the big city venues in London, Chicago, Berlin, or whereever? Or the beautiful ones like Jungfrau and The Great Wall?
I'm looking for recommendations for Marathons from people that have first hand experience with these.
I'm looking for scenery and routes that doesn't include too many hills (Being from Denmark - flat, flat, flat - I'm just very bad with hills :-)). I prefer the venues to be well-organized with a stable history... And nothing that requires qualifying times less than 3:30...
Until now I have just run many local runs - mainly half-Marathons - and there are many as this list shows - but now I would like to "try" something else.
I can find many lists with Marathons on the web... Too many really... It makes it so very difficult to choose.
Comment: Running the New York marathon is possible even if you can't meet the qualifying times--those are only for guaranteed entry.  Registrants who don't meet the qualifying times are put into a lottery where a certain number are drawn until the cap is met.  There are also some charities you can hook up with that will give you a guaranteed entry in exchange for fundraising a certain amount for them.
Comment: Just a note, the Marathon des Sables is most definitely NOT a marathon in the traditional sense of the term (26.2 miles). It's a largely self supported, 6 day, 151 mile running race across the Moroccan desert.
Comment: @Shog9 Not sure I like your re-title... I really want to get alternative suggestions for alternative races. Knowing how to get into the major marathons - possibly without qualifying - that could be another interesting question.
Comment: @Andrew The thing is that the rules are a little different for those coming from abroad - in my case Denmark... I'll have to check the lottery though. Thanks.
Comment: @MikeHedman I know. But that would be the ultimate challenge...
Comment: @TonnyMadsen So are you looking for a marathon or an ultra? Those are two different things. Running an ultra (more than 26 miles at a clip) takes much more patience and requires you to slow down... way down.
Comment: @Tonny: that's essentially the first part of your question though; you might consider breaking this into two.
Answer: Having done 37 marathons I can say some are definitely nicer than others.  Rating them is an impossible task. I do recommend NYC at least once.  I have guided disabled athletes 4 times now at NYC (run it 5 times myself) and doing it as a guide is a very different perspective and an amazing experience.  (Thus I can say I have run across the Verezanno Narrows bridge with 40,000 other people, and as a group of 50 people on the early start for disabled athletes.  Both ways are awesome!)
For example Salt Lake City is in July, starts on a mountain top at 5:30AM (start was 55F, finish was 110F) and has tons of downhill, however most of it is outside the city in the mountains and was beautiful.
Chicago is still easy to get into, and is a great big city marathon.  There is something unique about 40,000 people starting with you.  (I have done NYC 9 times, and Chicago once).
Cincinnati is a smaller race, but has great crowd support and a very bizarre pig theme that is probably taken a smidgen too far.
Often the race directors try to get the course through interesting areas.  In St Louis they run through the Budweiser factory which is sort of clever.
On the other hand, Mississauga marathon, a city outside Toronto is pretty boring, and I have done it twice, but would probably not do it again.  Not much in terms of sights. As is London, Ontario (Forest City marathon, also done it twice, so I clearly ignore my own advice).
Atlanta was nice but nothing special.
I have a friend who did all seven continents and she greatly enjoyed all of them.  If you can get to the point where a marathon is 'fun', then you are most of the way there.
There are so many races all over the world, pretty much every weekend, that you can travel where ever you like to do a race.
Comment: I'm afraid, I will not be able so travel all over the world constantly... With the family around, I neither have the time or money for that :-) So, Ill have to prioritize a bit... Though I would love to travel to a lot more races than that.
Comment: @TonnyMadsen I fully understand that.  The nice thing is there ought to be several within an hour or threes drive, if you live in the US.  Just because there seems to be such a huge proliferation of races everywhere.
Answer: I live in Norway and have completed 3 full marathons over the last 3 years: Oslo, Copenhagen and Berlin.
Oslo was nothing special, except being close to my home and very little travel time. There lots of running in quiet streets with little entertainment along the way (I hear it's a bit better now, though). It's not that flat either.
I had a good experience in Copenhagen. Much flatter than in Oslo. But I definitely felt the cobblestone along the river way up in my calves :/ (couple of kilometers of cobblestone)
Lots of people everywhere, nice route, and lots of entertaining along the route.
Berlin was much like Copenhagen, only bigger. More people, more entertainment. And Berlin is the race to compete if you want to set a record (and I did). Good, flat route.
All in all, from personal experience I would recommend Berlin the most. And Copenhagen. Not Oslo.
Personally I would love to compete in two specific races, New York and Great Wall.
Answer: If I was to pick one specific marathon that a runner should aim to run at least once, I'd definitely pick the Athens Classic Marathon.

It's an A to B route that is lined by people from different villages along the route cheering you on
At least in 2010 when I ran it, it was very well organised
Finishing at the Panathinaiko Stadium is amazing
It's the original route marathon was first run on over 2500 years ago (or more accurately, where the battlefield messenger ran from Marathon to Athens in the end Battle of Marathon.)
There is something about its history that really spurs you on
Answer: As I live in Israel, and only ran 21.1 so far, we got 3 major marathons here: The best (which does not fullfill your flat/flat/flat course) is The Jerusalem Marathon. It is not flat at all, but the scenery, running around the old city of Jerusalem, the Sacred Wall, through the old city - it's a race you will not forget.
The other marathon I can offer you, which is one of the more flat ones you will ever have, it the Tel Aviv Marathon (event on March 3rd 2012)  - The course plan is not yet fully approved by the police, but if like last year, it's entire height diff is +-40 meters in height.
Again, you are running along the sea shore/board walk of Tel Aviv, and into the old city as well (not as beautiful as Jerusalem).
HF, enjoy.
Answer: Of the three major marathons I have run (Edinburgh, Paris and London) I would recommend the London Marathon as having the best atmosphere, and for being the classic marathon for amateur runners. There are tens of thousands of entry places for charities and the entire day is very supportive to those runners who aren't at a professional place.
The Paris Marathon provides amazing scenery (42.195km in the most beautiful city in the world, as their site claims), and has one of my favourite sections - the Bois de Boulogne, where stalls are set up not with fruit or water, but with wines, cakes and cheeses - not conducive to a fast pace, but very pleasant for those last few miles before the finish.
The Edinburgh Marathon is the second largest marathon in the UK, but is a very fast marathon (voted the fastest marathon in the UK in 2008), with a few hills, but nothing steep (they used to include a steep run up Arthur's Seat, but the pros complained about the pace...) - there is an amazing run all along the coast, which can cool you down on a hot day.
Answer: As most probably you're doing this for fun, then choose the marathons that you like.
First you should settle on a type of marathon, because you enumerated quite a few. And on the distance as well.
Marathon des Sables is a more than 240km race, more or less self-sustained, so you should be in a quite good shape to finish it. Antarctic Ice Marathon has a 21, 42 and 100km version.
So you have depending on the distance half, marathon, ultra and multi-day ultramarathons. Then, depending on the terrain, you can run on road, mountain, sand/desert and ice.
If you want to run on desert you should start with the Sahara marathon in Alger which is a classical one compared to Marathon des Sables. If you want to run on ice, Antarctic or North Pole Marathons are quite expensive (over 10k EUR), but you also have the Polar Circle, Siberian Ice (actually a half one) or Baikal (you're running on the frozen lake) marathons.
If you want on the road, as you're from Denmark, there are plenty of options in Europe, almost every major city having one. So just a pick a city you want to visit and search for its marathon. Berlin one has a very flat profile so it's very good for setting good times :) (world record is registered there).
If you want on the mountains, Spain and Italy have very good choices. Also Romania, where I live, has very good choices in this area with beautiful and wild scenery. All half, marathon and ultra version. Biathlon and triathlon too.
You also have interesting marathons, like the ones in UK running against horses or a train.
Later update
Now I see that you edited your question and said that you want marathons with a history behind, as flat as possible and great scenery. Usually the flat ones will have more of an urban landscapes. For wild scenery, definitely you must go for the mountains. For the seaside you could try Limassol marathon in Cyprus. And it has just only one small hill.
When it comes to history there's nothing better than the classic marathon with a history of over 2500 years. If you want go into ultramarathons, then you should try the original challenge, Spartathlon or Phillipide's challenge.
I must reiterate that you should consider combining a city break with a marathon, it's double the fun.
If you also want an added thrill you could try North Korea, Ghaza or running in Africa with the lions and rhinos in Big Five. Or you could try at night or underwater. Or if you love the heat, you could also try the option of Dead Sea marathon.
Answer: The following two Midwestern races are flat and scenic: Bayshore marathon in Traverse City, MI, in May, and a marathon in St. Charles, IL, in September. I ran them both and really liked.
You have not mentioned if you tolerate heat and/or cold. What's your preference?

Which Marathons to run?


Issue about java 8 backward compatibility: new methods in JDK

Question: Simple question. In Java 8 we have huge number of new methods in JDK classes. Say we have created such class, using Java 7 (or Java 6):
class MyArrayList<E> extends ArrayList<E> {
        public void sort(Comparator<E> c) {
            // some sort
        }
}

This is quite reasonable implementation. Now we try to compile it with Java 8 and receive expectable compile error:
error: name clash: sort(Comparator<E#1>) in MyArrayList and sort(Comparator<? super E#2>) in ArrayList have the same erasure, yet neither overrides the other
            public void sort(Comparator<E> c) {
                        ^   where E#1,E#2 are type-variables:
    E#1 extends Object declared in class I.MyArrayList
    E#2 extends Object declared in class ArrayList

Here I would like to arise 2 questions:

Even with javac -source 1.7 -target 1.7 option using JDK 8 I receive same error - why? I thought these options should allow compile legacy code.
How about backward compatibility in general?

EDIT To be precise, may be I'm doing something wrong? JDK 1.8.0_65, Mac OS X:
bash-3.2$ javac -version
javac 1.8.0_65
bash-3.2$ javac -source 1.7 -target 1.7 MyArrayList.java
warning: [options] bootstrap class path not set in conjunction with -source 1.7
MyArrayList.java:7: error: name clash: sort(Comparator<E#1>) in MyArrayList and sort(Comparator<? super E#2>) in ArrayList have the same erasure, yet neither overrides the other
    public void sort(Comparator<E> c) {
                ^
  where E#1,E#2 are type-variables:
    E#1 extends Object declared in class MyArrayList
    E#2 extends Object declared in class ArrayList
1 error
1 warning

Comment: This is described in the javac docs. "But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use the -bootclasspath and -extdirs options when cross-compiling."
Comment: Relevant: http://stackoverflow.com/q/31188231/1743880
Comment: `-source 1.7` ensures that language features from Java 8 are not used, and `-target 1.7` ensures that generated bytecode is compatible with a 1.7 JVM. Neither changes the Runtime Library being used. You need more options to change the runtime library to Java 7 during compilation.
Comment: The source and target specify the version of the language to use not the version of the libraries to use.
Comment: @Tunaki Thanks, exactly. This is answer to my second question.
Comment: yes, java8 breaks things like that, and you aren't the only one complaining:)
Answer:
because even with these options, you're still compiling against the Java 8 classes. The JDK doesn't have any idea which methods appeared in what version of the JDK. All these options do is tell the compiler to  accept only Java 7 syntax in the code you're compiling, and to generate Java 7 bytecode. You would have to pass actually link to the JDK 7 classes (using the -bootclasspath option) to cross-compile.
Yes, it's a problem. Not huge, and the benefit of having all thses new default methods is more important than the inconvenience of having some rare non-compiling code.
Comment: That's what I would do by default. Unless I have a library/framework that can work with Java 7, but provides an added value when used with Java 8, or must support classes that only exist in Java 8. Take Spring, for example: it natively supports classes in the java.time package, but is nevertheless compatible with Java 7.
Comment: That is very strange :) If I have JDK 7, why I should try to compile it with JDK 8? Looks like useless feature, doesn't it?
Comment: @Andremoniy: the potential problem of class evolution when methods are added to a superclass always existed in Java. At least, Java 8's `javac` now warns about using the `-source`/`-target` options without a matching boot class path. This kind of usage still has a point. The Java 8 compiler might contain new bug fixes. See [here](http://stackoverflow.com/q/34659055/2711488) for an example of a difference.
Answer:
-source 1.7 only says that the source uses Java 7 language features. -target 1.7 says that the outputted bytecode targets a specific version of the JVM. However, you are still compiling against JDK 8. Since you are cross-compiling, you have to tell javac where the bootstrap and extension classes for Java 7 exist using -bootclasspath and -extdirs
Default methods in interfaces (that were introduced in Java 8) lets you add new functionality without breaking existing code. It's not a bulletproof solution and there can be minor issues (this answer explains the issues in some detail). But on the whole backwards-compatibility issues are quite rare.
Comment: Not necessarily. This way you can just maintain the runtime-library jars and any other extensions you need instead of maintaining the *entire* JDK distribution for a particular version. In addition, you can just use one compiler to compile to different targets, instead having to switch between compiler versions for the target you need (makes things easier for tooling). But yeah, if you already have JDK 7, then you don't strictly *need* to use JDK 8 to compile JDK 7 code. It depends on your usecase.
Comment: That is very strange :) If I have JDK 7, why I should try to compile it with JDK 8? Looks like useless feature, doesn't it?


How to select a custom block and region according to a view

Question: I have a view / display page that needs to be displayed in a specific html - page format.
I did a html--viewname.tpl.php and page--viewname.tpl.php to display my view.
Within page--viewname.tpl.php I call print render($page['content']); to render my view.
All is working except that block.tpl.php and region.tpl.php are called by drupal system to wrap the view content adding several html tags (div)  that I don't want.
I expected to use function MYTHEME_preprocess_block(&$variables) to ask drupal to use a custom block.tpl.php file, but within this function I didn't find the way to know if the function is called to render my viewn or anything else.
Answer: When dealing with a page view you can use the views_get_page_view() function, to get the view object for the current page, like this:
/**
 * Variable preprocessor for the block template.
 */
function MYTHEME_preprocess_block(&$variables) {
  // If we are on a views page display.
  if ($view = views_get_page_view()) {
    // If we are on the MYVIEW view.
    if ($view->name == 'MYVIEW') {
      // Add the view object to the variables for use in the template (if you need it).
      $variables['view'] = $view;

      // Use a custom block template for this specific display (if required).
      $variables['theme_hook_suggestions'][] =  "block__{$view->name}";

      // Add your block customisations for this specific view (if required).

      // If we are also on the MYDISPLAY display of MYVIEW.
      if ($view->current_display == 'MYDISPLAY') {
        // Add your block customisations for this specific view and display here (if required).

        // Use a custom block template for this specific display (if required).
        $variables['theme_hook_suggestions'][] =  "block__{$view->name}__{$view->current_display}";
      }
    }
  }
}

Comment: Thanks rooby, it is what I was looking for, now I don't understand why drupal is still calling the default `block.tpl.php` instead of my custom one set in the preprocess function. I'm still debugging to understand that...
Comment: Ok, in fact when `$variables['theme_hook_suggestions'][] =  "block__XXX_YYY";`   drupal looks for template file `block--XXX-YYY.tpl.php`. Strange because I did the same for html template using `html--XXX--YYY` as suggestion and `html--XXX-YYY.tpl.php` as template file name without any problem. I will ask a question about that.
Comment: Underscores in template suggestions are converted to dashes in the template file name. Dashes are left as dashes.


Find the integral: $\int{\frac{6x^4-5x^3+4x^2}{2x^2-x+1}}dx$

Question: I'm reading Differential and Integral Calculus by Piskunov, and have read up to integration using substitution. I've learned how to solve integrals of the form:
$$\int{\dfrac{Ax+B}{ax^2+bx+c}}dx$$
The integrals of the above form are solved by completing the square in the denominator, and decomposing the fraction into a sum such that the first fraction of the sum is of the form:
$$\int{\dfrac{2ax+b}{ax^2+bx+c}}dx$$
and the second fraction in the sum is of the form:
$$k\int{\dfrac{1}{ax^2+bx+c}}dx$$
By substituion, the above two terms are readily integrable.
I tried applying similar techniques to the following integral:
$$\int{\dfrac{6x^4-5x^3+4x^2}{2x^2-x+1}}dx$$
But have not been able to simplify them enough. The numerator is always two degrees higher than the denominator, and the $x^2$ term doesn't yield to the substitutions that worked in the simpler forms I wrote about above.
This is what I got after some simplification:
$$\dfrac{1}{4}\int{\dfrac{\left(3t^2+t-2\right)^2+71\left(t+1\right)^2}{\left(t^2+7\right)}}dt$$
$t$ is $4x-1$.
How can I solve the integral given in the question using only integration by substitution? In particular, can't use integration by parts.
Comment: Perform the long division first to arrive to something you knwo.
Answer: Note that
$$6x^4-5x^3+4x^2=(3x^2-x)(2x^2-x+1)+x$$
So $$\int \frac {6x^4-5x^3+4x^2}{2x^2-x+1} dx =\int (3x^2-x)dx+\int \frac {x}{2x^2-x+1} dx$$
I think you can do it now, using the techniques you mention in the question.


User rights: Only create, edit and publish articles

Question: There is a user role where users can edit, save and publish articles. But they don't see the admin menu.
Does exist a module to realize a "create content" button only or to modify the admin menu?
Answer: There is no specific module for that, and it is well known problem. But if you want them to only create one content type, like Article, you don't need a module for that. You can simply go to /admin/structure/menu and add links like /node/add/page to a menu they can access.
For node listings for such users, create a view with table of titles and edit links.
Answer: If you're looking to use a specific role for content creation but do not want them to get into any of the administration areas, I'd recommend the Workbench module. Create a new role called something like "Content Moderator" then in Workbench you can specify which content types they can add, edit, delete, and publish.


Are there good references or books for multivariate (multi-response) generalized linear mixed model (MGLMM) in R?

Question: I did not find material on this topic. Information on linear mixed model (lmm) or generalized linear mixed model (glmm) is easy to find, but it is not not the case for multivariate (multi-response) generalized linear mixed model (MGLMM).
Can you recommend a good reference for multivariate (multi-response) generalized linear mixed models?
Answer: One of the only books I can think of that cover this topic is the book Multivariate Generalized Linear Mixed Models Using R, which you can find here.

I think the book speaks a while on the univariate case, so if you are just wanting to learn multivariate GLMMs, I would skip to Chapter 11 (Page 115), though you may miss some important information on the syntax for the main function they use for these models, sabre, so it may be good to at least familiarize yourself with the function first. I also believe there is a sabre coursebook that can also be found here.
Comment: Thanks Shawn, I know the book and after your description I will have a look at it. I hoped to find something more recent, but arguably there are not many sources available
Comment: Something else you may be able to consider is a multi-level SEM, which allows you to include a GLMM framework into a SEM model (which of course allows multiple DVs).


Update oracle com informações distintas

Question: Estou tentando fazer um update no oracle com informações completamente distintas e não sei como fazer. Eu quero que todos os outros campus estejam igual ao campus 1, onde esse id_campu é uma foreign key com outra tabela.
Exemplo:
col1.id | col2.descricao |col3.id_campus| col4.flag
 1        desc1            1               a
 2        desc2            1               b
 3        desc3            1               c
 4        desc2            1               d
 5        desc3            1               e
 6        1desc            2               a
 7        1desc            2               b
 8        1desc            2               c
 9        desc2            2               b
 10       desc1            2               c
 11       1desc            3               b
 12       d1esc            3               d
 13       d1esc            3               c
 14       desc2            3               e
 15       des1c            5               a
UPDATE table1 t1
   SET (descricao, flag) =
       (SELECT t2.descricao, t2.flag
          FROM table1 t2
         WHERE t1.id_campus = 1
       )
 WHERE t1.id_campus in (select t3.id_campus from table1 t3 where t3.id_campus not in (1));

Só que aí, dá o erro: ORA-01427: a subconsulta de uma única linharetorna mais de uma linha.
Comment: Melhore o exemplo descrevendo as tabelas, confesso não tem entendido este "id_campus = 1" e "id_campus = 1" , em princípio um bloco plsql com um cursor deve resolver a questão.
Comment: Como o @Motta citou para a situação que mencionou será necessário um bloco plsql utilizando um select(cursor) em um FOR passando estes parâmetros distintos para o update. [LINK plsql para entender melhor](http://www.devmedia.com.br/pl-sql-functions-e-procedures/29882)
Comment: E o perguntador some ...
Answer: Parece que no select abaixo, está retornando mais de um id_campus = 1... Crendo que nessa "table1" ele é foreign de uma tabela "campus", por exemplo.

(SELECT t2.descricao, t2.flag
            FROM table1 t2
           WHERE t1.id_campus = 1
         )

Com base em todos os campus precisam ter a descricao e flag igual ao campus 1, poderia fazer:
UPDATE table1
SET DESCRICAO = ( SELECT DESCRICAO FROM TABLE1 WHERE ID_CAMPUS = 1 )
    , FLAG = ( SELECT FLAG FROM TABLE1 WHERE ID_CAMPUS = 1 )
WHERE ID_CAMPUS <> 1

Mas lembre de se garantir que nessa table1 tem apenas um registro pro campus 1, senão pode ser um erro de base, ou talvez tenha uma data de vigência dessas características...

Update oracle com informações distintas


Is Gould playing extra notes in Bach's Toccata in C Minor, and if so, why?

Question: In Glenn Gould's recording of Bach's Toccata in C Minor, it sounds like he modifies the melody in the the right hand to add two extra notes

You can hear it here.
Is this just a Gould improvisation, or are there editions where these notes exist?
Comment: I was explicitly told to improvise ornaments in my Baroque piano exam pieces. (I wasn't too good at that back in the day.)
Answer: It is comparatively typical baroque phrasing to add the intermediate as an appoggiatura to a descending third in ending phrases.  It would be unusual if the staccato marks were there in the manuscript, though.  But I don't see dots in the Urtext: your edition is filled to the brim with fingerings and articulations that are not in the original.
So while it seems like a Gould addition, it is not out of the period execution style.
Answer: To make @user87310's point more explicit. Embellishing on the written score was perfectly normal practice in the baroque. However,

Bach's writing is dense enough that it's not necessary
Bach is the baroque composer that's most familiar to people not into early music.
Bach is also the baroque composer most played by classical musicians who otherwise stay away from early music.

So it's to be expected that it may come as a surprise to the OP that a performer so clearly deviates from the score. However, be assured that for other performers to supply some extra notes is the most normal thing to do.
Comment: No, figured bass is of course more about the left hand, but it's just another indication that improvisation (whether in melody or accompaniment) was an expected skill for performers to have at this time, which is often overlooked by modern performers of classical music.  (Obviously it's still alive and well in jazz, but that's a whole other thing.)
Comment: Other pianists freely embellish, e.g. Murray Perahia does it on repeats in his Goldberg Variations.
Comment: It was actually common practice in those times for the entire left hand part to not even be explicitly written out, but just give a chord progression, and the performer was expected to fully improvise this.  See [basso continuo](https://en.wikipedia.org/wiki/Basso_continuo).
Comment: @DarrelHoffman Did you mean to say "right" hand? Also, realizing a continuo from figured bass (or sometimes just the bass line, no numbers or anything!) is something different from altering the melody. It pertains to accompaniment. Under discussion here is altering the melody.