Datalist com retorno de vários campos em PHP

Question: Após algumas pesquisas conseguir desenvolver um datalist que recupera valores diretamente dos registros mysql, com php apenas e os exibindo por javascript. Gostaria de saber se é possível retornar o valor de vários campos, após preenchimento de um? Por exemplo, após encontrar o cliente, os demais campos como telefone, endereço, data de nascimento, tambem são preenchidos.
Vou deixar o código abaixo pra exemplificar:
    <?php
include('./conexao.php');
?>

Ficha Micropigmentação

        <form oninput="escrever()">

                Cliente
                    <input type="list" id="clientes" list="cliente">
                    <datalist id="cliente">
                        <?php
                        $consulta_clientes = "SELECT nome FROM clientes ORDER by id DESC";
                        $resultado_clientes = mysqli_query($conexao, $consulta_clientes);

                        while ($linha_clientes = mysqli_fetch_array($resultado_clientes)) { ?>
                            <option value="<?php echo $linha_clientes['nome'] ?>"></option>
                        <?php } ?>
                    </datalist>

                Data do procedimento
                    <input type="date" id="datade">

                Forma de Pagamento
                    <select id="pagamento">
                        <option>Dinheiro</option>
                        <option>Cartão de Débito</option>
                        <option>Cartão de Crédito</option>
                    </select>

                Existe algum problema que julgue necessário informar antes do procedimento?
                    <textarea id="problemas" cols="25" rows="5"></textarea>

                Declaro que sou maior de idade e estou submetendo-me a MICROPIGMENTAÇÃO DE SOBRANCELHASde livre e espontânea vontade.
                    <select id="maior">
                        <option value="sim">Sim</option>
                        <option value="nao">Não</option>
                    </select>

Pigmento 1

                Marca do Pigmento
                    <input type="text" id="marca">

                Data da Abertura
                    <input type="date" id="abertura">

                Validade / Lote
                    <input type="text" id="validade">

                Cores Usadas / Pigmento
                    <input type="text" id="cor1">

                Cores Usadas / Pigmento
                    <input type="text" id="cor2">

Pigmento 2

                Marca do Pigmento
                    <input type="text" id="marca2">

                Data da Abertura
                    <input type="date" id="abertura2">

                Validade / Lote
                    <input type="text" id="validade2">

                Cores Usadas / Pigmento
                    <input type="text" id="cor11">

                Cores Usadas / Pigmento
                    <input type="text" id="cor22">

AUTORIZAÇÃO USO DE IMAGEM E FILMAGEM

                <select name="id">
                    <option>sim</option>
                    <option>não</option>
                </select>

        </form>

FICHA DE AUTORIZAÇÃO E ANAMNESE

                NOME:      DATA:

                ENDEREÇO: _______________________________________________________ CEP: ______________________
                FONE_______________________________________________
 DATA NASCIMENTO: _______________________
                E-MAIL:________________________________________________ CPF: __________________________________

                FORMA PAGAMENTO:

                PROCEDIMENTO DE MICROPIGMENTAÇÃO DE SOBRANCELHAS
                Cardíaco (tem marca passo) Diabético*: Hipertensão:
                Anemia: Câncer: Problema cicatrização:
                Hepatite: Alergias: Gestante:
                Doenças Infecto Contagiosa: Menstruada: Usa medicamento:
                Faz dietas / balões: Depressão: Fumante:
                Alcoólatra: Doença auto imune: Maior de idade:
                Queloide: Herpes: Lactente:

                Existe algum problema que julgue necessário informar antes do procedimento? se houver relatar abaixo:
                Não
                    <input type="radio" name="selecao" value="Não" checkdate>

                Sim
                    <input type="radio" name="selecao" value="Sim" checkdate>

                Quais?

                Declaro que sou maior de idade e estou submetendo-me a MICROPIGMENTAÇÃO DE SOBRANCELHAS de
                livre e espontânea vontade.

                    MARCA DO PIGMENTO
                    DATA DE ABERTURA
                    VALIDADE / LOTE
                    CORES USADAS / PIGMENTO
                    CORES USADAS / PIGMENTO

                    MARCA DO PIGMENTO
                    DATA DE ABERTURA
                    VALIDADE / LOTE
                    CORES USADAS / PIGMENTO
                    CORES USADAS / PIGMENTO

                 Estou ciente que realizarei a micropigmentação de sobrancelhas com a profissional....

                 O procedimento e todas as implicações relativas ao mesmo, me foram esclarecidas e estou ciente das minhas

                condições psicológicas e de saúde, ficando assim a profissional isenta de qualquer responsabilidade quanto as
                reações que por ventura eu venha apresentar.
                Estou ciente e confirmo que o material que será usado é descartável, assim como todo padrão de higiene está
                sendo seguido corretamente, conforme as normas da Vigilância Sanitária (ANVISA).

                Levando em consideração a absorção do pigmento em cada organismo, e também os cuidados que o cliente terá
                que ter a partir do momento em que optar em fazer a micropigmentação de sobrancelhas, estudos comprovam a
                durabilidade de média 8 meses á 1 ano, nesse período respeitando todas as indicações da micropigmentadora, o
                pigmento tende a clarear naturalmente com o passar dos anos, mas não sumirá definitivamente, sendo assim
                havendo a necessidade de manutenção nesse período.

                O retoque deverá ser realizado somente após 40 dias. Para todos os retoques realizados, cobraremos uma taxa
                de R$ .... reais referente ao material usado. O prazo para agendar o retoque é de 35 dias. É considerado retoque
                até os 3 primeiros meses, após este período realizaremos MANUTENÇÃO, no valor R$ .... reais.

                O modelo / formato de como ficará o desenho frontal fui eu quem escolhi, a profissional desenhou e mostrou
                como ficaria, apagou e refez até ficar do meu gosto, me orientando qual o modelo que seria melhor para mim,
                mas prevalecendo o desenho que "EU" escolhi, apenas micropigmentando após a minha autorização. Se eu me
                arrepender do formato estou ciente que será um trabalho com honorários a parte.

                Comprometo-me a seguir corretamente o tratamento, caso ocorra de dar um longo prazo de tempo sem
                comparecer a data marcada para o retoque, a micropigmentadora ficará isenta da responsabilidade do trabalho,
                estou ciente disso.
                 Marcação e confirmação de horário para realizar o retoque somente pelo telefone: ...

                 ATENTAR PARA A DATA DO RETOQUE. Em caso de intercorrências não podendo comparecer a consulta favor
                ligar e desmarcar no prazo de 24 horas, pois caso contrário perderá o direito ao retoque e pagará o valor de uma
                MICROPIGMENTAÇÃO R$ .... REAIS.

                Declaro que não me enquadro na lista de "clientes de riscos", nem apresento nenhuma doença infecto-
                contagiosa, não apresento nenhum sintoma de debilidade imunológica, não sou dependente de álcool ou drogas.
                E confirmo serem verdadeiras as declarações acima, assumindo total responsabilidade por quaisquer omissões
                ou erro das mesmas.

                Certifico que todos os itens acima me foram expostos detalhadamente e que não ficou nenhuma dúvida.
                AUTORIZAÇÃO USO DE IMAGEM E FILMAGEM:

                Autorizo também que fotografe/filme o "antes" e o "depois" gratuitamente para efeito de avaliações,
                documentação, e que este material seja ou não com fins comerciais (divulgação), via folder, cartões, banner,
                internet e quaisquer outros tipos de divulgação.

                ASSIM SENDO, FIRMO A PRESENTE AUTORIZAÇÃO.

                _________ DE _____________________ DE 2020

                ASSINATURA DA(O) CLIENTE ___________________________________________________________

            <input type="button" class="btn btn-warning" value="Imprimir / Pdf" onclick="imprimir_micro()">

    function escrever() {
    //Campos do Formulário
    var cliente = document.querySelector('#clientes').value
    let datade = document.querySelector('#datade').value
    let problema = document.querySelector('#problemas').value
    let pagamento = document.querySelector('#pagamento').value

    let marca = document.querySelector('#marca').value
    let abertura = document.querySelector('#abertura').value
    let validade = document.querySelector('#validade').value
    let cor1 = document.querySelector('#cor1').value
    let cor2 = document.querySelector('#cor2').value
    let marca2 = document.querySelector('#marca2').value
    let abertura2 = document.querySelector('#abertura2').value
    let validade2 = document.querySelector('#validade2').value
    let cor11 = document.querySelector('#cor11').value
    let cor22 = document.querySelector('#cor22').value

    //Escrevendo Conteúdo
    client.innerHTML = cliente + '.  '
    let formatoData = new Date()
    datade = formatoData.toLocaleString()
    dateof.innerHTML = datade
    problem.innerHTML = problema
    payment.innerHTML = pagamento

    brand.innerHTML = marca
    date_open.innerHTML = abertura
    validity.innerHTML = validade
    color1.innerHTML = cor1
    color2.innerHTML = cor2
    brand2.innerHTML = marca2
    date_open2.innerHTML = abertura2
    validity2.innerHTML = validade2
    color11.innerHTML = cor11
    color22.innerHTML = cor22
}

function imprimir_micro() {
    let ficha = document.getElementById('micro')
    let imprime = ficha.innerHTML
    window.print(imprime)
}

Comment: Não entendi muito bem, você quer selecionar o nome do cliente e através disso filtrar o telefone, data nasc, etc... e exibir esses dados no span?
Comment: Isso exato. Após localizar o cliente, os outros dados dele são automaticamente preenchidos nos campos restantes.
Comment: Entendi, é possível sim e bem simples, pra isso você teria que fazer uma requisição assíncrona para o backend passando o nome como filtro (o que não é muito funcional, geralmente filtramos por ID) e recuperar esses dados com o javascript. Vou fazer um exemplo como resposta
Comment: Obrigado, estou aguardando a resposta
Answer: Então, para fazer isso você teria que fazer uma requisição assíncrona por meio de Ajax, passando seu devido filtro.
Vale lembrar que você está utilizando o campo "nome" para filtrar os usuários, e isso não é uma boa prática, visto que podemos ter usuários com o mesmo nome. Aconselho você a usar os IDs deles.
Agora, vamos ao código:
JS
var select = document.querySelector('#seu_select')

select.onchange = function() { // assim, toda vez que ocorrer uma mudança no select ele executará a função
    var valor = this.value

    var xhr = new XMLHttpRequest();

    xhr.open("GET", "seu_backend.php?nome="+ valor); // envia a requisição a url com o seu filtro
    xhr.send(null);

    xhr.onreadystatechange = function() { // chama uma função quando o documento for carregado
        if(xhr.readyState === 4) { // verifica se a resposta foi de sucesso
            var user = JSON.parse(xhr.response) // pega o json do backend

            // agora é só você dar innerHTML nos respectivos campos, exemplo
            spanNome.innerHTML = user.nome_usuario
        }
    }
}

Com esse trecho de script, você já consegue o que quer. Só para observações, essa função que eu fiz é um jeito bem antigo, mas suportada muito bem. Existem bibliotecas que lidam com AJAX muito bem, se você tiver liberdade, talvez seja interessante procurar por jQuery ou outras. Também tem o método Fetch que já é suportado pela maioria dos navegadores.
Agora ao PHP, você vai precisar de um arquivo preparado esperando essa rota, e nele, quando você obter o registro do usuário em um array, dar um echo no resultado, e somente isso, por meio do json_encode. É bem importante você dar um exit() após o retorno dos dados;
$conn = // sua função de conexão
$sql = // sua query para obter o usuario, filtrando o usuario
$exec = // seu meio de executar as queries, lembre-se de dar bind no valor, e não botá-lo na query, evitando SQL Injection
if($query) {
 echo json_encode($query->fetch(PDO::FETCH_ASSOC);
exit();
}

Pronto, assim você vai conseguir o que quer, espero ter ajudado!!


Not getting any response using fetch()

Question: I am trying to send a http POST request using the JS fetch API, but I am not receiving any response, although the request goes through to the server and the data is posted as expected.
This is the code I am using in the frontend:
fetch('http://127.0.0.1:8000/users/add', {
    method: 'POST',
    mode: 'no-cors',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        "id": "johndoe1234",
        "name": "John Doe",
        "card": "bhgst-xxxx",
        "permissions": 1
    })
}).then(resp => console.log(resp))

The error I am getting is as follows:
devtools screenshot:

It works fine using Postman (And also using Python requests). This is the expected response (I get this same response using Postman).
{
    "card": "bhgst-xxxx",
    "id": "johndoe1235",
    "name": "John Doe",
    "permissions": 1
}

Comment: `type: 'opaque'` - Is the browser console telling you about any CORS issues?
Comment: Without the `mode: no-cors` it does tell me about a CORS issue. But in the server the response header is set to `Access-Control-Allow-Origin: *`
Answer: You need to use .json() to parse the body text as JSON.
fetch(...).then(res => res.json()).then(console.log);

Comment: Assuming you meant `.then(json => console.log(json))` at the end there, no it doesn't help since the response body is `null` as shown in my devtools screenshot. Using this suggestion (with the correction) I get this error: `Uncaught (in promise) SyntaxError: Unexpected end of input`
Comment: @Denisovich `.then(console.log);` is exactly the same as `.then(json => console.log(json))` in this case. Now this appears to be an issue with your request not being allowed. Do you have CORS configured properly?
Comment: I have this in my server side code `w.Header().Set("Access-Control-Allow-Origin", "*")`
Comment: @Denisovich You may also need to configure allowed methods and allowed headers.
Comment: I have solved the issue with some help, looks like the `no-cors` was causing all the problems setting the status to zero. It was indeed a CORS issue and I have taken care of it. Thank you so much for the help
Comment: If you have solved your problem, could you please post an answer yourself describing how you did it?

Not getting any response using fetch()


4 row 4 columns bootstrap responsive carousel animation script

Question: I need this type of 4 row 4 columns bootstrap responsive carousel animation script

first slide is workingin 4 row and 4 column but second slide is displayed only one row and 4columns only, how to display the 4 row and 4 columns in carousel
Comment: please add your code on jsfiddle.
Comment: @PratikDeshmukh The OP shared his code, explain well the context....
Answer: You have multiple item.active in your carrousel, it's not good.
If you want 4 rows and 4 columns in each slide, so you have to set 4 rows with 4 columns in each slide too.
Bootply : http://www.bootply.com/9o6kcnGsWp
HTML:

Answer:


DNS wildcard entry doesn't resolve correctly (Microsoft DNS Server)

Question: I am trying to set up a wildcard entry in MS DNS Server (on Windows Server 2008 within Active Directory) so that requests for all subdomains resolve to the same IP address. For example:
name1.my.subd.plop.com >>> 192.168.255.4
name2.my.subd.plop.com >>> 192.168.255.4
anythingyouwant.my.subd.plop.com >>> 192.168.255.4
I believe this should be simple but simply cant get it to work! I have tried two options, A records and CNAME records.
The A record in the plop.com domain is simply:
*.my.subd           A   192.168.255.25
When I use nslookup to resolve a domain it doesn't report an error OR an IP address. Dig output:
C:\Users\myusername>dig anything.my.subd.plop.com
<code>; <<>> DiG 9.10-P2 <<>> anything.my.subd.plop.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55062
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1280
;; QUESTION SECTION:
;anything.my.subd.plop.com.       IN      A

;; AUTHORITY SECTION:
plop.com.           3600    IN      SOA     dns1.plop.com. admin.plop.com. 2012291129     900 600 86400 900

;; Query time: 2 msec
;; SERVER: 192.168.255.10#53(192.168.255.10)
;; WHEN: Wed Jul 23 16:42:31 GMT Summer Time 2014
;; MSG SIZE  rcvd: 113
</code>
From a client command prompt PING it simply fails:
<code>C:\Users\myusername>ping anything.my.subd.plop.com
Ping request could not find host anything.my.subd.plop.com. Please check the name
and try again.
</code>
If I use a CNAME entry with an "*" nslookup reports the correct IP address but the client PING fails in the same way as above.
I am hoping this is a simple error that someone can help with, I dont mind looking silly if I can get it working, it is driving me nuts!!
More info:
I have created a new zone on my DNS server and added a similar wildcard entry. This works as expected.
I have changed my zone from a Primary Zone to an Active Directory - Integrated Primary which has had no impact on the response.
I added a wilcard A record (*) at the "root" level (i.e. *.plop.com) and this also fails in the same way.
Comment: Can you include `dig` output that shows off the problem? Also, the trailing dot in the owner name column looks incorrect in the wildcard record in the question but maybe that is more of a question formatting error than anything significant?
Comment: I have added some nslookup output for the CNAME lookup. The text with the dot is created for me by the Windows GUI...
Comment: Ok, but what you added looks like something that worked(?). I was hoping you would add something that shows off the problem. (Also, I think you'll be better off with `dig` in the long run if you're working with dns. It does what you asked and shows the full result, it's also the defacto standard in dns troubleshooting.)
Comment: Thank you Håkan! I have installed dig and using that now. I have added output for the A record lookup which doesn't fail BUT doesn't return an IP address. I have also added the output from the PING command which fails to look up the domain. I removed the nslookup output for CNAME as, as you said, this is working as you'd expect...
Comment: So now it's the actual record listed above in the question (`*.my.subd A 192.168.255.25`) that is present in the zone? It's worth noting that you're not getting an `NXDOMAIN` response but rather an empty `NOERROR` response. This indicates that it is a name that exists but that it doesn't have an `A` record specifically. Is there some other kind of record for `anything.my.subd.plop.com`? The coverage of a wildcard will end at any name that exists.
Comment: *.my.subd A 192.168.255.25 is the record in the zone file (I do not edit this directly but through the GUI), there is no record for "anything.my.subd.plop.com". I often use different domains to test, e.g. kl23j4.my.subd.plop.org, monkey.my.subd.plop.org, help.my.subd.plop.org etc
Comment: Can you share more context (ideally the whole zone) so that one can better understand what is actually going on?
Comment: Hi Håkan, I'd prefer not to publicly publish our private DNS entries, perhaps I could mail them to you?
Answer: Oh the relief! I have found out why it wasn't working as I expected :-)
My DNS server was set to "Use WINS forward lookup" (Right click the zone and select Properties, choose the WINS tab and deselect "Use WINS forward lookup").
Once deselected it all worked as I expected....
Comment: DNS on Windows Server 2008 R2, can confirm this worked for me too.
Answer: Did you lookup the name before the wildcard record was created? The client and/or/both the DNS server will have cached this negative lookup result which will cause your subsequent lookups to still fail after the record was created. I think default is 24 hrs for it to timeout on its own. Try "ipconfig /flushdns" on the client and/or cycling the DNS service on the server to flush the cache there.
Comment: The dig output in the question shows that the `aa` flag is set, meaning this is an authoritative answer, not a potentially cached recursive lookup.
Comment: (Negative caching will be based on the `SOA` `MINIMUM` field.)
Comment: I have flushed dns and restarted DNS services to see if it helps. It hasn't. I am also expecting any host to resolve (thanks to the wildcard) so I try new "random" stuff everytime (e.g. wdfwf.my.subd.plop.org) and they still dont work.


i want to draw circle around my current location excatly 1 kilometers readius

Question: hi friends i want to draw circle around my current location exactly 1 kilometer radius so wat can i do.....i able to draw circle but how to put radius so it becomes exactly one kilometer..
Comment: Have a look at this code. http://code.google.com/p/geobeagle/source/browse/trunk/GeoBeagle/src/com/google/code/geobeagle/activity/map/FixedMyLocationOverlay.java?spec=svn1086&r=1086 ..it may help you to do your task.
Answer: At a high level:

Get the bounding coordinates of your current map view.
Use your coordinates to compute the distance either horizontally or vertically across your map.  Convert your distance to meters, if necessary.
Divide your distance in meters by the horizontal or vertical resolution (in pixels) of your map view.  This gives you the number of meters per pixel at your current zoom level.
Evaluate 1000 / <meters per pixel> to determine the number of pixels in 1 kilometer at the current zoom level.  This is the radius of your circle.
Draw your circle using the radius you got in step 4.


Using Filter on NULL Values in Views 3

Question: I'm using Drupal 7 with views 3.
I am listing the student fees in a view and one of the field in view results is pid (payment id) which has some numeric value or NULL value. The NULL value means the payment is unpaid. I have used a custom field handler to show in view result as paid and unpaid for pid = some value as Paid and pid = Null value as Unpaid.
I want a filter on this field also which will have a drop down of two options as paid and unpaid. Which views filter I should use and how can I rename the drop down options?
hook_views_data()
<code>// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_WHICH_ONE_I_SHOULD_USE',
    ),
    );

class fee_management_handler_field_payment_status extends views_handler_field {
    function construct() {
    parent::construct();
    $this->additional_fields['pid'] = 'pid';
  }
  function render($values) {
    $pid = $this->get_value($values, 'pid');
    if (!empty($pid)) {
            return 'Paid';
        }
        return 'Unpaid';
  }
};
</code>
Thanks in advance for your help.
Answer: I have implemented this custom filter. All Thanks and credit goes to Amar :). I am just sharing the code.
<code>// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'fee_management_handler_filter_payment_status',
      'numeric' => TRUE,
    ),
    );
</code>
Handler
<code>class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    function query() {
    // as per your database st
        ;

  }

}
</code>

Using Filter on NULL Values in Views 3


SAT Prep Triangle Equation

Question: I got this problem from my teacher and don't know how to solve, could someone please help?
(SAT Prep) In △ABC, ∠B = 90°, BH = AH, and the ratio of m∠A to m∠C is 1:2. Find m∠BHA?
<code>    A. 100°
    B. 90°
    C. 120°
    D. 60°
</code>

I know that m∠A = 30°, and that m∠C = 60°
Comment: Use the fact that $\triangle BAH$ is isosceles.
Answer: Hint: Let us denote $$\angle{AHB}=\beta$$ and$$\angle{ACH}=\gamma$$. Since we have $AH=HB$ we get
$$\beta=\pi-2\alpha$$ and $$\alpha+\gamma=\frac{\pi}{2}$$ since we have $$2\alpha=\gamma$$ we get $$\alpha=30^{\circ}$$ and $$\beta=120^{\circ}$$
Comment: I'm sorry, I don't know enough math to understand this answer yet.
Comment: @BeastCoder2 The solution of Dr. Sonnhard is the most simplified version of this problem ever. Out of couriosity, in which grade do you read? Then you must learn because there is no age of learning.
Comment: @AnirbanNiloy Given the level of the question being asked, it is in my experience that anyone asking these types of questions is not likely to have a good understanding on the relationship between radians and degrees. While Dr. Sonnhard's answer is incredibly simple to anyone with significant experience in Math, right from the start it makes use of radian measure by letting $\beta = \pi - 2\alpha$. While this is completely equivalent to saying $\beta = 180 - 2\alpha$, this very likely isn't obvious to beginning students, and neither is the implicit conversion from radians to degrees at the end
Comment: @user516079 I haven't enough experience yet to understand your comment!! I thought all relaionship were confined within degrees instead of using radians. I never noticed such an equation $\beta = \pi-2\alpha$.  for your better explanation.
Answer: $\triangle BAH$ is isosceles because it has two equal sides.
This means that $m(\angle BAH) = m\angle ABH$ because of base angle theorem.
Then, $m\angle BHA = 180 - (m(\angle BAH) + m(\angle ABH))$ (because the sum of the measures of the angles in a triangle is $180$)
But since $m(\angle BAH) = m(\angle ABH) = 30$, we simply have
$m(\angle BHA) = 180 - (30 + 30) = 120$
Comment: Please use
[MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
to format math on this site.

SAT Prep Triangle Equation


Remover o primeiro elemento de uma lista duplamente encadeada - C

Question: Estou com problema para remover o primeiro nó da minha lista duplamente encadeada. Eu criei uma função que retorna o tipo da lista (Value) para realizar a operação, ao mostrar os elementos da lista dentro da função é possível ver que ela realiza a remoção do primeiro elemento, contudo ao retornar ela para main e listar ela utilizando a função printList() ela parece mostrar o primeiro elemento que supostamente foi removido.
Segue o meu código completo abaixo. Desde já agradeço.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CLEAN "cls"
#define PAUSE "pause"

typedef struct Value{
  int value;
  struct Value *next;
  struct Value *prev;
} Value;

Value *list;

Value *start(){
  return NULL;
}

void freeList(Value *list){
    Value *v = list;
    while(v != NULL){
        printf("Liberando o canal: %d\n", v->value);
        Value *temp = v->next;
        free(v);
        v = temp;
    }
}

int isEmptyList(Value *list){
    return (list == NULL);
}

void menu(){
    printf("\t _______________________________________________________________");
    printf("\n\t|O que Voce Deseja Fazer?\t\t\t\t\t|\n\t|");
    printf("\t\t\t\t\t\t\t\t|\n\t|[01] - Adicionar valor de forma ordenada;\t\t\t|");
    printf("\n\t|[02] - Adicionar valor no fim da lista;\t\t\t|");
    printf("\n\t|[03] - Listar todos os valores;\t\t\t\t|");
    printf("\n\t|[04] - Mostrar o maior valor;\t\t\t\t\t|");
    printf("\n\t|[05] - Mostrar o menor valor;\t\t\t\t\t|");
    printf("\n\t|[06] - Remover ultimo valor;\t\t\t\t\t|");
    printf("\n\t|[07] - Remover primeiro valor;\t\t\t\t\t|");
    printf("\n\t|[08] - Sair;\t\t\t\t\t\t\t|");
    printf("\n\t|_______________________________________________________________|\n");
    printf("\t Opcao: ");
}

Value *insertOrdered(Value *list){
  int value;
  Value *aux = list;
  Value *aux2 = list;
  Value *new = (Value*) malloc(sizeof(Value));

  printf("Informe um valor: ");
  scanf("%d", &value);
  new->value = value;
  if(aux == NULL){
    new->next = aux;
    new->prev = NULL;
  }else{
    while(aux != NULL){
      if(new->value < aux->value){
        new->next = aux;
        if(aux->prev != NULL){
          aux2->next = new;
          aux->prev = new;
          new->prev = aux2;
          return list;
        }else{
          new->prev = NULL;
          aux->prev = new;
          return new;
        }
      }else if(aux->next == NULL){
        aux->next = new;
        new->prev = aux;
        new->next = NULL;
        return list;
      }
      aux2 = aux;
      aux = aux->next;
    }
  }
  return new;
}

Value *insertEnd(Value *list){
  int value;
  Value *aux = list;
  Value *new = (Value*) malloc(sizeof(Value));

  printf("Informe um valor: ");
  scanf("%d", &value);
  new->value = value;
  while(aux != NULL){
    if((aux->next == NULL) && (new->value > aux->value)){
      aux->next = new;
      new->prev = aux->next;
      new->next = NULL;
    }else if((aux->next == NULL) && (new->value < aux->value)){
      printf("O numero informado e menor que o ultimmo valor\n");
      printf("A ordem da lista sera comprometida\n");
      break;
    }
    aux = aux->next;
  }
  return new;
}

void printList(Value *list){
    Value *v = list;
    if(isEmptyList(v)){
        printf("Essa lista está vazia!\n");
    }
    else{
        while(v != NULL){
            printf("\nValor: %d\n", v->value);
            v = v->next;
        }
    }
}

void findBigger(Value *list){
  Value *v = list;
  while(v != NULL){
    if(v->next == NULL){
      printf("O maior valor da lista e: %d\n", v->value);
    }
    v = v->next;
  }
}

void findSmaller(Value *list){
  printf("O maior valor da lista e: %d\n", list->value);
}

Value *removeLast(Value *list){
    Value *v = list;
  if(isEmptyList(v)){
        printf("Essa lista está vazia!\n");
    }else{
    while(v != NULL){
      if(v->next == NULL){
        v->prev->next = NULL;
        printf("Ultimo elemento removido com sucesso\n");
        return list;
      }
      v = v->next;
    }
  }
}

Value *removeFirst(Value *list){
  Value *v = list;
  if(isEmptyList(v)){
        printf("Essa lista está vazia!\n");
    }else{
    if(v->next != NULL){
      v->next->prev = NULL;
    }
    list = v->next;
    v->next = NULL;
    printf("\nValor: %d\n", list->value);
    return list;
  }
}

int main(){

  int op;

  list = start();

  do{
    system(CLEAN);
    menu();
    scanf("%d", &op);
    switch(op){
    case 1:
      system(CLEAN);
      list = insertOrdered(list);
      system(PAUSE);
      break;
    case 2:
      system(CLEAN);
      insertEnd(list);
      system(PAUSE);
      break;
    case 3:
      system(CLEAN);
      printList(list);
      system(PAUSE);
      break;
    case 4:
      system(CLEAN);
      findBigger(list);
      system(PAUSE);
      break;
    case 5:
      system(CLEAN);
      findSmaller(list);
      system(PAUSE);
      break;
    case 6:
      system(CLEAN);
      removeLast(list);
      system(PAUSE);
      break;
    case 7:
      system(CLEAN);
      removeFirst(list);
      system(PAUSE);
      break;
    case 8:
      break;
    }
  }while(op != 8);

    system(CLEAN);
    printf("O programa esta liberando a memória\n");
    freeList(list);
    system(PAUSE);

  return 0;
}

Answer: Gosto da forma que estruturou seu programa, mas o seu problema acontece por causa de um mal entendido, ou falta de atenção na remoção tanto no caso de remover o primeiro elemento, quanto no caso de remover o último, segue abaixo como deveriam ser alguns detalhes destas funções, comentando onde você errou de forma comparativa.

Value *removeLast(Value *list)
Value *removeFirst(Value *list)

Primeiramente, se sua função não é utilizada para retornar nenhum valor, não defina que ela retorne nenhum valor. No seu código você apenas chama essas funções e o retorno dela não vai para lugar algum, não faça isso, tudo bem que no Windows não há nem warning, mas em outros casos há, e, particularmente, eu prefiro programar de forma a não causar warnings, mas não é um problema, só um conselho.
Outro problema nas declarações destas funções é que você passa um parâmetro cujo nome é idêntico ao de uma variável global, tudo bem que a variável que você passa como parâmetro quando chama estas funções é igual, e é mesmo recomendável que você crie funções genéricas, no caso, que aceite qualquer struct Value, e sua função pode acabar se confundindo quanto a usar a variável local ou a global sempre que você usa list nela. Eu particularamente condeno o uso de variáveis globais, mas se preferir continuar usando, não passe nenhum valor para essas funções, utilize list como variável global mesmo, ou mude o nome do parâmetro para torná-la mais genérica, ficando assim:
void removeLast()
void removeFirst()

Quanto ao removeLast, você tem alguns problemas no fluxo.
Se a sua lista estiver vazia, você corretamente imprime que ela está vazia, se ela não estiver, você deve verificar se o "next" dela é diferente de NULL, porquê ai você sabe que esta lista não possui apenas um único valor e deve usar a variável v para percorrer a lista até encontrar o último Value.
Se não fizer esta verificação, não existirá "prev" para você fazer o "v->prev-next=NULL" e a referência de list continuará diferente de NULL também, apenas a referência local de v estará nula.
Então ficaria assim:
if(isEmptyList(v))
    printf("Essa lista está vazia!\n");
else if(v->next != NULL)
{
    /*É possível otimizar porquê já sabemos que o primeiro elemento não é o último,
    mas por didática vou deixar assim*/

    while(v != NULL)
    {
        if(v->next == NULL)
        {
            printf("Ultimo elemento, %d, removido com sucesso\n",v->value);
            v->prev->next=NULL;
            free(v);
            return;
        }
        v = v->next;
    }
}
else
{
    ...

No caso do else, então, é apenas se a lista não estiver vazia mas o início dela já for o último, ou seja, ela contém apenas um valor, e, portanto, a própria list deve ser liberada e sua referência deve ser reiniciada, definindo ela como NULL ou iniciando ela pela função start() novamente, que é basicamente a mesma coisa:
else
{
    printf("Ultimo elemento, %d, removido com sucesso\n",list->value);
    free(list);
    list=start(); //list=NULL;
}

Perceba que definir v como NULL neste caso não seria correto, já que list ainda guardaria o endereço para a struct que foi liberada, que ainda está na memória. As outras operações como a de obter o valor usando v->value e free(v) ainda funcionaria, mas list ainda guardaria o endereço para a estrutura que você liberou.
É importante saber que a função free() não apaga os dados da memória, eles continuarão lá naquele endereço, a função free() apenas avisa ao Sistema Operacional que aquele espaço de memória pode ser usado para salvar outros dados, e portanto, qualquer acesso a essa área de memória é permitida, mas a qualquer momento pode ter dados que não são mais os que você colocou lá, e sim o que outros processos colocaram. A memória não é zerada quando você libera ela, você apenas libera ela, ela agora está disponível para ser utilizada por outros processos, o que você colocou lá ainda está lá até que seja sobrescrito por outro processo ou por você mesmo.
Portanto, se você não definir - no caso da lista conter apenas um elemento - que a própria variável list é NULL, tudo que for feito com a variável list ainda funcionará, como no seu caso, ainda irá imprimir na tela esse valor porquê você apenas permitiu que o SO sobrescreva as informações ali, elas não estão mais protegidas e isso pode causar efeitos indesejados.

O mesmo problema também ocorre para remover o primeiro elemento, ficaria assim:
if(isEmptyList(list))
    printf("Essa lista está vazia!\n");
else
{
    printf("\nValor Removido: %d\n", list->value);
    if(list->next!=NULL)
    {
        list = list->next;
        free(list->prev);
        list->prev=NULL;
    }
    else
    {
        free(list);
        list = start(); //list = NULL;
    }
}

mas no exemplo que você forneceu, na remoção do primeiro elemento, você acaba por destruir o acesso a todos os outros valores porquê você define que a lista é o próximo, e que o próximo dela é NULL. O correto a se fazer é basicamente liberar a raiz da lista, ou seja, a própria lista, mas fazer com que list agora seja o próximo dela, e que o próximo dela tenha anterior NULL, para não haver referência ao início original da lista. Fiz isto simplesmente movendo list para o próximo e liberando o "prev", que era a list anteriormente.
Observe que também há o problema da lista com um único elemento, porquê ela não terá "next" para fazer isso, então deve-se literalmente liberar a própria list e reiniciá-la usando start() ou atribuir para NULL.

Espero que estas considerações tenham lhe ajudado, qualquer dúvida continue explorando a plataforma, espero que você tenha aprendido mais sobre como é o funcionamento dos ponteiros e endereçamento, certamente meu detalhismo é confuso, as vezes é confuso até para quem já tem experiência com isso, então não se sinta mal, programação, principalmente em C, é assim mesmo!
Comment: Muito obrigado sua resposta foi de muita ajuda, também agradeço os conselhos, vou tentar para de usar variáveis globais hehe, e não tinha pensado em inicializar a lista novamente. Confesso que tive que ler mais de duas vezes algumas partes para entender o que você quis dizer, mas agora entendo mais sobre endereçamento.
Comment: Consegui fazer outro exercício que envolve a função de remover no inicio, meio ou fim, sem muitos problemas. Muito obrigado.


Effects of vector pushback on element address

Question: I have a vector of class objects. A function randomly choses two elements and return their addresses.
Now using these two elements, I want to generate two new objects of the same class and add them to the vector by using push_back.
Here is the address of the two parent elements:
No problem here. The first child object is then generated, and I use vector_pushback to add it to the end of the vector. The problem is, after the push_back command has been executed, it seems like the addresses of the parent objects change. Here is the state of debugger after push_back:
As you can see, the addresses obviously stay the same, but it seems like they point to garbage values after push_back. To my understanding, push_back adds an element at the end of the vector. Therefore I expect the address of the 2 elements to not change at all.
What's wrong?
Answer: TL;DR version:
An insertion operation can invalidate any pointers, references or iterators to elements of a std::vector.
Full explanation:
A std::vector has two useful metrics:

size, which is the number of elements stored.
capacity, which is the number of elements it's currently capable of storing.

capacity >= size at all times.
The capacity is the length of the internal dynamically-allocated array.*  When you insert an element, the size increments by 1.  But once it reaches capacity, a new, larger array must be allocated (hence increasing the capacity).  This requires all the elements to be copied across, and the originals to be deleted.  So all their addresses change.

* This is the typical internal implementation of a std::vector.
Comment: Wow, I wish there was a +2 button
Answer: push_back can cause reallocation and moving of all elements in the vector, if the space that's currently assigned for element storage cannot contain the new element.


What is this time series model and how to produce it in R?

Question: I know that $Y_{t} = a + bY_{t-1} + \epsilon$ is named as autoregression model. I am dealing with the model like: $Y_{t} = a + bY_{t-1} + cX_{t} + dX_{t-1} + \epsilon$. I could not find any useful information when I searched "multivariate autoregression". Could anyone tell me the model name and how to do it in R?
Comment: Sure they do. The link was just for distributed lag models (lacking the 'autoregresive' part), but that was just to get you started. Look at the first equation here for example: http://mail.tku.edu.tw/chenyiyi/ADL.pdf That is exactly what you have, is it not?
Comment: You can fit these type of models in R using basic `lm`, but you need to create the lagged variables by hand. Package *dynlm* allows specifying lags in the formula interface, the R code for ardl(1,1) model would be `dynlm(y~L(y,1)+x+L(x,1))`. Also package *midasr* allows fitting of such models, the code would be `midas_u(y~mls(y,1,1)+mls(x,1,0:1))`.
Comment: Next time when you encounter "multivariate autoregression", you may look at "vector autoregression".
Comment: It's called an Autoregressive distributed lag model. https://en.m.wikipedia.org/wiki/Distributed_lag
Comment: AR distributed lag model doesn't contain the response as predictor
Comment: Could you clarify what "do it in R" might mean?  Do you have data you wish to fit with this model, or do you wish to create data according to this model?
Answer: Combining comments by hejseb and mpiktas, which answer this question:

It's called an Autoregressive distributed lag model:
https://en.wikipedia.org/wiki/Distributed_lag

The [previous] link was just for distributed lag models (lacking the
'autoregresive' part), but that was just to get you started. Look at
the first equation here for example: https://mail.tku.edu.tw/chenyiyi/ADL.pdf
That is exactly what you have, is it not?

$-$  hejseb

You can fit these type of models in R using basic lm, but you need to
create the lagged variables by hand. Package dynlm allows specifying
lags in the formula interface, the R code for ardl(1,1) model would be
dynlm(y~L(y,1)+x+L(x,1)). Also package midasr allows fitting of such
models, the code would be midas_u(y~mls(y,1,1)+mls(x,1,0:1))

$-$ mpiktas


How to declare a method that takes an instance as an argument in Python?

Question: I know it is probably a stupid question, but I am new to OOP in Python and if I declare a function def myFunction( b) and pass an instance of an object to it, I get TypeError: expected string or buffer.
To be more specific, I have a following code that I use to parse a summary molecular formula and make an object out of it.
class SummaryFormula:
    def __init__( self, summaryFormula):
        self.atoms = {}
        for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):
          symbol = atom.group(1)
          count = atom.group(2)

    def extend( self, b):
        # these are the two dictionaries of both molecules
        originalFormula = self.atoms.copy()
        self.atoms.clear()
        addAtoms = SummaryFormula( b)

        # and here both dictionaries are merged
        for atom in addAtoms.atoms.keys():
          if atom in originalFormula.keys():
            self.atoms[ atom] = originalFormula[ atom]
            self.atoms[ atom] += addAtoms.atoms[ atom]
          else:
            pass
        for atom in originalFormula.keys():
          if atom not in self.atoms.keys():
            self.atoms[ atom] = originalFormula[ atom]

 #this is what works now
 test = SummaryFormula( "H2CFe2")
 test.extend("H5C5") #result is a molecule H7C6Fe2

 #this is what I want instead
 test = SummaryFormula( "H2CFe2")
 toExtend = SummaryFormula( "H5C5")
 test.extend( toExtend)

Thank you, Tomas
Comment: That is not because of this declaration. Some part of the function definition is throwing the TypeError exception. As others said, you should post your function's code and what you have passed to it.
http://www.catb.org/esr/faqs/smart-questions.html
Comment: Can you provide a code sample?
Comment: I think, we need a little bit more context in order to help you. What's the actual definition of `myFunction`? Is it a plain function? A method? What's the stack trace, which comes along with the exception?
Comment: Care to show us the function definition? I can't say anything using the provided info.
Comment: You should show your function's code to help us answer your question.
Comment: You're missing an "import re" at the top of the file.
Comment: You don't do anything with `symbol` and `count` in __init__.
Answer: Firstly, the program needs to include the re module.
Secondly, you have a typo at line 4:
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", SummaryFormula):

should read
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):

i.e. lower-case s in summaryFormula.
SummaryFormula refers to the name of the class while summaryFormula refers to the second parameter (after self) of the __init__ method.
Third, the line addAtoms = SummaryFormula(b) is passing an instance of SummaryFormula as argument b (assigned in top-level part of script test.extend(toExtend).
The fixed program should look like:
import re

class SummaryFormula:
    def __init__(self, summaryFormula):
        self.atoms = {}
        for atom in re.finditer("([A-Z][a-z]{0,2})(\d*)", summaryFormula):
          symbol = atom.group(1)
          count = atom.group(2)

    def extend( self, b):
        # these are the two dictionaries of both molecules
        originalFormula = self.atoms.copy()
        self.atoms.clear()

        # PASS AN APPROPRIATE VALUE HERE!
        addAtoms = SummaryFormula("SOME STRING")

        # and here both dictionaries are merged
        for atom in addAtoms.atoms.keys():
          if atom in originalFormula.keys():
            self.atoms[ atom] = originalFormula[ atom]
            self.atoms[ atom] += addAtoms.atoms[ atom]
          else:
            pass
        for atom in originalFormula.keys():
              if atom not in self.atoms.keys():
            self.atoms[ atom] = originalFormula[ atom]

#this is what works now
test = SummaryFormula("H2CFe2")
test.extend("H5C5") #result is a molecule H7C6Fe2

#this is what I want instead
test = SummaryFormula("H2CFe2")
toExtend = SummaryFormula("H5C5")
test.extend(toExtend)

with "SOME STRING" replaced by the intended string literal or string variable reference. I don't know the exact intention of the program so I'll leave it up to somebody else to determine what this program should be passing to the constructor of SummaryFormula at this point.
Hope that helps!
Comment: Thank you, I repaired that, but that still doesn't solve the problem.
Comment: Extended answer with comment about "addAtoms = SummaryFormula( b)" line.
Answer: Richard Cook is correct. There is another problem, however: In extend, you say:
addAtoms = SummaryFormula( b)

Thus, a SummaryFormula instance is passed into the __init__ method of SummaryFormula. Here (modulo the typo mentioned before), this object is given to re.finditer:
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula)

The function re.finditer expects a string; it doesn't know what to do with a SummaryFormula instance.
There are a few ways to fix this. The immediately simplest is to check whether you already have a SummaryFormula instance before trying to create one:
if isinstance(b, SummaryFormula):
    addAtoms = b
else if isinstance(b, str):
    addAtoms = SummaryFormula(b)
else:
    raise TypeError("Expected a SummaryFormula or equivalent string.")

Answer: In short you can pass any object to a function, including instances of classes you created.
More generally, everything in Python is an object.  This is a key concept in Python so if you're new to the language spend some time getting familiar as it will help your write code which is more concise and pythonic.
The error you get isn't from passing a class instance object, but rather is generated somewhere (see other answers as they seem to be onto it) else in your code by another function or operation which is expecting a string, or string-like object to operate on.  For example you can generate a similar error by doing:
>>> a = 2
>>> open(a, 'r')

TypeError: coercing to Unicode: need string or buffer, int found

Here the error occurs because the file opening function open is expecting a string rather than an integer.


Get all checked items and delete them using button_to

Question: I have a table with some data and there is also a checbox in each table row and each of them has an unique id like 'chk_1'. There is a button delete.
= button_to 'delete', {controller: 'users', id: '1'}, method: :delete

where id: '1' is just a stub. I want the button to delete all checked items. How can I do this?
Answer: There really isn't a way to do this in the RESTful way in which you are attempting to so.
I would just build a form (<%= form_tag("/users/delete_users", :method => "delete") %>) and submit it to your Users controller and write some code in that method to delete the check items.
Your checked items will be available in the params hash, and you can delete them all using something like this, assuming all checkboxes have the same "name" and the value of the checkboxes are the user's Id.
def delete_users
  users_to_delete = params[:users_to_delete]
  users_to_delete.each{ |user_id| User.find(user_id).destroy }
end

Comment: but I have many different buttons: for deleting, for activating.... How do I combine all these 'form_tag'? I mean, checkboxes in the main table should be placed inside form tag.
Comment: what does the view code look like for your `activate` action?
Comment: I can't help you if I can't see what you are trying to do.


Alter submitted by text and retain RDF tags

Question: I am looking to change the submitted by text from:
Submitted by author on Sun, 20/03/2011 - 22:54

to:
Date posted: 20 March 2011

I know how to alter the text in node.tpl.php but I do not know the function that will return the date formatted with the RDF tags around it. Does anyone have experience in this area?
Answer: The function that returns the content of that tag is date_iso8601().
To understand how those tags are output, you should look at rdf_preprocess_node() and rdf_process().


irreducible representation of a group

Question: Reduced group $C^\ast$-algebra of group $G$ is defined to be $G^*_{r}(G)=\overline{\lambda(L^1(G))}$ where $\lambda$ is left regular representation. My question is how to get a irreducible representation of $G$ from a irreducible representation of reduced group $C^*$-algebra $G^*_{r}(G)$? (In my question $G$ is a locally compact group)
Answer: You need an approximate identity for the convolution, i.e., a Dirac delta function at the identity of $G$. Then you can get a Dirac-$\delta$ at each $g$ by translating. Your representations $g$ amounts to $\pi(\delta_g)$. Of course, this can formally only done with nets.
To obtain that Dirac delta for general locally compact groups can be done via approximation of $G$ locally as a projective limit of Lie groups.

irreducible representation of a group


Web access to tableau server installed on google cloud instance with centos 7 as OS

Question: I created VM (virtual machine) instance on Google Cloud with CentOS 7 as OS to install Tableau Server and http access to it using set of commands from online free video. After successful installation I try to use web browser to get an access to Tableau Configuration and I see nothing but an error message "Connection took too long".
Pretty much I didn't do anything else yet because on video everything is right and smooth. Already asked owner of video but who knows how busy he is and if consider it his responsibility to answer the questions.
sudo -i
yum update -y
sudo yum install wget -y
wget https://downloads.tableau.com/tssoftware/tableau-server-2018-2-0.x86_64.rpm
chmod 777 tableau-server-2018-2-0.x86_64.rpm
sudo yum install tableau-server-2018-2-0.x86_64.rpm
adduser admin
passwd admin
usermod -aG wheel admin
systemctl status firewalld.service
systemctl disable firewalld.service
systemctl stop firewalld.service
su - admin
cd /opt/tableau/tableau_server/packages/scripts.20182.18.0627.2230/
sudo ./initialize-tsm --accepteula
sudo usermod -G tsmadmin -a admin
source /etc/profile.d/tableau_server.sh

After many starts and stops and checking the Tableau Server application status I still not able to have web access to configuration page.
Any suggestions please?
Answer: I would follow the Linux install docs.  You are missing a few steps like registration and configuring the initial node.
Also, you shouldn't install as su - admin.  You want to install in the user space using sudo.
When you do get the server up and running you should be able to run tsm status and see that Tableau Server is running.  If you still cannot reach the server after that then there is probably something going on with the networking with the GCP settings.


Eclipse: How to convert a web project into an AspectJ project and weave and run it using the AJDT plug in?

Question: What I want to do:

I want to use the @Configured annotation with Spring. It requires AspectJ to be enabled. I thought that using the AJDT plugin for compile time weaving would solve this problem. Before installing the plug in the dependencies which were supposed to be injected into my @Configured object remained null.

What I have done:

Installed the AJDT: AspectJ Development Tools plug in for Eclipse 3.4.
Right clicked on my web project and converted it into a AspectJ project.
Enabled compile time weaving.

What doesn't work:

When I start the Tomcat 6 server now, I get an exception*.

Other information:

I haven't configured anything in the AspectJ Build and AspectJ Compiler parts of the project properties.
JDT Weaving under Preferences says weaving is enabled.
I still have Java build path and Java Compiler under project properties. And they look like I previously configured them (while the above two new entries are not configured).
The icon of my @Configured object file looks like any other file (i.e. no indication of any aspect or such, which I think there should be). The file name is MailNotification.java (and not .aj), but I guess it should still work as I'm using a Spring annotation for AspectJ?
I haven't found any tutorial or similar which teaches: How to turn a Spring web application project into an AspectJ project and weave aspects into the files using the AJDT plugin, all within Eclipse 3.4. If there is anything like that out there I would be very interested in knowing about it.

What I would like to know:

Where to go from here? I just want to use the @Configured annotation of Spring. I'm also using @Transactional which I think also needs AspectJ.
If it is possible I would like to study AspectJ as little as possible as long as my needs are met. The subject seems interesting, but huge, all I want to do is use the above two mentioned Spring annotations.

*** Exception when Tomcat 6 is started:
Caused by: java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:spring-agent.jar
at org.springframework.context.weaving.DefaultContextLoadTimeWeaver.setBeanClassLoader(DefaultContextLoadTimeWeaver.java:82)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
... 41 more

Answer: Have you added spring-aspects.jar to your aspect path for the project?
In the project properties, under 'AspectJ Build' -> 'Aspect Path' try adding spring-aspects.jar and clean building the project.
Sorry you might have already done this - but you didn't mention it.
Comment: I haven't added it or done any specific configuration really (like stated above). I can't seem to find any good documentation for the AJDT plugin so I don't really know what I need to do. :-/
Answer: It looks like the compile time weaving isn't working. Try adding the below lines to your applicationcontext.xml
<context:load-time-weaver />
<context:spring-configured/>

You'll probably want to add the following xsd to the xml file also
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
For details see here:
http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-aj-ltw
Answer: You can use @Transactional without AspectJ.  Your configuration file should contain something like following to make it work:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
  http://www.springframework.org/schema/util
  http://www.springframework.org/schema/util/spring-util-2.5.xsd"
  >
<tx:annotation-driven/>

 tells spring to look for @transactional annotations when creating instances of configured beans. On finding such annotation, spring returns a dynamic proxy of the bean to the application code. This dynamic proxy ensures that whenever the annotated methods are called, spring is able to intercept it to provide intended transactional behavior. But the proxy-based AOP mandates that you code against interfaces and not concrete classes.


Gradient inequality in Morrey's and Gagliardo-Nirenberg inequality proofs

Question: I'm approaching for the first time functional analysis and in general "advanced math". In the book "Lecture Notes on Functional Analysis" by A. Bressan, in the Sobolev space chapter, I get stuck in two inequalities involving $\nabla u$. $$$$ 1) In the proof of Morrey's inequality: be $u \in C^{1}(\mathbb{R}^{n})\cap W^{1,p}(\mathbb{R}^{n})$; in the proof, the following set of coordinates is defined: $(r,\xi)=(r,\xi_{2}...\xi_{n}) \in \left[0,\rho \right] \times  B_{1}$, with $B_{\rho}:=\left( x=(x_{1},x_{2},...,x_{n});x_{1}=\rho,  \ \sum_{i=2}^{n} \ x^2_{i}\leq \rho^{2}\right)  $; to this system of coordinates, the point $x(r, \xi)=(r,r \xi)$ is associated (x belongs to a cone), moreover define $U(r,\xi)=u(r,r\xi)$. Here I got stuck (citing the text): since $|\xi|\leq 1$ the directional derivative of $u$ in the direction of the vector $(1,\xi_{2},\xi_{3},...,\xi_{n})$ is estimated by $$\left| \frac{\partial }{\partial r} U(r,\xi)\right|=\left| u_{x_{1}}+\sum_{i=2}^{n}\xi_{i}u_{x_{i}} \right| \leq 2|\nabla u(r,\xi)|.$$
$$  $$ 2) In the proof of Gagliardo-Nirenberg inequality:  be $f \in C^{1}_{c}\left( \mathbb{R}^{n} \right)$ , I got stuck in the following inequality: $$ \prod _{i=1}^{n} \left( \int _{-\infty}^{\infty}...\int _{-\infty}^{\infty} \left | D _{ x _{i}} dx _{1} dx _{2}... dx _{n}   \right | \right) ^{1/(n-1)} \leq \left ( \int _{\mathbb{R}^{n}}^{} |\nabla f|dx  \right )^{n/(n-1)} $$ $$$$ It seems to me that I miss something becouse in the book it appears that such inequalities involving $\nabla u$ and $ \nabla f $ are so straightforward; I probalby lack the knowledge of some identity or inequality, perhaps from calculus. Could anyone give me some hints? Thank you for your kindness, I apologize if it might be trivial, but I'm a rookie!
Comment: It appears that something is wrong with the formatting of the second inequality. Or perhaps the notation $D_{x_idx_1\ldots dx_n}$ is defined somewhere. Can you clarify it please?
Comment: Oh! yes, there is a typing error, I'll edit the question, Thanks!
Answer: The first one is Cauchy-Schwarz:
$$
\big|\sum_{i=2}^n\xi_iu_{x_i}\big|
\leq
\big(\sum_{i=2}^n\xi_i^2\big)^{\frac12}
\big(\sum_{i=2}^n|u_{x_i}|^2\big)^{\frac12}
\leq|\xi||\nabla u|
\leq|\nabla u|.
$$
Comment: Oh! how did I not see it?!. Thank a lot!!!
Answer:
It is as timur said for the first one - \begin{align}
\left| \frac{\partial }{\partial r} U\right|\overset{\substack{chain\\rule\\{\phantom{x}}\\}}=\left| u_{x_{1}}+\sum_{i=2}^{n}\xi_{i}u_{x_{i}} \right| \overset{\triangle ineq.}\le  |u_{x_{1}}|+\sum_{i=2}^{n}|\xi_{i}||u_{x_{i}}|  \overset{C-S}\le |u_{x_{1}}|+\sqrt{\sum_{i=2}^{n}|\xi_{i}|^2 } \sqrt{\sum_{i=2}^{n}|u_{x_{i}}|^2 }
\end{align} Now observe that \begin{align}|u_{x_1}| &\le \sqrt{\sum_{k=1}^n |u_{x_k}|^2} = |\nabla u|,\tag{GradientBound}\label{X}\\ \sqrt{\sum_{i=2}^{n}|\xi_{i}|^2 } &\le 1, \\
\sqrt{\sum_{k=2}^n |u_{x_k}|^2} &\le \sqrt{\sum_{k=\color{red}1}^n |u_{x_k}|^2}=|\nabla u|,\end{align}
which gives
$ \left| \frac{\partial }{\partial r} U\right| \le 2|\nabla u|$ as claimed.

I can confidently interpret $\prod _{i=1}^{n} \left( \int _{-\infty}^{\infty}...\int _{-\infty}^{\infty} \left | D _{ x _{i} dx _{1} dx _{2}... dx _{n}  } \right | \right) ^{1/(n-1)} \leq \left ( \int _{\mathbb{R}^{n}}^{} |\nabla f|dx  \right )^{n/(n-1)}$ as this part of the proof of the Gagliardo-Nirenberg-Sobolev inequality:
$$\prod _{i=1}^{n} \left( \int _{-\infty}^{\infty}\dots\int _{-\infty}^{\infty} | D_{ x _{i}}f| dx _{1} dx _{2}\dots  dx _{n}    \right) ^{1/(n-1)} \leq \left ( \int _{\mathbb{R}^{n}}^{} |\nabla f|dx  \right )^{n/(n-1)}$$ Indeed, this is what page 171 of Bressan's book says. This is also the proof in Evans.

To prove this, note that there is a product of $n$ terms on the left hand side, and there is an $n$ power on the left. This hints  that there may be an estimate that does not depend on which of the $n$ terms you are estimating. That is, it is enough to show that for each $i=1,2,\dots,n$,

$$ \left( \int _{-\infty}^{\infty}\dots\int _{-\infty}^{\infty} | D_{ x _{i}}f| dx _{1} dx _{2}\dots  dx _{n} \right)^{1/(n-1) } \le \left(\int _{-\infty}^{\infty}\dots\int _{-\infty}^{\infty} |\nabla f| dx_1dx_2\dots dx_n\right)^{1/(n-1)}$$
and this directly follows from the line marked $\eqref{X}$ above.
Comment: Oh thak you a lot!!! very clear explanations! I will edit the anwer because in Bressan, the $\xi$ vector strart with the index 2. Obviously the explanation remain still valid!
Comment: Oh, I didn't notice! I will change it


Using and interpreting nested manova in R

Question: I have measured the concentration of 7 elements in 30 Lakes. I have between 8 and 12 observations per Lake (i.e., I measured the concentration of all 7 elements upon each observation). I took more than one observation per Lake to account for within Lake variability. These Lakes can be classified into 3 nested grouping variables: Lake is nested within State which is nested within Region. My goal is to see if there is a difference in chemistry between each of the grouping variable, which elements are different between them, and which grouping variable best describes the variance between Lakes. My data is set up like this:
Lake  State  Region  Measure   Elm1   Elm2   Elm3   Elm4   Elm5   Elm6   Elm7
a      WY      2       1        …     …

Where Measure is the unique ID number for each of the 8-12 measurements per lake. This is a unique number throughout the dataset, so there is only 1 observation where Measure == 1.
I am having trouble finding an example that is similar to my design. How can I specify a nested manova model for this kind of design in R?
Answer: You can fit a model something like
mod <- lm(cbind(Elm1,Elm2,Elm3,Elm4,Elm5,Elm6,Elm7) ~ Region / State / Lake, data = dat)

Get omnibus tests from manova() and post-hoc comparisons using the emmeans package. e.g.
library(emmeans)
emm <- emmeans(mod, ~ Region | Elt, mult.name = "Elm")
emm
pairs(emm)

Comment: could you clarify how you would specify this if the elements had names of different lengths, like Magnesium, Manganese, ect.. instead of `Elmx` like in my example
Comment: Use the actual variable names. You can choose what you want for mult.name, but change it both places.


How to proof that the limit of this square root is $3$?

Question: $$\sqrt{2\sqrt{3\sqrt{4\sqrt{\cdots\sqrt{(n-1)\sqrt{n}}}}}}$$
I know how to deal with roots like that when there is addition (like this: How can I show that $\sqrt{1+\sqrt{2+\sqrt{3+\sqrt\ldots}}}$ exists?), but I have no idea what to do with multiplying.
Comment: for $n\to \infty$? what is the source of this problem?
Comment: This expression is $2^{1/2}3^{1/4}4^{1/8}\cdots n^{1/2^{n-1}}$.
Comment: yes, $\ n -> \infty $
Comment: @Emily You mean `n\to\infty`.
Comment: Please read [Somos' quadratic recurrence constant](https://en.wikipedia.org/wiki/Somos%27_quadratic_recurrence_constant).
Answer: The wanted quantity is not three. It is
$$ \exp\sum_{n\geq 1}\frac{\log(n+1)}{2^n} $$
and the inner series can be easily approximated via summation by parts and creative telescoping:
$$ \begin{eqnarray*}S&=&\lim_{N\to +\infty}\sum_{n=1}^N\frac{\log(n+1)}{2^n}\\&=&\lim_{N\to +\infty}\left[(1-2^{-N})\log(N+1)-\sum_{n=1}^{N-1}\left(1-2^{-n}\right)\log\left(1+\tfrac{1}{n+1}\right)\right]\\&=&\log(2)+\sum_{n\geq 1}\frac{1}{2^n}\log\left(1+\tfrac{1}{n+1}\right)=\log(2)+2\sum_{n\geq 2}\frac{\log\left(1+\tfrac{1}{n}\right)}{2^n}\end{eqnarray*} $$
approximately equals
$$\begin{eqnarray*}&& \log(2)+2\sum_{n\geq 2}\frac{1}{2^n}\left[\frac{1}{n+\tfrac{1}{2}}+\frac{1}{12\left(n-\tfrac{1}{2}\right)\left(n+\tfrac{1}{2}\right)\left(n+\tfrac{3}{2}\right)}\right]\\&=&\log(2)-\frac{143}{30}+\frac{49}{6\sqrt{2}}\log(1+\sqrt{2})\end{eqnarray*}$$
which is a number slightly larger than $1$. It follows that
$$ C=\sqrt{2\sqrt{3\sqrt{4\sqrt{5\sqrt{\ldots}}}}} $$
is slightly larger than $e$, but definitely less than $3$. By Frullani's theorem we also have the following integral representation for $C$:
$$ C = \exp \int_{0}^{+\infty}\frac{2(1-e^{-x})}{x(2e^x-1)}\,dx\leq \exp\int_{0}^{+\infty} 2 e^{-5x/2}\left(1+\tfrac{25}{24}x^2\right)\,dx = \exp\left(\tfrac{16}{15}\right).  $$
Answer: Actually products are easier because their logarithms are sums. In this case the result is $\exp\sum_{n\ge 2}2^{-n}\ln n$. The polylogarithm $\operatorname{Li}_s(z):=\sum_{n\ge 1}z^n n^{-s}$ satisfies $-\partial_s\operatorname{Li}_s(z):=\sum_{n\ge 2}z^n n^{-s}\ln n$, so your expression is $\exp-\partial_s\operatorname{Li}_s(z)|_{s=0,\,z=1/2}$.
Comment: Do you know how to do that without derivatives?


how rename series legend in chart created by views

Question: I created a chart page by using Views. But the legend is always Series 1, Series 2. Not using the label data.

I tried to find the option to replace the label "Series" with the label from the data, but I could not find it.
Anyone can help me how to use the label of the data instead of "Series"
Answer: Finally I can find the answer, after keep on trying:
I have to switch to custom label. Just change to custom label in the field.


How does Windows manage file versions across different Windows Updates?

Question: One thing i never understood nor find any easy explanation is how Windows manages changes to system files from differing Windows updates. Take for example
A certain KB release applies patches to A.dll and B.dll, which I may not apply.
A later KB release patches up A.dll only. Which I apply. A.dll should not be carrying the fix in the earlier KB.
When I do choose to apply the former KB fix, what version does A.dll really become? It would seem that Windows Update cannot merely replace files wholesale, but have to intelligently patch the files based on past KBs' hotfixes applied. Correct me if I'm wrong, thanks.
Comment: Not quite an answer, but you can enable verbose logging of windows update. IIRC, It shows dependencies resolution. Instructions at bottom of [this KB Article 902093](http://support.microsoft.com/kb/902093/en-us)
Answer: In the case you gave, it will either hold two patches to A.dll (one for those who have patched B.dll and one for those who have not) or, more commonly, it will carry the patch to B.dll as well.
Comment: Sometimes you will not be offered the 2nd update until the first is fulfilled as well. How many times have you installed every update on an old system, just to find 20 more waiting after a reboot?
Comment: But what content do the KB hotfixes hold within? I cannot think it is possibly a _full_ copy of A.dll, since the patches are mutually exclusive and that would mean overwriting a patch over another depending on the sequence order of update.
Comment: The hotfix confirms the versions before it updates and has logic to update from various previous versions. A hotfix installation will never unintentionally downgrade a file.
Comment: So it means a hotfix has a chain of _dependencies_ (past hotfixes) that must be satisfied before the current one can go in. You cannot apply hotfix C until you apply A and B. The matter may even be further complicated if you obtain a QFE patch that is not part of regular Windows update releases.


Cannot do calculations with values passed as props in React Native

Question: I'm developing a React Native app. There, I'm using react-native-simple-gauge and I want to fill the gauge by calculating the percentage value.
I'm passing the value (value) and the reference value (refValue) as props to the particular component. Then, I calculated the percentage as follows.
this.props.value / this.props.refValue * 100
But, this gives me an error saying that
Invariant Violation: Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWilUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
BTW, I'm not using any of setState, componentWillUpdate, componentDidUpdate in my component.
The relevant code segment is given below.
<AnimatedGaugeProgress
    size={50}
    width={3}
    fill={this.props.value / this.props.refValue * 100}
    rotation={90}
    cropDegree={90}
    tintColor={this.props.tintColor}
    backgroundColor="#808080"
 />

When I hard code and replace this.props.refValue, it works well.
<AnimatedGaugeProgress
   size={50}
   width={3}
   fill={this.props.value / 20 * 100}
   rotation={90}
   cropDegree={90}
   tintColor={this.props.tintColor}
   backgroundColor="#808080"
 />

Please help me to solve this problem. Thank you.
Comment: Are you perhaps frequently calling something that is updating `this.props.refValue` constantly (thus triggering many re-renders)? See https://stackoverflow.com/a/48497410/7548163, for example.
Answer: With the information you have provided, the only difference is the this.props.refValue.
If that prop is constantly changing, it will cause the AnimatedGaugeProgress component to re-render each time.
The easiest way to find the issue is to find out the place where you are changing the value of refValue. Check in the lifecycle methods, specially ones which can trigger a render.
Answer: The problem was solved by,

First, calculate what is needed and set the result to a state.
Then, pass the resulting state as props to component.


Creating a database and tables in MySQL using a JDBC application

Question: I've created a program in Java for a school project. I created the database and tables using MySQL Workbench, but now I need my program to work on other computers and therefore I need it to check if the database and tables exist, and if not create them on its own.
This is the relevant code in my driver class as it stands:
<code>private static Connection conn;

static
{
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch (ClassNotFoundException exc)
    {
        javax.swing.JOptionPane.showMessageDialog(null, "Oops! Something seems to have gone wrong!\n\n" + exc, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

public static Connection getMySQLConnection() throws SQLException
{
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tournament_manager", "studentCouncil", "****");
    return conn;
}
</code>
As above, the database I would like to create, if it does not exist, is to be called "tournament_manager". The tables to be created with the database are as follows:
Table 1 Name: password
Column 1: passwordID
Type: int(11)
Nullable: NO
Column 2: password
Type: varchar(20)
Nullable: YES
Character Set: latin1
Table 2 Name: tournaments
Column 1: tournamentID
Type: int(11)
Nullable: NO
Extra: auto_increment
Column 2: tournamentName
Type: varchar(20)
Nullable: NO
Character Set: latin1
Column 3: date
Type: date
Nullable: NO
Column 4: startTime
Type: int(11)
Nullable: NO
Column 5: matchDuration
Type: int(11)
Nullable: NO
Column 6: breakDuration
Type: int(11)
Nullable: NO
Column 7: numTeams
Type: int(11)
Nullable: NO
Column 8: numVenues
Type: int(11)
Nullable: NO
Table 3 Name: teams
Column 1: teamID
Type: int(11)
Nullable: NO
Extra: auto_increment
Column 2: teamName
Type: varchar(20)
Nullable: NO
Character Set: latin1
Column 3: points
Type: int(11)
Nullable: NO
Column 4: tournaments_tournamentID
Type: int(11)
Nullable: NO
I am new to stack overflow, so I may have not included all the relevant information or included irrelevant information. In the case that I haven't included relevant details, please ask.
Thank you in advance for the support!
Comment: But what's the problem?
Comment: You can get a `DatabaseMetaData` object from your `Connection` object via `getMetaData()`. Once you have that object, you can query it for existing tables and create them using standard SQL, if they are not there using your `Connection` object.
Comment: You can do it, but I'd consider it a bad design to be creating tables in Java.  Usually applications create a schema before the app runs and then perform CRUD operations with Java.  You're making that classic student/beginner mistake: Mingling database and UI code in one class.  There's no separation of concerns there.
Answer: To create tables, you should use the "CREATE TABLE" SQL syntax. This can be done on the database management program but also in JDBC.
<code>  stmt = conn.createStatement();

  String sql = "CREATE TABLE password" +
               "(passwordId INTEGER not NULL, " +
               " password VARCHAR(20), " +
               " PRIMARY KEY ( passwordId ))";

  stmt.executeUpdate(sql);
</code>
Answer: Actually you can do it with Hibernate JPA.
Create a Model
<code>@Entity
@Table(name = "USER")
public class User{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id
  @Column(name="FIRST_NAME")
  private String firstName
  @Column(name="LAST_NAME")
  private String lastName
}
</code>
Define hibernate auto creation
in applicationContext.xml (spring-servlet.xml or hibernate.cfg.xml) add that:
<code>         <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/DB"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value=""/>
            // That property create tables and key options.
            <property name="hbm2ddl.auto" value="create"/>
        </properties>
</code>
Start Server
When you start server hibernate will create your tables or update your columns.
Comment: Just because you can do it with hibernate, doesn't mean you need to use an additional library to accomplish it and where in the question does it mention spring servlet?
Comment: He wants to create tables in Java. Hibernate auto is a tool for it. Spring-servlet is a etc. case. Which xml he has he can use it.
Comment: I'm saying the code the question provided uses DriverManager and here you are promoting an alternative method. While it may attempt to answer, it does not directly solve the problem addressed in the question. If you could explain what hibernate is and why it should be used with a runnable example, maybe your answer will be accepted.


Linear independence of a set of vectors in $\mathbb{R}^n$

Question: There is a theorem that states: $$Let \space S=\{v_1,v_2,...v_r\}\space be \space a \space set \space of\space vectors \space in\space \mathbb{R}^n. \space If\space r>n,\space then\space S\space is\space linearly\space dependent.$$ My question is, does the 'other' case apply as well? By other case, I mean if $r<n$, does this mean the set $S$ is linearly independent or linearly dependent? No proofs please, just some intuition behind the answer if possible!
Thanks in advance!
Comment: Think about 2 parallel vectors in R^3. Now think about 2 perpendicular vectors in R^3.
Comment: @toliveira: That is basically an answer.
Comment: @CameronBuie, I promoted it to an answer. ;-)
Answer: If $r\leqslant n$ then anything could happen.
For instance, if one of the vectors is $0$, or if two of the vectors are the same, then the set is linearly dependent no matter how small $r$ is.
Comment: @coreyman317 You're welcome.
Comment: @coreyman317 Definitely not. You need exactly as many vectors as the dimension to form a basis.
Answer: Not without more information. We can choose $r<n$ linearly independent vectors. But we can also choose them to be linearly dependent: we can choose them all from a subspace of dimension less than $r$, in which case they must be dependent.
Answer: There's nothing to be said (without further information) about a set with less elements than the dimension of the space, except when the size of the set is exactly one (in which case it's trivially linearly independent iff it's not the zero subspace). Consider, for example, $v \in \mathbb{R}^k \setminus\{0\}$ with $k \geq 3$ and the set
$$
\{v,2v,3v,...,(k-1)v\}
$$
which is clearly linearly dependent, but has less than $k$ elements. The intuition here is that you could easily choose vectors that belong to the subspace generated by the previously chosen, and if you choose more vectors than the dimension of the space, this property is guaranteed.
Answer: Just from $r<n$, you cannot say whether the set S is linearly independent or linearly dependent. E.g., in $R^3$, two parallel vectors are linearly dependent, while two non-parallel vectors are linearly independent.


How do I apply a custom set of blocks to a custom content type

Question: I have a custom content type I call a Listing. It contains a few hundred fields, and it has a custom template, which renders the node indie the main content area.
How do I configure the sidebar and other blocks to appear/not appear for only this content type and not all content?
Answer: This depends on the information you would like to show in the sidebar. If you want to show some static information like for example a help text, then you can create a block in admin / structure / blocks. After you added a new block, you can modify the visibility settings of this Block (and many other settings). For example set the block to to show only on a specific path, content type or whatever.
The other way or case you might have, is to show dynamic data which has a relation to the content you're currently looking at. These dynamic blocks can be built for example with Views or you can create them programmatically in an own module.
The placement of the blocks works like on the first case. But there are other ways to place a block (e.g with Context).
Comment: Thanks, that helps. I'll check into the visibility settings. Where are they located?
Comment: Just go to create a block and look at the options on the bottom of the page.
Comment: I was looking into hook_block_view_MODULE_DELTA_alter to do it programatically...and then I realized that I could just configure my content as blocks, and define each block, rather than using the template to map node fields to locations on the page. Ultimately giving my users more configuration options for the custom content.


Nonlinear Second Order Differential Equation

Question: I have been trying to solve the following ODE and cannot get anywhere with it:
$\frac {d^{2}y}{dx^{2}} = 1-( \frac {dy}{dx})^{2}$.
The techniques I have used which are really the techniques for simple 2nd order ODEs don't work at all. Using the "D" operator doesn't work.
I am aware that I could write the RHS as
$(1-dy/dx)(1+dy/dx)$
but it seems that doesn't get me very far.
I am also aware I could try to solve this using infinite series, i.e
$y = a_{0}+a_{1}x+... $
and do tedious calculations to get somewhat of an answer, but I am hoping for a closed form answer.
Any help would be appreciated.
(BTW this is not, strictly speaking, homework, just a puzzle I've been thinking about).
Answer: Let $dy/dx=u$. Then the equation becomes
$$
u'=1-u^2,
$$
which is a first order ODE that can be solved by separation of variables.
Comment: Wow. So simple. I feel stupid.


Add events to my google calendar from my website

Question: I have created a php page with fullcalendar jquery plugin which allow website users to book time. On background I'm storing event into my DB and then using Google calendar API creating same event to my google calendar.
But my implementation is asking user to login into their google account and creating event on user's calendar. How can I achieve to create user event in my(website owner's) google calendar "seamlessly"?
my code is as below:
<?php
session_start();

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Google Calendar');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR)
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);

/*if (file_exists($credentialsPath)) {
  $accessToken = file_get_contents($credentialsPath);
} else {*/

    if(!$_REQUEST['code']) {
        $authUrl = $client->createAuthUrl();
        //printf("Open the following link in your browser:\n%s\n", $authUrl);
        header("Location:".$authUrl);
    }
    $authCode = $_REQUEST['code'];
    $accessToken = $client->authenticate($authCode);

    // Store the credentials to disk.
    /*if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, $accessToken);*/
    //printf("Credentials saved to %s\n", $credentialsPath);
//}
$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(array(
  'summary' => $_SESSION['cal-data']['fname']." ".$_SESSION['cal-data']['lname'],
  'location' => $_SESSION['cal-data']['address'],
  'description' => "Contact: ".$_SESSION['cal-data']['phoneno']." for ".$_SESSION['cal-data']['title'],
  'start' => array(
    'dateTime' => $_SESSION['cal-data']['starttm'],
    //'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => $_SESSION['cal-data']['endtm'],
    //'timeZone' => 'America/Los_Angeles',
  ),
  /*'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),*/
  'attendees' => array(
    array('email' => $_SESSION['cal-data']['email'])
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'firstname.lastname@example.com';
$event = $service->events->insert($calendarId, $event);
//printf('Event created: %s\n', $event->htmlLink);
unset($_SESSION['cal-data']);

header("Location: next-page.php");

Comment: There should be a setting to make it public, no? I've never worked with those, but assume there would be.
Comment: Yes there is setting to make your calendar public and my calendar is already public.
Answer: There's a way to store credentials in a shared/public calendar, using the calendar id as in the "normal" API call.
POST https://www.googleapis.com/calendar/v3/calendars/YOUR_SHARED_CALENDAR_ID/events

BUT, you have to share a calendar with those people or with the public. https://support.google.com/calendar/answer/37082?hl=en
Otherwise you can't
Comment: can you help me in my code where should I make api call as you suggested?
Answer: You can use a Service account to serve as a proxy user accessing your Calendar (no more prompting users to login their account). Based on Inserting Google Calendar Entries with Service Account, You can add an event to a shared calendar.
Here is the steps:

Create a Service Account
You need to create a public/private key pair.

In the Create service account window, type a name for the service account and select Furnish a new private key. If you want to grant Google Apps domain-wide authority to the service account, also select Enable Google Apps Domain-wide Delegation.

Note: Enable the API and share the Calendar to your email address from the service account credentials. And don't forget to enable "Changes to events".


UIGestureRecognizer rotate UIVIew with CGAffineTransformRotate and with angle between zeroPoint(0, "some number") and gesture pan point

Question: I have a simple task: rotate UIView on user touch. Top of my view must always pointed on finger touch.
I tried to do it with next code:
func handlePan(recognizer: UIPanGestureRecognizer) {
        let currentPoint = recognizer.locationInView(self.superview)
        let dx = currentPoint.x - self.center.x
        let dy = currentPoint.y - self.center.y - self.radius
        let angle = atan2(dy, dx)
        var deg = angle * CGFloat(2.0 / M_PI)
        if deg < 0 {
            deg += 360.0
        }
        let transform = CGAffineTransformRotate(self.rotateView.transform, angle)
        self.rotateView.transform = transform
        println("x: \(currentPoint.x), y: \(currentPoint.y), angle: \(angle), deg: \(deg)")
    }

But I have a wrong angle as you can see below

x: 235.0, y: 426.5, angle: 0.616667, deg: 0.392582
x: 221.0, y: 431.5, angle: 0.761626, deg: 0.484866
x: 212.0, y: 433.5, angle: 0.858078, deg: 0.54627
x: 203.0, y: 436.5, angle: 0.973115, deg: 0.619504
x: 196.0, y: 437.5, angle: 1.05952, deg: 0.67451
x: 187.0, y: 439.5, angle: 1.18336, deg: 0.753351
x: 179.0, y: 439.5, angle: 1.29117, deg: 0.821982
x: 168.0, y: 439.5, angle: 1.45047, deg: 0.9234
x: 143.0, y: 439.5, angle: 1.82228, deg: 1.1601
x: 122.0, y: 437.5, angle: 2.10547, deg: 1.34038
x: 108.0, y: 435.5, angle: 2.26738, deg: 1.44346
x: 96.0, y: 429.5, angle: 2.42129, deg: 1.54144
x: 80.0, y: 423.5, angle: 2.5815, deg: 1.64343
x: 73.0, y: 418.5, angle: 2.66274, deg: 1.69515
x: 68.0, y: 415.5, angle: 2.71183, deg: 1.7264
x: 60.0, y: 409.5, angle: 2.79456, deg: 1.77907
x: 56.0, y: 406.5, angle: 2.83288, deg: 1.80347
x: 47.0, y: 397.5, angle: 2.9309, deg: 1.86587
x: 40.0, y: 384.0, angle: 3.05294, deg: 1.94356
x: 26.0, y: 359.0, angle: -3.03503, deg: 358.068
x: 18.0, y: 342.0, angle: -2.92442, deg: 358.138
x: 12.0, y: 326.0, angle: -2.83205, deg: 358.197
x: 8.0, y: 312.0, angle: -2.75807, deg: 358.244
x: 6.0, y: 303.0, angle: -2.71317, deg: 358.273
x: 5.0, y: 296.0, angle: -2.67881, deg: 358.295
x: 3.0, y: 286.0, angle: -2.63395, deg: 358.323
x: 2.0, y: 281.0, angle: -2.61273, deg: 358.337
x: 2.0, y: 277.0, angle: -2.59407, deg: 358.349
x: 2.0, y: 272.0, angle: -2.57132, deg: 358.363
x: 2.0, y: 269.0, angle: -2.55798, deg: 358.372
x: 3.0, y: 266.0, angle: -2.54192, deg: 358.382
x: 4.0, y: 264.0, angle: -2.53029, deg: 358.389
x: 6.0, y: 262.0, angle: -2.51563, deg: 358.398
x: 8.0, y: 260.0, angle: -2.5009, deg: 358.408
x: 11.0, y: 254.0, angle: -2.46631, deg: 358.43
x: 13.0, y: 250.0, angle: -2.44352, deg: 358.444
x: 16.0, y: 244.0, angle: -2.4098, deg: 358.466
x: 19.0, y: 238.0, angle: -2.3767, deg: 358.487
x: 24.0, y: 228.0, angle: -2.32303, deg: 358.521
x: 25.0, y: 222.0, angle: -2.29921, deg: 358.536
x: 28.0, y: 214.0, angle: -2.26265, deg: 358.56
x: 28.0, y: 206.0, angle: -2.2387, deg: 358.575
x: 29.0, y: 199.0, angle: -2.21521, deg: 358.59
x: 30.0, y: 191.0, angle: -2.19018, deg: 358.606
x: 31.0, y: 182.0, angle: -2.16401, deg: 358.622
x: 32.0, y: 174.0, angle: -2.14163, deg: 358.637
x: 34.0, y: 168.0, angle: -2.12118, deg: 358.65
x: 35.0, y: 161.0, angle: -2.10286, deg: 358.661
x: 36.0, y: 155.0, angle: -2.08731, deg: 358.671
x: 36.0, y: 152.0, angle: -2.08147, deg: 358.675
x: 37.0, y: 149.0, angle: -2.07233, deg: 358.681
x: 39.0, y: 146.0, angle: -2.05992, deg: 358.689
x: 39.0, y: 146.0, angle: -2.05992, deg: 358.689

And I don't know why my angle is always ~385.
Anyone have any idea what I do wrong?
Comment: Keep it concise. Show less lines of output code but make sure it is relevant.
Answer: Glancing at your code, it looks like you're converting from radians to degrees incorrectly.  360 degrees = 2π radians, so...
var deg = angle * CGFloat(180.0 / M_PI)

should fix things.
Hope this helps.


The test procedure of significant differences in count data over time

Question: The data below are from a health testing centre over 8 years so there are different people being tested there each year. All I really want to show is that the amount of females being tested is different over the different years. The data look like this:
YEAR   FEMALE   MALE   TOTAL
2002     50       7      57
2003    126      50     176
2004    339      68     407
2005    401     158     559
2006    639     328     967
2007    744     600    1344
2008    570     526    1096
2009    452     448     900
2010    561     372     933

I think these data are not actually repeated measures, because each year different individuals are being tested. Moreover, the data are counts in nature. So, I was just thinking of using Runs test to show if the amount of females being tested is different over the different years. Because Runs test is a test of randomness. The alternative hypothesis should be indicating some trend in the data.
Am I right that the data are not repeated measures? Moreover, is the concept of Runs test appropriate here?
What would the test be if I wanted to test "if the proportion of females being tested is different over the different years"? I think this is a more sensible test to do, but how can I do it?
I have several comparisons like this, so it would be good to know if I'm using the wrong test! Any suggestion regarding the test procedure will be greatly appreciated.
Comment: @PeterFlom, Sir may I ask for your suggestion? I guess if Runs test is appropriate, I can perform this for proportions too. But I am just getting a little bit confused!
Answer: You could just fit a flexible regression model and examine that instead.  Since you don't know what the trend might be, but you think that the visits are independent people so the counts are binomially distributed, then you could do the following in R.
First we make the data and load a useful library
## make the data
dat <- data.frame(f=c(50, 126, 339, 401, 639, 744, 570, 452, 561),
                  m=c(7, 50, 68, 158, 328, 600, 526, 448, 372),
                  year=c(2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010))

## load the splines library
require(splines)

Then fit a flexible generalised linear model
## fit a model of the counts as a smooth (beta spline) function of year
mod <- glm(cbind(f, m) ~ bs(year), data=dat, family=binomial)

## get the model predictions with standard errors
mod.pred <- predict(mod, type='response', se=TRUE)

Now plot the original data
## plot the data as proportions of females
with(dat, plot(f/(f+m) ~ year))

and put the model's predictions on top.
## plot them on top with rather approximate confidence intervals
with(mod.pred, lines(fit ~ dat$year))
with(mod.pred, lines(fit + se.fit*2 ~ dat$year))
with(mod.pred, lines(fit - se.fit*2 ~ dat$year))

That looks like evidence of a trend to me, albeit not a uniformly linear one.
If you were to assume the trend was linear (in the log ratios of females to males), then you might fit a simpler model, like
## just take out the spline
mod.lin <- glm(cbind(f, m) ~ year, data=dat, family=binomial)
summary(mod.lin)

This doesn't fit so well, but nevertheless still suggests that each year there are expected to have been exp(-0.16205) = 0.85 i.e. only 85% of the number of women each year compared to the year before - an effect that is, for what it's worth, significant.
Comment: If we assume that the counts of women and the counts of men in a year are Poisson distributed with different means (a reasonable assumption here) then at the end of the year we have a total number of people that arrived.  *Conditional* on this total, the two counts must therefore, as a matter of mathematics, be Binomially distributed.  That's just what happens when you condition two Poisson variables on their total.
Comment: You'll notice that in the link you provided there is a test of whether a set of proportions could actually all be the same, but the opposite of 'all the same' is not specified.  In the answer above I am working with your specified alternative: that there is a time trend.  Consequently I showed how to fit models that could find and represent such a trend if there was one to be found and could fail to see it if there was not.  But that's really just a difference in perspective on your problem.
Comment: Thank you so much. Your answer is very complete. But could you please explain a little more for me on why the counts are taken to be binomially distributed? Why we do not consider them as Poisson random variables?

For testing the proportion of females would you please see if I can use the following link for my case?
http://www.itl.nist.gov/div898/handbook/prc/section4/prc474.htm


Prove: For open sets $(U_i)_{i\in I}$ with $\mu(U_i)=0 \implies \mu(\bigcup_{i\in I}U_i)=0$

Question:
Let $(\Omega,O)$ be a topological space with countable basis $\mathcal F$. Furthermore, let $\mu$ be a Borel-measure (resp. a measure on the measure space $(\Omega,\mathcal B(\Omega))$.

  Prove that if for a family of open sets $(U_i)_{i\in I}$ with $\mu(U_i)=0 \ \ \forall i\in I$ it follows that $\mu(\bigcup_{i\in I}U_i)=0$

The problem here is that $I$ may be an uncountable index set, so I cannot use the $\sigma-$sub-additivity. We have:
$$U_i = \bigcup_{\substack{F\in\mathcal F \\ F\subset U_i}}F$$ Hence $$\bigcup_{i\in I}U_i=\bigcup_{i\in I}\bigcup_{\substack{i\in F\in\mathcal F \\ F\subset U_i}}F=\bigcup_{\substack{F\in\mathcal F \\ F\subset\bigcup_{i\in I} U_i}}F$$ since $(U_i)_{i\in I}\subset O \implies \bigcup_{i\in I}U_i\subset O$. Can I now conclude that $$\mu(\bigcup_{i\in I}U_i)=\mu(\bigcup_{\substack{F\in\mathcal F \\ F\subset\bigcup_{i\in I} U_i}}F)=\sum_{\substack{F\in\mathcal F \\ F\subset\bigcup_{i\in I} U_i}}\mu(F)=0
\ \ ?$$ Thanks in advance!
Answer: In a space with a countable basis any union $\cup_{i\in I} U_i$ can be written as $\cup_{i\in } U_{i_n}$ for some $i_1,i_2,...$. Proof: if $x \in \cup_{i\in I} U_i$ then there exists $i$ such that $x \in U_i$. There is a member of the basis  $V$ such that $x \in V \subset U_i$. The collection of all $V$'s that arise this way is countable and each of then is contained in some $U_i$. This way we get a countable number of $U_i$'s whose union includes every $x \in \cup_{i\in I} U_i$.
Comment: Another way to phrase your answer and to go in the direction of the OP is that $\displaystyle\bigcup_{i\in I}U_i = \displaystyle\bigcup_{F\in\mathcal{F}, \exists i\in I, F\subset U_i}F$ and then use $\sigma$-sub-additivity