Como criar método de envio de mensagem em Tabs?

Question: Estou criando um app, em android, que possui tabs. Cada tab é uma sala de chat. Peguei um exemplo de um vídeo sobre como criar app com Tabs, onde o autor, além de criar o app usando um modelo de tabs, ele criar uma classe tab para cada uma das tabs e um xml para cada um delas também. Conclui que para enviar uma mensagem, em uma determinada tab, eu teria que criar o método de envio de mensagem na classe tab, de cada uma delas, porém, não estou conseguindo fazer a devida "ligação" do campo de texto (TextView) nessa classe, pois o comando findoViewById() não aparece na classe tab!
package com.example.gustavo.vigilantescomunitarios;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabRua extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab_rua, container, false);

    }

}

Comment: Tentou usar a classe [Context](https://pt.stackoverflow.com/questions/38853/o-que-%C3%A9-um-context-no-android)?
Comment: Desculpe, mas como assim?
Comment: Dá uma olhada nesse [tópico](https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment) e veja se te ajuda.
Comment: Não entendi, muito bem o que tem que ser feito kkkkk desculpa
Answer: Você não cosnegue usar o findviewById porque você não está usando a root inflada do layout, quando você extende a um fragment as coisas são um pouco diferentes de quando você extende a uma Activity, você tem que acessar os outros layouts através do layout inflado:
public class TabRua extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_rua, container, false);
    Textview textView = rootView.findviewById(R.id.textView); //Apenas um exemplo
    return rootView;
}

Comment: Agora estou tentando criar o método para enviar a mensagem e colocando uma Toast, mas o método tem como parâmetro (View view). Preciso pegar a mensagem digitada na textview
Comment: Hunmm você pode fazer de várias formas essa transação, da uma lida na arquitetura MVP talvez lhe ajude
Comment: Onde encontro essa arquitetura MVP? Na documentação do android?
Comment: Onde vejo isso @Matheus?
Answer: Você pode utilizar a classe Bundle e passar uma instancia dessa classe para o seu Fragmentno ato da sua Intent.
Exemplo:
Bundle bundle = new Bundle();
bundle.putString("foo", "bar"); // chave e valor, respectivamente
fragment.setArguments(bundle);

E para pegar os dados no seu Fragment
Bundle bundle = this.getArguments();

if (bundle != null) {
    String foo = bundle.getInt("foo", "VALOR_PADRAO");
}

EDIT 1: Quanto ao findViewById(), recomendo você dar uma olhada na biblioteca ButterKnife para lidar com view binding.
Comment: Cara sobre o Bundle eu sei, a questão é outra.
Comment: A sua pergunta é pouco explicativa. Você quer trocar mensagem de um `TextView` de uma tab para um `TextView` de outra tab?
Comment: Não, vc quem não entendeu... Cada Tab é um canal de chat e cada TextView manda mensagem para seu respectivo canal! É um chat normal!
Comment: Você quer fazer a ligação do seu `TextView `? Tente isso: `TextView textView = (TextView) getView().findViewById(R.id.text_view);`


Login to external server from Drupal site

Question: Is there any way to customize Drupal login to use authentication from an external server?
I'd like to know about any modules or if Drupal core can implement this function.
Source code:

// Include FirePHP for debug

function authdave_form_alter(&$form, &$form_state, $form_id) {
    // Authentication based on username and password
    if ( ($form_id == 'user_login' || $form_id == 'user_login_block') ) {
        $form['#validate'][] = 'authdave_user_form_validate';
    }
}
/**
* Custom form validation function
*/
function authdave_user_form_validate($form, &$form_state) {
    if( !authdave_authenticate($form_state) ) {
        form_set_error('name', t('Unrecognize username.'));
    }
}
/**
* Custom user authentication function
*/
function authdave_authenticate($form_state) {
    // get first four characters from user name
    $complete_username = $form_state['input']['name'];
    $password = $form_state['input']['pass'];

    // retrieve users credentials from DB
    $credential = get_all_credentials();

    while($row = $credential->fetch_assoc()) {
        // check if there are any match
        if ( $row["username"] ==  $complete_username && $row["password"] == $password) {
            user_external_login_register($complete_username, 'custom_athentication');
            return TRUE;
        }
    }

    return FALSE;

}

function get_all_credentials() {

    //credenziali di accesso al dbms
    $server = "****";
    $username = "***";
    $password = "***";

    //nome db
    $db_name = "credenziali_db";

    //creo una connessione con il dbms
    $conn = new mysqli($server, $username, $password, $db_name);

    if ($conn -> connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    echo "Connection successfully";

    //sql query
    $sql = "SELECT username, password FROM credenziali";
    $result = $conn -> query($sql); //risultato della query

    return $result;

}

?>
Answer: This depends what you mean by external server? There's a tonne of contribution modules at the moment that support a variety of external logins.
You can implement Open Auth 2 to allow a single sign on:
https://www.drupal.org/project/oauth2_authentication

Or you can use Facebooks Oauth authentication:
https://www.drupal.org/project/fboauth

Comment: I would allow users using credentials of private company server in wich they are signed up instead of drupal authentication.
Comment: In that case you need to write your own solution hooking into the Drupal login system. Check the Drupal API documentation on its login and authentication hooks. You should make a note to be very careful here as mistakes could open your site to abuse.
Comment: I've written my custom module to customize user authentication. I've used external server database to verify user access credentials and everything works fine. I've only one problem: after user authentication drupal site show me an error message "Sorry, unrecognized username or password. Have you forgotten your password?", but the user is logged in. What should be the mistake?
Comment: Can you provide any source code of this? be best in your question
Comment: You can see source code in the question above
Comment: I also tried to customize the code showed here https://api.drupal.org/comment/13434#comment-13434 but I don't understand what  I've to insert. Also  in my case should return only a boolean (true or false if user is authenticated).


Proving that $\prod_{n=0}^\infty (1 + x^{2^{n}}) = \frac{1}{1-x}$

Question: I would like to verify the truth of my proof that $$\large\prod_{n=0}^\infty (1 + x^{2^{n}}) = \frac{1}{1-x}.$$
Proof. The proof is rather straightforward, just using some observations that two consecutive factors form a sum of a geometric sequence.
\begin{align*}\prod (1 + x^{2^{n}}) &= \prod (1 + x^{2^{2n}})(1+x^{2^{2n+1}}) \\
&= \prod (x^{3\cdot 2^{2n}} + x^{2\cdot 2^{2n}} + x^{1\cdot 2^{2n}} + x^{0\cdot 2^{2n}}) \\
&= \prod \frac{x^{4 \cdot 2^{2n}} - 1}{x^{2^{2n}} - 1}.
\end{align*} Next, we note that $$\large\prod_{n=0}^\infty \frac{x^{4 \cdot 2^{2n}} - 1}{x^{2^{2n}} - 1} = \frac{\prod_{n=0}^\infty x^{4 \cdot 2^{2n}} - 1}{\prod_{n=0}^\infty  x^{2^{2n}} - 1} \qquad (*)$$
Step (*) worries me a little, even though I feel like it is valid. (Would I need to prove that if the limit of the LHS exists, then it's equal to the RHS?)
Then $$\Large \frac{\prod_{n=0}^\infty x^{4 \cdot 2^{2n}} - 1}{\prod_{n=0}^\infty  x^{2^{2n}} - 1} = \frac{\prod_{n=0}^\infty x^{4 \cdot 2^{2n}} - 1}{(1-x)\prod_{n=0}^\infty  x^{2^{2n+2}} - 1} = \frac{1}{1-x},$$ and we are supposedly done.
EDIT: For $|x| < 1$
Comment: I don't think that displaying formulas $\large large$ or even $\Large Large$ improves the presentation. Just my 2 ct.
Comment: Hint: $4\cdot 2^{2n} = 2^{2(n+1)}$, you are dealing with a "telescoping" product.
Comment: By definition, $\prod\limits_{n=1}^\infty (\cdots) = \lim\limits_{m\to\infty}\prod\limits_{n=1}^m (\cdots)$. Since the product is telescoping, you know how to evaluate the partial product for any given $m$....
Comment: @achillehui I know, that's what I am trying to do on the last line.
Comment: See bullet 5: https://en.wikipedia.org/wiki/Limit_of_a_sequence#Properties
Answer: Hint:
You can make the step $$\prod_n\frac{a_n}{b_n}=\frac{\prod_n a_n}{\prod_n b_n}$$
if and only if the sums
$$A=\sum_n\log a_n,\qquad B=\sum_n\log b_n$$
converge absolutely. Set $a_n=x^{4\cdot2^{2n}}-1$, $b_n=x^{2^{2n}}-1$, and see for which values of $x$ we have absolute convergence of $A, B$.

Edit:
As was pointed out in the comments, we have the definition of an infinite product $\prod_na_n$:
$$\prod_n a_n=\exp\left(\sum_n \log a_n\right),$$
which is equivalent to $$\log\left(\prod_na_n\right)=\sum_n\log a_n.$$
So the product is said to converge iff the sum $\sum_n\log a_n$ converges.
If the sums $A$ and $B$ converge absolutely, then we are justified in saying that
$$A-B=\sum_n\log a_n-\sum_n\log b_n=\sum_n(\log a_n-\log b_n)=\sum_n\log\frac{a_n}{b_n}.\tag 1$$
Since $A=\log \prod_n a_n$ and $B=\log\prod_n b_n$ by definition, we see that
$$A-B=\log \left(\prod_na_n\right)-\log \left(\prod_n b_n\right)=\log\left(\frac{\prod_na_n}{\prod_nb_n}\right).$$
On the other hand, by definition,
$$\sum_n\log\frac{a_n}{b_n}=\log\left(\prod_n\frac{a_n}{b_n}\right).$$
Thus from $(1)$, assuming the products are real-valued,
$$\log\left(\frac{\prod_na_n}{\prod_nb_n}\right)=\log\left(\prod_n\frac{a_n}{b_n}\right)$$
$$\Rightarrow \frac{\prod_na_n}{\prod_nb_n}=\prod_n\frac{a_n}{b_n}.$$
Comment: I did not know about this. Do you know what this theorem is called?
Comment: @politeproofs its essentially the definition of infinite product, $\prod a_i=\sum\log a_i$ - thats why some people say the product "diverges to 0" if it does tends to 0, as the sum goes to -infz
Comment: @GarethMa You are missing an $\exp$ in "the definition of infinite product".
Comment: @Gary my bad phone doesn't even render latex in comments
Comment: @politeproofs please see the edit for a proof


Removing list members in scheme with remove*

Question: So I want to remove #\space from a list, lets say the list is (#\a #\b #\space #\b #\space) and I want to (remove* (list space) (list #\a #\b)) all spaces.
So when I run,
(remove* (list #\space) (list #\a #\b #\space #\b #\space))

the print out is correct. i.e. '(#\a #\b #\b)
this is also true if I were to write:
(define somelist #\space)

(remove* (list somelist) (list #\a #\b #\space #\b #\space))

however if I create a list via:
(define somelist (string->list " "))

it fails.
I don't know what the difference is and why it doesn't work. Anyway in my program I need to get rid of the spaces that become part of the list via string->list. Any idea how to do this?
I'm using Racket.
Comment: `(somelist (string->list " "))` does not make sense. Did you mean: `(define somelist (string->list " "))` ?
Comment: That is what I meant and I edited accordingly thanks.
Answer: You are wrapping the char list in another list.
What you want is:
(remove* somelist (list #\a #\b #\space #\b #\space))

Comment: Thank you so much and for the very fast response! I am new to scheme. I'd upvote you if I had enough reputation points lol.


Preencher valor no combobox quando clicar em checkbox

Question: Estou fazendo um cadastro de clientes e nele tem um checkbox que preenche um input com "ISENTO, deixa ele como "READONLY" e precisava preencher uma combobox com um valor que está no options.
Porém já tentei de tudo e não estou conseguindo fazer isso, poderiam me dar uma luz?
Segue o código que fiz.

function IEcli() {
  var cbocontribuinte = document.getElementById('tp_contribuinte');
  if ($('#iecli').prop("checked")) {
    $('#estadual').val("ISENTO");
    $('#estadual').attr("readOnly", true);
    cbocontribuinte.selectedIndex = 2;

  } else {
    $('#estadual').val("");
    $('#estadual').removeAttr("readOnly");
    cbocontribuinte.selectedIndex = 0;
  }
}
I. Estadual

  <input type="text" class="form-control" name="estadual" id="estadual" placeholder="" value="" />

  <input type="checkbox" name="iecli" id="iecli" onclick="IEcli()"> Isento?

  Insc.Municipal

    <input type="text" class="form-control" name="nome" placeholder="" value="" />

   Contribuinte

    <select class="form-control selectpicker" name="tp_contribuinte" id="tp_contribuinte" onchange="atualizaIEDest();">
      <option value="0">Selecione</option>
      <option value="1">1 - Contribuinte ICMS</option>
      <option value="2">2 - Contribuinte isento de inscrição no cadastro de contribuintes</option>
      <option value="9">9 - Não contribuinte, que pode ou não possuir inscrição no cadastro de contribuintes</option>
    </select>

Comment: Podes juntar código para reproduzirmos o exemplo? Assim podemos responder com código a funcionar.
Comment: Boa Tarde Sergio. Claro. Estou colocando o código
Comment: Sergio, só consegui colocar o trecho, pois o código é muito grande e não permite salvar a pergunta.
Comment: Acredito que o que falta é incluir o jquery na sua pagina
Comment: Boa Noite Pessoal.
Gostaria de agradecer a todos, todas as ajudas funcionaram perfeitamente, eu estava utilizando na página o bootstrap-select.min.js e ele estava influenciando no código, por isso não estava funcionando.
Uma pergunta: É possível marcar todas como resposta válida?
Answer: .val() é JQuery. JavaScript puro .value.
Em JQuery:
function IEcli () {

    var cbocontribuinte = $( '#tp_contribuinte' );

    if ( $( '#iecli' ).prop( 'checked', true ) ) {
        $( '#estadual' ).val( 'ISENTO' );
        $( '#estadual' ).prop( 'readonly', true );
        cbocontribuinte.prop(n'selectedIndex', 2 );

    } else {
        $( '#estadual' ).val( '' );
        $( '#estadual' ).prop( 'readonly', false );
        cbocontribuinte.prop( 'selectedIndex', 0 );
    }

}

JavaScript puro:
function IEcli () {

    var cbocontribuinte = document.getElementById( 'tp_contribuinte' ),
        iecli = document.getElementById( 'iecli' ),
        estadual = document.getElementById( 'estadual' );

    if ( ieclie.checked === true ) {

        estadual.value = 'ISENTO';
        estadual.readOnly = true;
        cbocontribuinte.selectedIndex = '2';

    } else {

        estadual.value = '';
        estadual.readOnly = false;
        cbocontribuinte.selectedIndex = '0';

    }

}

Answer: Podes fazer isso só com JavaScript e usando a propriedade do objeto diretamente.

function IEcli() {
  var cbocontribuinte = document.getElementById('tp_contribuinte');
  var iecli = document.getElementById('iecli').checked;
  var estadual = document.getElementById('estadual');

  estadual.value = iecli ? "ISENTO" : "";
  estadual.readOnly = iecli;
  cbocontribuinte.selectedIndex = iecli ? 2 : 0;
}
I. Estadual

  <input type="text" class="form-control" name="estadual" id="estadual" placeholder="" value="<?php echo $cliente->getInscestRg() ?>" />

  <input type="checkbox" name="iecli" id="iecli" onclick="IEcli()"> Isento?

  Insc.Municipal

    <input type="text" class="form-control" name="nome" placeholder="" value="<?php echo $cliente->getInscMunicipal() ?>" />

   Contribuinte

    <select class="form-control selectpicker" name="tp_contribuinte" id="tp_contribuinte" onchange="atualizaIEDest();">
      <option value="0">Selecione</option>
      <option value="1">1 - Contribuinte ICMS</option>
      <option value="2">2 - Contribuinte isento de inscrição no cadastro de contribuintes</option>
      <option value="9">9 - Não contribuinte, que pode ou não possuir inscrição no cadastro de contribuintes</option>
    </select>

Answer: Desta forma, o seu exemplo está funcionando perfeitamente.
Particularmente eu evito usar .attr() nesses casos.
OBS.: .val() além de inserir valores, também pode ser usado para selecionar opções.
function IEcli() {
    if ($('#iecli').prop("checked")) {
        $('#estadual').val("ISENTO");
        $('#estadual').prop("readonly", true);
        $('#tp_contribuinte').val("2");
    } else {
        $('#estadual').val("");
        $('#estadual').prop("readonly", false);
        $('#tp_contribuinte').val("0");
    }
}

Comment: **Particularmente eu evito usar .attr().** Por que?
Comment: http://api.jquery.com/prop/
Comment: The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Comment: Por vezes tive problemas com alterações especificamente em formulários, values, readonly e checked, o melhor é usar .val() e .prop()
Comment: Boa Noite Pessoal.
Gostaria de agradecer a todos, todas as ajudas funcionaram perfeitamente, eu estava utilizando na página o bootstrap-select.min.js e ele estava influenciando no código, por isso não estava funcionando.
Uma pergunta: É possível marcar todas como resposta válida?
Answer: Não existe erros no seu código! Simplesmente, como o  MarceloBoni disse no comentário Acredito que o que falta é incluir o jquery na sua pagina o qual deveria ter sido Falta é incluir o jquery na sua pagina. Para corroborar tal comentário faço executar aqui o seu codigo com o jquery.

        function IEcli() {
  var cbocontribuinte = document.getElementById('tp_contribuinte');
  if ($('#iecli').prop("checked")) {
    $('#estadual').val("ISENTO");
    $('#estadual').attr("readOnly", true);
    cbocontribuinte.selectedIndex = 2;

  } else {
    $('#estadual').val("");
    $('#estadual').removeAttr("readOnly");
    cbocontribuinte.selectedIndex = 0;
  }
}

    I. Estadual

  <input type="text" class="form-control" name="estadual" id="estadual" placeholder="" value="" />

  <input type="checkbox" name="iecli" id="iecli" onclick="IEcli()"> Isento?

  Insc.Municipal

    <input type="text" class="form-control" name="nome" placeholder="" value="" />

   Contribuinte

    <select class="form-control selectpicker" name="tp_contribuinte" id="tp_contribuinte" onchange="atualizaIEDest();">
      <option value="0">Selecione</option>
      <option value="1">1 - Contribuinte ICMS</option>
      <option value="2">2 - Contribuinte isento de inscrição no cadastro de contribuintes</option>
      <option value="9">9 - Não contribuinte, que pode ou não possuir inscrição no cadastro de contribuintes</option>
    </select>

Se realmente queres usar JavaScript puro use a resposta do Sergio


Discrete Fourier Transform - Definition?

Question: On the internet I have found the definition of the DFT to be :
$$
F(k) = \frac{1}{\sqrt{N}}  \sum\limits_{n=0}^{N-1} f(n) e^{-\frac{2\pi}{N}jkn}
$$
But in this article I have found an implementation which doesn't really match the formular above. Are there different definitions ? Can I exchange the $e^{-\frac{2\pi}{N}jkn}$-part with something else? And if yes, why ?
The implementation in the article I mentioned above looks similar to:
<code>for (i = 0; i <= transformLength /2; i++) {
   cosPart[i] = 0;
   sinPart[i] = 0;
   for (k = 0; k < transformLength; k++) {

       tmp = 2*i*M_PI*( double)k/(double)transformLength;
       sinPart[i] += inputData[k] * (-1) * sin(tmp);
      cosPart[i] += inputData[k] * cos(tmp);
    }
}
</code>
Could someone explain to me the context between the sin/cos functions and the e-function in the definition formular?
Answer: The following equation holds for all $z\in\mathbb{C}$:
$e^{iz}=\cos z+i\sin z$
With, of course, $i=\sqrt{-1}$. This relation is known as Euler's formula, and you can see it is true by looking at the power series of the exponential, the cosine and the sine.
The article you linked computes the imaginary part of the Fourier transform explicitly, meaning without using complex numbers, and saves it separately as sinPart.
Answer: What has not been mentioned is that different books, papers, and software will have different conventions on the normalization of the discrete Fourier transform. One normalization that is a bit more common than the one in the OP is
$$X_n=\sum_{k=0}^{N-1} x_k \exp\left(-\frac{2\pi i kn}{N}\right)$$
that is, without the normalizing factor in front that makes for convenient formulae for the forward and inverse transform. Sometimes, one will have a forward transform without the minus sign in the exponential. If you're going to be doing Fourier work, ensure that the normalization conventions you are using in your work is the same as the convention in the software you will be using.


Is there any limits for binary serialization / deserialization object graph size in .net?

Question: For example, i have:
struct SomeStruct
{
   //some fields
   //each instance will store info read from file, maybe be 3kb, maybe more.
}

List<SomeStruct> lst = new List<SomeStruct>();

I will add to that list crazy amount of objects, so it will end up to 10Gbs or more in size.
Can i serialize lst without any errors like out of memory and etc? Can i deserialize it later?
Answer: If you can hold the list of items in memory at one time, you should have a decent chance of serializing/deserializing them. You may want to handle them individually, in a stream, rather than serializing/deserializing the entire list all at once, perhaps. That would take care of any edge cases you might have.
Pseudo-code:
private void SerializeObjects(List<foo> foos, Stream stream)
{
    foreach (var f in foos)
    {
        stream.Write(f);
    }
}

private void DeserializeObjects(List<foo> foos, Stream stream)
{
    foo f = stream.ReadFoo();
    while (f != null)
    {
        foos.Add(f);
        f = stream.ReadFoo();
    }
}


Sending emails without looking like spam

Question: I want so send every week an update by email. But Im afraid that if there are too many emails sent, they will be marked as spam. Any of you has experience sending many emails (thousands) weekly? What techniques do you use?
Answer:
A good answer for this question would
  be a real gold mine for a motivated
  spammer :)

Not really -- as you'll see in that other thread, answers center on showing that you are the authorative sender of the email, and various aspects that are useless to spammers and useful to non-spammers who send a lot of email.


Confirmation of PowerShell behaviour on arrays

Question: Consider the following small script:

$a = @(1,2,3)         #1
$b = $a               #2
$a[0] = 101           #3
$b += 99              #4
Write-Host "a: $a"
Write-Host "b: $b"

The output is this which required me to think a bit:

a: 101 2 3 b: 101 2 3 99

My observations for clarification:

The $b array contains four elements in the output so $b = $a is creating a copy of original array with three items in it and then the 99 element is added. If $b = $a was a pointer operation, then adding an element to $b would effect the $a array as well
The array contains pointers to the integers and not the integers themselves. Proved by the fact that line #3 changes the contents of both arrays. If $a contained integers, then $b wouldn't have been affected

So my understanding is:
A PowerShell array is always an array of pointers even if it contains just integers. Assigning an array to another variable creates a copy of that array of pointers.
Right?
Answer: I don't know the actual reason behind this, but if you look at this behavior, you can begin to understand it:
$a = @(1,2,3)
[int[]]$b = $a
$a[0] = 101
$b += 99

Write-Host $a"`n"
101 2 3

Write-Host $b"`n"
1 2 3 99

You can see that it does not "link" $b to $a and instead initializes it as a separate array.

Further reading on Value Types VS Reference Types

http://www.leeholmes.com/blog/2006/09/05/value-types-vs-reference-types/
http://kizan.com/20143263-reference-types-powershell/
Comment: Thanks for this addition as it does make it clear what's happening. For somebody coming from a more traditional C/VB background, it caught me out. I'm not saying PowerShell is wrong - just different. I suppose my next question should be can you work with references to arrays. In my real life example, I wasn't actually working with integers but a JSON tree structure and I assigned a variable to a collection part way down the tree expecting a pointer but got a copy of the array instead and then wondered why the changes weren't written back
Comment: I think that the data types are pretty flexible in Powershell, to the point where it's not worth worrying about. Although I did dig up some articles that might help in terms of understanding. I've added them to my answer.
Answer: I think internally these are implemented as linked lists and not arrays. The difference being that it is very expensive to add an item to an array, because the size of an array is declared, then contiguous memory is allocated for it. Because of this, there is no guarantee that the next contiguous block of memory is available to the array, and a new array of size (origArray + 1) has to be created, the old array copied in and the new element copied in as well. I have no proof of this of course other than programming experience and observing the behavior of powershell.
Update
I do have proof! Avoiding the list operator vs. How an Array is declared in powershell. Note the user of the New-Object cmdlet when declaring an array:
PS > $myArray = New-Object string[] 10

So, what you're interacting with on the command line are two linked lists. I'm not sure how Powershell/.NET handles copying linked lists, although it appears from your example that for efficiency $b simply holds the same pointers as $a, but when you add an item to $b or $a it doesn't show up in the other, unless explicity copied again. I like to refer to this as a static copy, though I don't know if that term has use in the field.
Comment: Thinking further, it's preferable that the array contains pointers and not the actual variables. Just think of the performance overhead if large objects were being manipulated and not small integer. An operation like $a[0] = SomeBigObject would be pretty slow if it made a copy of the object. The gotcha for me coming from vb.net is that Array2 = Array1 is a pointer operation - it doesn't create a duplicate array which I'm pretty sure is what PowerShell is doing


How do I find this angle in the given quadrilateral?

Question: I'm not looking for the answer, but for how to work it out (IE what steps should I take; I think I've sketched the shape with the wrong measurements in each area) cuz I'm completely clueless. Here's the question:
'In a quadrilateral ABCD, AB = 4, BC = 5, CD = 7, DA = 5, and angle ABC is 87 degrees. Find angle ADC'
Thanks :)
Comment: It's going to involve a lot of trig, and a lot of numerical answers. The first step is to find out the length of $BD$.
Comment: @ParclyTaxel why do I need BD?
Comment: You can split the quad into two triangles ABC and CDA. You know all four sides; once you get BD you can solve for everything.
Answer: Hint. Use the Law of Cosines in the triangle $\triangle ACB$ (to find $|AC|^2$) and in the triangle $\triangle ACD$ (to find angle the $\angle ADC$):
$$|AB|^2+|BC|^2-2|AB||AC|\cos(87^\circ)=|AC|^2=|AD|^2+|DC|^2-2|AD||DC|\cos(\angle ADC).$$


What determines the size of a saved object in R?

Question: When I save an object from R using save(), what determines the size of the saved file? Clearly it is not the same (or close to) the size of the object determined by object.size().
Example:
I read a data frame and saved it using
<code>snpmat=read.table("Heart.txt.gz",header=T)
save(snpmat,file="datamat.RData")
</code>
The size of the file datamat.RData is 360MB.
<code>> object.size(snpmat)
4998850664 bytes        #Much larger
</code>
Then I performed some regression analysis and obtained another data frame adj.snpmat of same dimensions (6820000 rows and 80 columns).
<code>> object.size(adj.snpmat)
4971567760 bytes
</code>
I save it using
<code>> save(adj.snpmat,file="adj.datamat.RData")
</code>
Now the size of the file adj.datamat.RData is 3.3GB. I'm confused why the two files are so different in size while the object.size() gives similar sizes. Any idea about what determines the size of the saved object is welcome.
Some more information:
<code>> typeof(snpmat)
[1] "list"

> class(snpmat)
[1] "data.frame"

> typeof(snpmat[,1])
[1] "integer"

> typeof(snpmat[,2])
[1] "double"         #This is true for all columns except column 1

> typeof(adj.snpmat)
[1] "list"

> class(adj.snpmat)
[1] "data.frame"

> typeof(adj.snpmat[,1])
[1] "character"

> typeof(adj.snpmat[,2])
[1] "double"         #This is true for all columns except column 1
</code>
Comment: @Pratyay What do you know about compression?  It would probably be beneficial to read up on it as that's basically what you're asking. http://en.wikipedia.org/wiki/Data_compression
Comment: The saved `.Rdata` file is compressed and should thus be smaller.  How much smaller will depend on the compression algorithm and your data.
Comment: If you have an example where the serialized size is much bigger than object.size, it might be interesting to post it with code/data. One particular documented situation where this can happen is when data is hidden in an environment - environment content is excluded from object.size calculation.
Comment: In my example, what might be the reason?
In other words, can you tell me what aspects of the data affect it?
Comment: @Dason Thanks. I went through the link. But I still do not understand how it works specifically in R. What data types are compressed better? Also, in my example, the two data frames had everything similar. Why is there such a huge difference in compression?
Also, is there any tricks to generate smaller files while saving objects? eg using some particular data types or so?
Comment: I have the same issue with a variable around 5Mb with `object.size` which become 750Mb after `save` !
Comment: Unfortunately I cannot share the only data for which I encountered this. I tried to produce a small reproducible example, but it didn't work. Can you tell me how to check if there is any hidden component? I am not sure if I fully understood about that. Since you said it is documented, can you lead me to such documentation?
Comment: I was referring just to `?object.size` (environments and external pointers are excluded). To exclude the impact of compression from your experiments, you can use `compress` argument of `save`.
Answer: Your matrices are very different and therefore compress very differently.
SNP data contains only a few values (e.g., 1 or 0) and is also very sparse.  This means that is very easy to compress.  For example, if you had a matrix of all zeros, you could think of compressing the data by specifying a single value (0) as well as the dimensions.
Your regression matrix contains many different types of values, and are also real numbers (I'm assuming p-values, coefficients, etc.)  This makes it much less compressible.


Spring @Autowired not working with configuration files across multiple projects

Question: I have different Java projects for data, business and web layer. I initialize the Spring context in the web layer and have all the Spring beans XML file(s) only in the web layer.
@Autowired feature works only for Spring beans in the web layer (and does not works for the Spring beans from the other two projects).
Do I need to define the Spring beans XML configuration in the other two projects (data and business) as well?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
    http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
    http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.jai.mdm" />
    <context:annotation-config />

    <jaxrs:server id="mdmCxfServer" address="/">
        <jaxrs:serviceBeans>
            <ref bean="airlineService" />
        </jaxrs:serviceBeans>

        <jaxrs:extensionMappings>
            <entry key="json" value="application/json" />
        </jaxrs:extensionMappings>

        <jaxrs:providers>
            <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
        </jaxrs:providers>

        <jaxrs:features>
            <cxf:logging />
        </jaxrs:features>
    </jaxrs:server>

    <bean id="airlineBusiness" class="com.jai.mdm.business.impl.AirlineBusinessImpl">
        <property name="airlineRepository" ref="airlineRepository" />
    </bean>

    <bean id="airlineRepository" class="com.jai.mdm.data.repository.impl.AirlineRepositoryImpl">
    </bean>

    <jpa:repositories base-package="com.jai.mdm.data.repository"  />

    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
        <property name="url"
            value="jdbc:oracle:thin:@localhost:1521/jaydb" />
        <property name="username" value="jay" />
        <property name="password" value="jay" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.jai.mdm.data" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven />
</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<display-name>mdm</display-name>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>CXFServlet</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

Comment: Define _not working_. Are the fields `null`? Does it throw an exception? Provide an MCVE.
Comment: Would you mind sharing your Spring configuration file? Additionally, do you use multiple XML files? If so, across the three projects? And the last one: are you using Maven?
Comment: @ɐuıɥɔɐɯ - Thanks code added
Answer: I would recommend to use a different Spring XML configuration file (or more depending on your needs) for every project. The JPA repositories, for instance, are used to be declared in your data project and imported whenever needed; the same for the others.
Have a look at the import from Spring.
I think you can have many configuration files in each project and be able to import them from web by using (the path /META-INF/* can be different):
<import resource="classpath:/META-INF/spring-context-data.xml" />
<import resource="classpath:/META-INF/spring-context-business.xml" />

Answer: It was my mistake... I have used the annotations ( like @Repository, @Service ) in the interface instead of the implementing class. After moving it to the class it works fine.


Enviar informação via post com Ajax e retornar valores separados

Question: Aqui tenho um código para abrir modal enviando o idcolaborador para buscar no arquivo cadastro.php e retornar nas variáveis.
Exemplo: data.data6, data.Colaborador6, data.Observacao6...
Dúvida: Queria saber como faço no php para atribuir as variáveis fazendo uma consulta no BD de uma tabela e retornando os dados para a pagina com as variáveis.

$(document).on('click', '.edit_data6', function(){
       var idcolaborador = $(this).attr("Id");
       $.ajax({
            url:"cadastro.php",
            method:"POST",
            data:{idcolaborador:idcolaborador},
            dataType:"json",
            success:function(data){

                 $('#data6').val(data.data6);
                 $('#Colaborador6').val(data.Colaborador6);
                 $('#Observacao6').val(data.Observacao6);
                 $('#Estado1').prop("checked", data.Estado);
                 $('#Conclusao').val(data.Conclusao);
                 $('#idcolaborador').val(data.Id6);
                 $('#insert6').val("Gravar");
                 $('#exampleModal6').modal('show');
            }
       });
  });
<?php
$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$Query = mysqli_query($conexao,"SELECT * FROM colaboradores WHERE id='".$dados['idcolaborador']."'")or die(mysql_error()); ?>
while($row=mysqli_fetch_array($Query)){
$data6 = $row['data6'];
$Colaborador6 = $row['Colaborador6'];
$Conclusao= $row['Conclusao'];
$Id6= $row['Id6'];} ?>
Comment: `dataType:"json"`, no AJAX você está esperando um JSON, então precisa fazer o PHP responder com um JSON. Leia sobre a função `json_encode` do PHP.
Answer: Fiz essa alteração do PHP, mas mesmo assim não está trazendo o valor na pagina com o exemplo do JS que mencionei acima. O que estou precisando é que os valores venham separados para usar em diferentes id na página.

<?php
$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$Query = mysqli_query($conexao,"SELECT * FROM colaboradores WHERE id='".$dados['idcolaborador']."'")or die(mysql_error());
while($row=mysqli_fetch_array($Query)){
  $resultado_dados = array(
    'data6' => $row['data6'],
    'Colaborador6' => $row['Colaborador6'],
    'Observacao6' => $row['Observacao6'],
  );
}

echo(json_encode($resultado_dados));

?>


Rails where to place your Activemodel::validators

Question: This is a two part question.
Part one if my Model that i am writing the validations for is inhering from ActiveRecord::Base do i need to include ActiveModel::Validations within that class?? the API for rails doesnt say but here in yehudakatz blog seems to hint that?
part two is where would be the best place to put these validator files? under helpers or as a new model or in lib?
my current validator looks like this
class GenderValidator < ActiveModel::validator
  def validate(record)
    cred = /(\d{6})(\d{4})(\d{1})(\d{2})/.match(record.id_number.to_s) #breaks up the id into the relevent sections namely birthdate, gender, nationality, validator.
    unless cred[0][/\d{13}/] #checks to see if the id is a valid length of numbers if it isnt then skip the validation of gender
      return true
    else
      birthdate = cred[1] #returns a 6 digit string 'yymmdd'
      parsed_gender = cred[2] #returns a 4 digit string '0001-4999:female 5000-9999:male'
      nationality = cred[3] # should return either a 1 or a 0 1 if the person is foreign or 0 if the person is southafrican

      validate_gender(parsed_gender, record)
    end
  end

  private
  def validate_gender(parsed_gender, record)
    calculate_gender = (parsed_gender <= 4999 ? :female : :male)
      unless employee.gender == calculate_gender
        employee.errors[:gender] << "Your id indicates you have entered the wrong gender"
      end
  end
end

an valid id number of each person is optional, but if they do specify it it should check to see if the gender is correct.
if i keep it in the same model the employees model then i get this error
ActionController::RoutingError (uninitialized constant Employee::GenderValidator):
app/models/employee.rb:25:in `<class:Employee>'
app/models/employee.rb:1:in `<top (required)>'
lib/role_requirement_system.rb:19:in `inherited'
app/controllers/employees_controller.rb:1:in `<top (required)>'
librato-rails (0.8.1) lib/librato/rack/middleware.rb:12:in `call'

so i take it they cant be in the same file. what is the best practice for validations? i watched all the rails casts and i have read a few blogs and i am quite new still.
EDIT
in my model i include this class like
include ActiveModel::Validations

and my validations look like this
validates_presence_of :name, :position, :gender
validate :instance_validations, :on => :create

def instance_validations
  validates_with GenderValidator
end

just incase you wanted to see that too
thanks ahead!
Answer: You do not need include ActiveModel::Validations
My preference to to keep the validation objects in the model folder.
So for model Gender you have a file gender.rb
For the validator GenderValidator you have the file gender_validator.rb
So both files site together in the model folder.
Here is a validator for my Newsletter model
class NewsletterValidator < ActiveModel::Validator
  def validate(record)
      if record.send_test_email
        if test_email_address.blank?
          record.errors[:test_email_address] << "Test email address is blank"
        end
        if record.send_email_to_subscribers
          record.errors[:send_test_email] << "You cannot send a test and send to subscribers at the same time"
        end
      end

  end
end

In my Newsletter model I simply have
  validates_with NewsletterValidator

You have a spelling  mistake in your example
You have
class GenderValidator < ActiveModel::validator

It should be
class GenderValidator < ActiveModel::Validator

Note the capital V


How can I solve for t if is part of $2 = {A+Bt \over A-Bt}?$

Question:
$2 = {A+Bt \over A-Bt}$

I've tried cross multiplying and have come up with a possible solution but I have no one to verify for me as it is very late where I am.
$$2(A-Bt) = A+Bt\\
2A-2Bt = A+Bt\\
A = 3Bt\\
{A \over 3B} = t$$
Is this the answer?
Comment: See [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for formatting tips.
Comment: Looks good to me! Do note that $B$ should not be zero nor should $A$ be zero.
Answer: Your working seems fine.
If you substitute it back in and check:
$$\frac{A+Bt}{A-Bt}=\frac{A+\frac{A}3}{A-\frac{A}3}=\frac{4A}{2A}=2$$


Templating Python class level attributes to create generic rest serializers

Question: I'm using the Django Rest Framework and would like to serialize different types using the same format. The format being a list of all instances of a specific type as well a certain selected instance.
My problem is that I have to write a different serializer class for every type that I want to serialize. In C++ I'd solve this by giving the type and type serializer as a template argument. How can I do this in Python?
The generic Object I'd like to serialize:
class OptionSelect(object):
    def __init__(self, options, selected):
        self.options = options
        self.selected = selected

What I currently need to serialize it:
class TypeAOptionSerializer(serializers.Serializer):
    options = TypeASerializer(many=True)
    selected = TypeASerializer()

class TypeBOptionSerializer(serializers.Serializer):
    options = TypeBSerializer(many=True)
    selected = TypeBSerializer()

class TypeCOptionSerializer(serializers.Serializer):
    options = TypeCSerializer(many=True)
    selected = TypeCSerializer()

Instead I'd like to create a Serializer like this:
class OptionSerializer(serializers.Serializer):
    options = serializer(many=True)
    selected = serializer()
    def __init__(self, serializer):
        self.serializer = serializer
        super().__init__()

Is there maybe a different approach that I should be taking?
Answer: You can try the following:
def create_serializer(serializer):
  class MySerializer(serializers.Serializer):
    options = serializer(many=True)
    selected = serializer()
  return MySerializer

TypeAOptionSerializer = create_serializer(TypeASerializer)
TypeBOptionSerializer = create_serializer(TypeBSerializer)
TypeCOptionSerializer = create_serializer(TypeCSerializer)

This should be equivalent to your current approach with three separate classes.


Passar List para um sub relatório e chama-lo no relatório principal

Question: Galera tenho um método que gera um relatório pdf em um determinado diretório, agora surgiu a necessidade de usar um sub relatório, porém estou com dificuldade em entender como posso passar uma List como data source pra esse sub relatório e depois exibi-lo no relatório principal.
Esse é o meu método que gera o relatório principal:
public boolean gerarRelatorio(List list, int numeroRelatorio, String nomePrestador, String dataSistema) {
        JasperReport report = null;
        InputStream image = this.getClass().getResourceAsStream("/br/com/xml/relatorio/LOGO.png");
        filtro.put("Image", image);
        try {

            InputStream inputStreamReal = getClass().getResourceAsStream("/br/com/xml/relatorio/Relatorio3.jrxml");
            report = JasperCompileManager.compileReport(inputStreamReal);
        } catch (JRException ex) {
            Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Erro ao pegar arquivos!", "ERRO!", JOptionPane.ERROR_MESSAGE);
        }
        try {

            JasperPrint print = JasperFillManager.fillReport(report, filtro, new JRBeanCollectionDataSource(list));
            JasperExportManager.exportReportToPdfFile(print,
                    "C:/Demonstrativos/" + dataSistema + "/" + nomePrestador + "_" + dataSistema + "_" + numeroRelatorio + ".pdf");

            /*Variaveis necessarias para salvar o Arquivo no Banco de dados*/
            caminho1 = "C:/Demonstrativos/" + dataSistema + "/";
            ext = ".zip";
            nomeArquivo1 = nomePrestador + "_" + dataSistema + "_" + numeroRelatorio;
            caminhoCompleto = caminho1 + nomeArquivo1 + ".pdf";

            codAP = Long.parseLong(codArquivoPrestador);
            relatoriosGerados = numeroRelatorio + 1;
            return true;
            /*Variaveis necessarias para salvar o Arquivo  no Banco de dados*/
        } catch (JRException ex) {
            Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Erro ao Gerar relatório, verifique se nenhum arquivo está aberto ou se o nome está correto!\n" + ex, "ERRO!", JOptionPane.ERROR_MESSAGE);
            return false;
        }

    }

--
Tentei passar a lista e o caminho por parâmetro da seguinte forma:
filtro.put("listaDados", lista);
filtro.put("localizarRel", "src/br/com/xml/relatorio/subRelatorio.jasper");

Porém da esse erro:
15/05/21 10:36:25 ERROR fill.JRFillSubreport: Fill 1: exception
net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : dataRealizacao

Esse Bean dataRealização faz parte do meu sub Relatório, algum sabe aonde posso estar errando?
Comment: Alguém pode me ajudar?
Comment: A resposta desta pergunta pode ser encontrada nesta pergunta que eu já  respondi a algum tempo: http://pt.stackoverflow.com/questions/32955/criar-relatorio-com-listas-aninhadas :o)
Answer: Bom dia! Você tem que criar um parâmetro do tipo List no seu relatório,
o mesmo tem que estar com o mesmo nome do parâmetro que você esta mandando em código. Exemplo:
filtro.put("listaDados", lista);

Crie "listaDados" no seu relatório, ai é só mandar para o sub-relatório assim:
new JRBeanCollectionDataSource(listaDados);
no dataset da sua lista, no campo "Use a JRDatasource expression" que você
 deve marcar.
Neste caso posso ver que seu relatório ou sub-relatório não esta encontrando o campo dataRealizacao, avalia o objeto da sua lista, tem algo errado nele.
Espero ter ajudado! Abraço!


Definition of topological space: Is Ω equal to the powerset of X?

Question: A topological space is a set $X$ and a collection $\Omega$ of subsets of $X$ such that:

$\emptyset \in \Omega$ and $X \in \Omega$
The union of any collection of $\Omega$ is in $\Omega$
The intersection of any finite collection of sets in $\Omega$ is again in $\Omega$

My question is, is the set $\Omega$ essentially the powerset of $X$? Or is the powerset of $X$ just a special case of a suitable collection of subsets of $X$?
Comment: Why does this question have so many similar answers?
Comment: It *can* be the power set of $X$, but it need not be. There are a lot of different topologies on a set $X$. It is always a subset of the power set, but most topologies are not closed under taking the complement.
Comment: @Unit All the answers appeared right after the question was posted. I suspect they were being composed in parallel. I know mine was. The answers are similar because the question has essentially one answer.
Comment: The requirement is that $\Omega \subseteq \mathcal P (X) $, not  $\Omega = \mathcal P (X) $.
Answer: The power set of $X$ is a special case of such a collection $\Omega,$ called the discrete topology on $X$. All topologies on $X$ will be subcollections of the power set of $X$ (by definition).
For a wildly different example (at least, if $X$ has more than one point), consider the indiscrete topology on $X$: $\Omega=\{\emptyset,X\}.$
Comment: I'd remark that the discrete topology is basically the degenerate special case where the space has _no_ topological properties anymore, but only behaves as a plain old set. In that sense, if the set of open sets were always the powerset, then we wouldn't need topology...
Comment: @leftaroundabout The indiscrete/trivial topology also is in some sense "behaving as a plain old set". Both are adjoints to the forgetful functor that forgets about topological structure: https://ncatlab.org/nlab/show/discrete+and+codiscrete+topology
Answer: The power set is a good example that defines a topological space. This is usually called the discrete topology. This is definitely not the only way to define a topology though!
On the other extreme, for any set $X$ $\tau=\{\emptyset, X\}$ is a topology on $X$.(do you see how this satisfies all your axioms?)
In general though, we don't care much about these topologies since their structures aren't difficult to understand. A large chunk of more interesting topologies are those that are induced by a collection of subsets. For example, the usual topology on $\mathbb{R}$ is the smallest topology that contains all the open intervals. It may not be obvious that this doesn't include the entire power set, so a good way to convince yourself of that would be to consider a singleton, for simplicity say $\{0\}$. Since topologies are closed under arbitrary unions and finite intersections, the question is if we can express $\{0\}$ with a combination of unions and only finitely many intersections of open intervals. Any two non-disjoint open intervals intersect in another open interval though and any arbitrary union of open intervals can always be written as a disjoint union of open intervals so it ends up we find that the only types of objects that we get from doing any combination of finitely many intersections and arbitrary unions of open intervals is a disjoint union of open intervals. Since $\{0\}$ is not a disjoint union of open intervals, $\{0\}$ is not a member of our topology.
I would suggest writing out a proof of this(in actual rigor) if you have time as I think that would be a good exercise to help you get an idea of why topologies aren't always just power sets. Hope this helps!
Comment: No problem. One thing I should have mentioned: the reason that I chose to look at a singleton is because if a topology contains all the singletons, then it is the discrete topology, which means that if a topology isn't the whole power set, then there must be singletons that are not in the topology.
Comment: It most certainly does! Thank you for your extensive answer!
Comment: Why the downvote on this and all the other answers but one (I suspect it's the same person)?
Answer: The power set of $X$ is a topology for $X$, but it certainly is not the only one.  Consider $\mathbb R$ with $\mathscr B=\{(a,b):a,b\in\mathbb R, a<b\}$ and $\Omega=\{\bigcup U_i: U_i\in\mathscr B\}$.  You are probably already aware that this is a topology, but $\Omega\ne\mathscr P(\mathbb R)$.  In general, a topology of $X$ is a subset of its power set with the stated properties.
Comment: That's not a topology by itself. We probably know what you meant, though.
Comment: Yes, you are confusing the basis of the topology on the reals with the topology on the reals.
Comment: Yes, I've fixed my answer.
Answer: The power set is an example of a topology, but a topology can be much smaller - for example, there's always the trivial topology $\Omega = \{\emptyset, X\}$.
Answer: The powerset of $X$ is a special case of a topology - the special case that makes every function to another topological space continuous. It's the largest possible topology.
But a topology need not be all the subsets of $X$. Many other subsets of the power set may satisfy the axioms. The smallest is the subset containing just $X$ itself and the empty set.
Comment: Why did you delete your previous answer and re-post it?
Comment: @ThomasAndrews By accident, while I was making a trivial edit.
Answer: Ω is a subset of the powerset of X.  It can be the entire powerset (at most), the set {∅,X} (at least), or another subset that meets the properties.
Answer: The power set can be a lot bigger than the topology. For instance, in the real numbers under the usual topology, there is a bijection between $\mathbb{R}$ and the topology $\mathcal{T}$, but due to Cantor's famous diagonalization argument, the power set of the reals has strictly greater cardinality than the reals.
The fact that the usual topology is in bijection with $\mathbb{R}$ comes from the fact that each open set is a union of rational intervals, and there are only countable many of these.
Comment: Could I get an explanation from the downvoter? This is the most important topological space and I have quantified the distinction between its powerset and its topology.
Comment: Every answer in the thread excepting the first was downvoted. Likely someone unhappy about the numerous similar answers.
Answer: Let X = {a,b} be a set with 2 elements. There are four distinct topologies on X:
<code>{∅, {a,b}} (the trivial topology)
{∅, {a}, {a,b}}
{∅, {b}, {a,b}}
{∅, {a}, {b}, {a,b}} (the discrete topology)
</code>
(wikipedia: Finite topological space)
The second and third of these are topologies, but are not power sets of X.
Afaict if all the elements of X are elements of the topology then there is only one topology, the discreet, identical to the powerset of X.
Comment: Note: It's the discrete topology. Discreet is if you don't talk about sensitive things.


Add blocks via layout.xml - magento

Question: I'm new to Magento so sry if it's a bit of a newbie question.
I was adding these blocks from a controller:
$this->_addContent($this->getLayout()->createBlock('abc/adminhtml_abc_edit'))
     ->_addLeft($this->getLayout()->createBlock('abc/adminhtml_abc_edit_tabs'));

The blocks were added. However now I'm trying to add the blocks via layout.xml. I've tried the following:
<abc_adminhtml_abc_edit>
        <reference name="content">
            <block type="abc/adminhtml_abc_edit" name="form">
                <reference name="left">
                    <block type="abc/adminhtml_abc_edit_tabs" name="tabs"/>
                </reference>
            </block>
        </reference>
 </abc_adminhtml_abc_edit>

but it didn't work out and I can't find how to do it right...
what's the correct way?
Thanks!
Krt_Malta
Answer: Find out how, after looking at some of the layout xml files of Magento. This did the trick:
<abc_adminhtml_abc_edit>
        <reference name="content">
            <block type="abc/adminhtml_abc_edit" name="form"/>
        </reference>
        <reference name="left">
            <block type="abc/adminhtml_abc_edit_tabs" name="tabs"/>
        </reference>
</abc_adminhtml_abc_edit>

Add blocks via layout.xml - magento


Como adicionar um elemento no final de uma lista ligada

Question: Preciso adicionar um elemento no final de uma lista ligada, fiz o método pedindo para ele adicionar como se ele fosse um elemento inicial caso a lista esteja vazia (está funcionando) e, caso não esteja, percorrendo a lista da seguinte forma:
else{
    Celula * cursor = prim;
    while (cursor != NULL){
      cursor = cursor -> getProx();

Para mim, quando ele chega na condição de parada, é porque o cursor = NULL, criando outra condição para adicionar o elemento que seria a seguinte:
if (cursor == NULL){
  Celula * c = new Celula(i);
  c->setProx(prim);
  cout << cursor->getInfo()<< endl;

Quando rodo o programa, eu consigo inserir o primeiro elemento normalmente, mas quando vou inserir no final, o programa quebra.
Caso alguém precise do programa full para entender melhor (desculpe se não sou bom com palavras rs), segue o link do arquivo no repl.it cujo problema está em ListaLigada.cpp
https://repl.it/@RodrigoCosta1/beijonabocaecoisadopassadoagramodaefazerlistaligada
(ignorem o título do link)
Comment: Se para em `NULL` ao fazer `->` qualquer coisa sobre `NULL` vai crashar. Troque a condição do `while` para `while (cursor->getProx() != NULL){`
Comment: Troquei e ele não crashou, mas mesmo assim não está adicionando nada do final.
Comment: Isso já tem a ver com a parte de definir o próximo. Olhando para o seu código e sem testar seria algo como a seguir ao `while`, fazer `Celula * c = new Celula(i);c->setProx(NULL);cursor->setProx(c);`
Answer: Você não está adicionando os itens nos final, está apontando todos os novos itens para o primeiro.
Você deve criar um novo item e apontar o ultimo da lista para ele, assim:
while (cursor->getProx() != NULL)
    cursor = cursor->getProx();

if (cursor->getProx() == NULL)
{
    Celula * c = new Celula(i);

    //  Aponta o ultimo item encontrado para o novo item.
    cursor->setProx(c);
}


Interpreting the random effect in a mixed-effect model

Question: I am looking at several dependant variables for which I created LMMs of the following kind:
DV ~ Group + (1|Subject) + (1|Time)

Now I am struggling with how to interpret the output concerning the random effects, e.g. for DV1:
Random effects:
 Groups   Name        Variance Std.Dev.
 Subject   (Intercept)  6.2     2.49
 Time      (Intercept) 67.7     8.23
 Residual             50.2     7.08

and for DV2:
 Groups   Name        Variance Std.Dev.
 Subject   (Intercept)  27.2     5.22
 Time      (Intercept)  17.7     4.21
 Residual             125.2    11.19

Are conclusions such as the following valid?

Variability between subjects was about twice as high for DV2 than DV1.
Variability between dates (time) was higher for DV1 than DV2.
For DV1 time accounted for a higher variability than subject
For DV2 a similar amount of variability can be attributed to time and subject.
For DV1 there was a variability of about 8 [units] between years.
For DV2 variability between subjects was about 5 [units].

Thanks!
Comment: Keep in mind what you are modelling. Each subject has its own intercept, and your model assumes that these intercepts follow a N(0,v) distribution. The variances reported are simply the "v" parameter here. Similarly for the time variable.
Answer: I'd suggest centering the interpretation around intraclass correlations:

For DV1, the total random variation not explained by the group differences (the fixed factor) is $\hat\sigma^2_{tot} = 6.2 + 67.7 + 50.2 = 124.1$, so that the total SD is $\hat\sigma_{tot}=11.14$. For DV2, these figures are $\hat\sigma^2_{tot} = 170.1$ and $\hat\sigma_{tot}=13.04$
For DV1, the correlation between two observations on the same subject but different times is $r_S = 6.2/124.1=.050$, while for DV2 it is $27.2/170.1 = .160$
For DV1, the correlation between two observations at the same time but different subjects is $r_T = 67.7/124.1=.546$, while for DV2 it is $17.7/170.1=.104$
For DV1, the correlation between two observations on the same subject and the same time is $r_{ST} = (6.2 + 67.7)/124.1 = 1-50.2/124.1=.595$, while for DV2 it is $1-125.2/170.1=.264$

Of course, point (4) may or may not be meaningful in your experiment. The largest correlation, by far is the Time one for DV1: Time effects contribute hugely to the variations in DV1.
I agree with ahfoss on avoiding the word "variability"
A bit more on intraclass correlation
Most experimental design books discuss this topic under "model II" or "random-effects models". Suppose that a measurement $Y$ follows $Y = \mu + S + E$ where $S$ is random variation among subjects and $E$ is error variance. Then $Var(Y) = Var(S)+Var(E) = \sigma^2_S + \sigma^2_E$. Now let $Y_1$ and $Y_2$ be two such measurements. Then in general,
$$Var(Y_1-Y_2)=Var(Y_1)+Var(Y_2)-2Cov(Y_1,Y_2) = 2(\sigma^2_S+\sigma^2_E)-2Cov(Y_1,Y_2)$$
If the measurements are on the same subject, then the $S$ term cancels out and we have
$$Var(Y_1-Y_2)=2\sigma^2_E$$
Equating these, we have
$$Cov(Y_1,Y_2) = (\sigma^2_S+\sigma^2_E) - \sigma^2_E = \sigma^2_S$$
and thus that $Corr(Y_1,Y_2) = \sigma^2_S / (\sigma^2_S+\sigma^2_E)$.
This is called the intraclass correlation because it is the correlation of two measurements in the same class. It is useful because having random effects in a model implies a correlation structure in the data, and this quantifies it. The above ideas apply when there are more random effects; you just add the variances of the random effects you are conditioning upon.
Comment: Although this is not exactly what the original question asked, I would say this is a better answer than mine since ICC is an ideal framework in which to present the results. One suggestion: in your point #1, you might clarify that "group differences" refers to a fixed effect in the model called "group", not the "Groups" listed in the random effects results. That confused me for a sec...
Comment: @ahfoss makes a good point. I edited the answer to clarify what I meant there.
Comment: Many thanks, I think that's just what I need! By any chance, do you know if there is a package/function in R with which it is quick and easy to calculate the interclass correlations for a LMM?
Comment: Hmmm, I don't know of an R package that does this, but one would think there would be. I'll let you know if I find something.
Comment: This posting: http://stats.stackexchange.com/questions/50561/computing-cronbachs-alpha-and-intraclass-correlation-coefficient-from-an-lmer-m does at least give an idea how to use the `VarCorr` function to get the variance estimates you need
Comment: Thanks! Could you explain a bit more what the idea behind these "interclass correlations" is and how I interpret those correlation coefficients?
Comment: OK, I added some discussion to my answer.
Answer: A few things. First, be careful with the general term "variability." In a general context it is fine, but if you are referring to variance or standard deviation specifically, use the correct term. Also, as per my comment to your statement, remember that these are variances of the distributions of subject- and time-specific intercepts.
Your statements (1) and (2) are not valid. If your goal in this analysis is to make an inference about absolute differences in variances between two variables with respect to a grouping, you would need some formal hypothesis test, which you have not implemented. You can make relative statements, however. You might modify (1) as "between-subject variability accounted for a greater proportion of the variance in DV2 compared to DV1"
Modify your remaining statements like this:
(3) Time accounted for a larger proportion of the variance in DV1 than subject
(4) modify as in (3), but how you define "similar" should be carefully considered based on your goals. In some contexts, a difference of 1 might be very meaningful...
(5) For DV1, time-specific means were drawn from a normal distribution with standard deviation 8 (assuming you have checked that normality assumptions hold, approximately)
Comment: Looking at the residuals is good. What I was referring to is verifying that the distribution of the random intercepts are also approximately normal, which you should also check.
Comment: Many thanks for your answer, one more question concerning (5), which normality are you referring to? I looked at the QQplot of the model residuals, is that sufficient or do I have to do further tests?


How to determine the appropriate VSS hotfixes/updates to apply to a Windows 2003 server?

Question: Yes...I know...Windows 2003 has already EOL'd now.
I'm dealing with a remaining one in a large environment and have some issues that I believe are related to VSS according to a KB hotfix article.  Instead of applying just that single hotfix, I'd like to gather the VSS rollups that have been missed over the years.
For some reason I can't seem to remember or find how to check which VSS updates/hotfixes the server would need.  I know hotfixes typically are "deploy if needed in a certain situation" but Microsoft offers some VSS update rollups that include hotfixes.  However, MS is also bad about not simply publishing a chronological list that would say "here's the latest VSS rollup, apply this one".
Is there a way to find out which VSS rollups are needing to be applied to a server without trying to check file versions against each KB article?  Windows Update itself doesn't seem to list out any VSS specific patches, likely because they are considered hotfixes/hotfix rollups.
Comment: I would presume this is the latest rollup to apply: https://support.microsoft.com/en-us/kb/940349 - but I'm not certain on that...so hence the question.
Comment: Did you run across this article: http://blogs.technet.com/b/yongrhee/archive/2009/10/12/list-of-storage-related-hotfixes-post-service-pack-2-for-windows-server-2003.aspx
Comment: @austinian - no but that does help at least shortcut me to where I can figure it out manually for the most part.
Comment: I just checked to see if the VSS related hotfixes were available via the Microsoft Update catalog, and they don't seem to be, so I can't check their status with WSUS. I found http://serverfault.com/questions/15122/how-do-you-know-when-a-microsoft-hotfix-has-been-obsoleted-by-a-newer-patch and http://arstechnica.com/civis/viewtopic.php?t=223079 as related questions. Unfortunately, none of them are resolved.
Comment: @austinian - correct, WSUS wouldn't assist me on it either.  Thanks for the help...this pushes me down the right path.
Answer: Unfortunately, there doesn't seem to be a good method for doing this if you don't have access to the  Microsoft Premier Support knowledgebase, which, from what I can tell from here, isn't even guaranteed to have the information you're looking for, but is simply likely to have it. Both I and many others seem to have searched for a tool or solution to the hotfix problem, but have found the quick-and-easy solution to be non-existent.
So, no, there still isn't an easy way to tell if a Hotfix has been superseded unless it's been clearly published as being superseded in its KB article. You're left doing the footwork (file version numbers) unless you have a support contract that will provide the information for you.
Related: How do you know when a Microsoft hotfix has been obsoleted by a newer patch?
Comment: Correct that the Premier site (which I do have access to) doesn't list it, at least not in KB 940349 at https://premier.microsoft.com/kb/940349.  It does say which KB's it replaces, but doesn't say it was superceded by anything, so maybe that means it is the latest...hard to say for certain.  But I do have Premier support so I'll open a case and see what they say is the latest and report back to you and accept your answer.
Comment: No...not really.  I opened the case and they said basically what we already discussed here.  So I ended up replacing the server with a 2012 VM  :)
Comment: Were you ever able to resolve this?


VMWare Virtual Storage Appliance 5.1: Network clarification

Question: After bludgeoning my way through a vanilla two-node VSA installation ("Greenfield"), I have a VSA setup with no machines running at the moment; just trying to get my head around how the network is configured.
You can see what the network is configured as here (borrowed from a VMWare blog post, but looks the same):

Caveat: what makes my deployment slightly more non-standard is the use of Emulex Flex NICs that handle the VLAN tagging within the firmware itself, so no tagging is taking place in ESXi natively, I just assign pre-tagged, pre-carved-up "virtual" interfaces to the corresponding pNIC/uplink/vSwitch accordingly.
Where I need clarification revolves around the fact that I have 8 physical NICs per (two) ESXi hosts; obviously I'd like to use them all.  However, all documentation I've seen for VSA centers around a 4-NIC (2 x 2 GbE) configuration.
Questions as follows:

I want to add another VM Network and remove/rename the pre-created/default VM Network to assign it to another virtual switch with a different pNIC (see above).
From what I can tell from the Summary tab, the "VSA-01" and "VSA-02" VSA virtual machines are only configured with the "VSA-Front End" and "VSA-Back End" networks; removing the "VM Network" from vSwitch0 should have no impact, nor should creating any other virtual machine networks on new vSwitches.  Does this sound about right?

I see there's a "VSA-VMotion" port group.  Is this for VSA-related VMotion activities only, or is this also used for "normal" VMotion moves between the two ESXi hosts in the cluster?
Comment: were you not tempted to use the VSAN feature with vSphere 5.5? I know it's still technically in beta but it's as stable as VSA and will replace it once it's released.
Answer: Regarding 4 vs 8 pNICs.  Your current (ASA derived) configuration binds x2 pNICs to vSwitch0 and x2 pNICs to vSwitch1.  There is absolutely nothing stopping you adding two more pNICs each to your existing vSwitches, to give you utilisation over the whole of 8 pNICs.  As long as the additional pNICs are configured to carry the same VLANs as the existing ones, there is no problem with this approach.
Answers to your questions:
(1) This should not cause any issues. You can rename/delete the default VM network, just check none of your VMs are using it first.  According to your screenshot, nothing is using "VM Network" currently, so you are safe to alter it.
(2) The VMotion port group created by VSA installer is for use by both VSA-VMs and your "normal" VMotion moves.
Note1: you appear to have management and VMotion on the same VLAN, "best practice" (whatever you take that to mean) is to separate this traffic onto different VLANS.
Note2: you probably don't want your VMs and management/VMotion interfaces sharing the same VLAN ID 1955, so you should separate them.
Answer derived from:
http://www.vmware.com/files/pdf/techpaper/VM-vSphere-Storage-Appliance-Deep-Dive-WP.pdf
Comment: Thanks.  I ended up redoing the VSA cluster and pre-configured the network as I wanted it and the VSA installation was successful; why the VSA creates this as default (vMotion/Management on same VLAN, VSA-Back End on a separate switch), I have no idea; Deep Dive suggested "costs/complexity" but honestly, you're buying the redundant switches regardless, how much more is it to throw a quad NIC in your hosts?  Should've standardized on an 8-NIC configuration , not 4, is what I'm saying.  Maybe new version of VSA in 5.5 will be different in that regard.


Why does the order of expectation plus the square root of order of variance equal the big $O_p$ rate of convergence in probability?

Question: Midway through p. 154 of this paper, the authors compute the expectation and variance of a variable $\sum_{i,j=1}^nG_{i,j}^l$ and get
\begin{align}
E\bigg[\sum_{i,j=1}^nG_{i,j}^l\bigg] & = O(n^2h^{l+1}), \\
\text{Var}\bigg[\sum_{i,j=1}^nG_{i,j}^l\bigg] & = O(n^3 h^{2(l+1)} + n^2h).
\end{align}
Using this they say that
$$
\sum_{i,j=1}^nG_{i,j}^l = O_p(n^2h^{l+1} + \sqrt{n^3 h^{2(l+1)}} + \sqrt{n^2h}).
$$
So it seems that the big $O_p$ rate of convergence in probability is given by the order of convergence of expectation and the square root of the order of convergence of the variance.
Why is this? Is this due to some kind of bias-variance decomposition? How can it be proved? For example, if we have a random variable $X$ such that $E[X] = O(n)$ and $\text{Var}[X] = O(n)$ how do we prove that $X = O_p(n + \sqrt{n})$?
Comment: See Chebyshev's Inequality.
Comment: Note that $X_n = O_p(n + \sqrt{(n)})$ if and only if $X_n = O_p(n)$.
Answer: Suppose $f, g$ are positive functions and $E(X_n) = O(f(n))$ and $\text{Var}(X_n) = O(g(n))$. Then there exist $C>0, N>0$ such that for all $n > N$, $E(X_n) < Cf(n)$ and $\text{Var}(X_n) < C^2g(n)$.
Given $\epsilon > 0$, let $k > \max(\frac 1 {\sqrt{\epsilon}}, 1)$.
For $n > N$,
$$
\begin{align}
P(|\frac{X_n}{f(n) + \sqrt{g(n)}}| < kC) &= P(|X_n| > (f(n) + \sqrt{g(n)})kC) \\
&\le P(|X_n - E(X_n)| > k\sqrt{g(n)}C) \\
&\le P(|X_n - E(X_n)| > k\sqrt{\text{Var}(X_n)}) \\
&\le \frac 1 {k^2} \text{ (by Chebyshev's inequality)}\\
&\lt \epsilon
\end{align}
$$
This shows that $X_n = O_p(f(n) + \sqrt{g(n)})$.
Comment: Excellent thanks!


android: show direction in google maps

Question: i am developing an android application that use map view.
i can add point to the map, zoom, get current location and animate to point.
but how to get direction between 2 points?
when user click on point to show direction between current location and clicked location.
Thanks
Answer:
but how to get direction between 2 points?

Math. This has nothing to do with Android. It has little to do with maps, even. It has everything to do with math.
Depending on the distances involved, you might be able to get away with treating things as plain Carteisan coordinates and do the necessary trigonometry. Over a significant distance, though, the curvature of the Earth starts to play a role, and the math will get harder.
You might consider using a search engine to find whatever versions of the formulas you would like to use.
Comment: i do not want to calculate direction ..... i neeed to draw the path from current location to choosed location inside my image view that use android google maps.
Comment: @ahmed: You may wish to update your question to reflect that. Your question, as written, gives no indication that this is your intent.
Answer: in order to show a direction on maps (android)
you can try to make an Overlaying custom route on your application.
We shall further assume that the route returned may contain additional information such as the local slope of the route (which could be important if one is negotiating the route in a wheelchair, for example). Since this requires a network access that could block the main UI thread if there are network difficulties, we shall also use this example to introduce the important skill of putting time-consuming or potential UI-blocking tasks on a background thread. and use AsyncTask to run the process in the background. To use AsyncTask we must subclass it.
maybe this is helped you out.
Comment: me too, use asynctask to avoid blocking UI apps and internet. sometimes it makes force close

android: show direction in google maps


which key-value data structures should i use? quick retrieval by value, and quick retrieval by key

Question: i have a set of pairs of data: (key, value). they key is unique, and so is the value (there will not be two equal values, nor two equal keys). Like this...
dataStructure = {"ph", 0}, {"f", 1}, {"o", 2}, {"th", 3} ...
(the index is arbitrary, but it must be accessible)
is there any data structure that (efficiently) allows me to retrieve the key of an item, given a value? like this:
dataStructure.getByValue("ph") -> 0 and dataStructure.getByKey(0) -> "ph"
I've been reading about hashmaps, but this is not the structure i'm looking for: hashmaps are for non-unique value items, so i can't retrieve the key given a value.
I'd like to use this as a codifier, "photho" would be codified into 0230, and this would be decodified as "photho" again.
I'd like to know the name of the data structure... it doesn't matter the language...
Answer: Boost. bimap  should suit you.

Boost.Bimap is a bidirectional maps library for C++. With Boost.Bimap
  you can create associative containers in which both types can be used
  as key. A bimap can be thought of as a combination of a
  std::map and a std::map.
Answer: Use two maps.  Combine them into a single class, so that you can have  your two get methods on the same object.
Comment: this is a good answer... but i'm choosing Johan's answer, because he gave me the name of the data structure


node_access by specific role?

Question: I am trying to build a list of node ids that have view access for a specific role. Is this at all possible? I currently have an array of all 'page' content type nodes "pages".
I now need to loop through these and see if they have a specific role enabled, if so get the id and display the link on a page if the user has access to that page.
I know I can do that using the following example. But this just checks if the user has view access, and the user could have access from another role they have which my list would not be accurate for what I am trying to achieve.
if(node_access('view', $nodeid, $user)){
    // do something
}

Or is there a way to check if a specific users role has view access rather than just access in general.
The reason I am trying to do this, is I am trying to get the list of specific pages dynamically if a role is given to that node "page".
Sorry if my terminology is off I am not super familiar with drupal.
Comment: "node ids that have view access for a specific role. "? What do you mean? It's roles that have privilages to content types, and to nodes of that types.
Comment: Exactly, I probably worded it wrong, or you read it wrong sorry. I came up with a solution. But yea I wanted to show all nodes where a user with a specific role had view access.
Comment: Could you reword it, then? And you know, self-answers are allowed, even encouraged.
Comment: Yea I will post what I used as an answer in a min, just woke up.
Answer: This is what I ended up using, it could probably be optimized a bit but it works.
<?php
if ($node = menu_get_object()) {
  // Get the nid
  $currentNode = $node->nid;
}
if (in_array("Gold Member", $user->roles)) {
    echo '

Free Courses for Gold Members

';

    echo '
';
        $role_type = 'Gold Member';// Texas Member
        $getRole = db_query("SELECT rid FROM role WHERE name = '%s'",$role_type);
        while ($roleid = db_fetch_object ($getRole)) {
          $roleids[] = $roleid;
        }
        //Get the ID of the role type we are using from the array
        foreach($roleids as $roleId){
            $role_id = $roleId->rid;
        }

        $node_type = "page";
        $result = db_query("SELECT * FROM node WHERE type = '%s'", $node_type);
        $nids = array();
        while ($obj = db_fetch_object ($result)) {
          $nids[] = $obj;
        }

        $idsToInclude = array();
        foreach ($nids as $pageId) {
            $page_id = $pageId->nid;
            $realm = 'content_access_rid';// content access
            $grant_view = 1; // Has view
            $result = db_query("SELECT * FROM node_access WHERE nid != '%d' and nid = '%d' and gid = '%d' and realm = '%s' and grant_view = '%d'",$currentNode, $page_id, $role_id, $realm, $grant_view);

            while ($obj = db_fetch_object ($result)) {
              $idsToInclude[] = $obj;
            }
        }

        //var_dump($user->uid);
        //var_dump($nids);

        foreach($idsToInclude as $id){
            $courses = $id->nid;
            $nodeid = node_load($courses );
            if(node_access('view', $nodeid, $user)){
                echo '
'.$nodeid->title.'
';
            }
        }
    echo '
';
}

?>

node_access by specific role?


Drupal 7: how to build a form system

Question:
I want to build something like:
We have 2 type of users: staff and student.
Student logins into a drupal site, then a collection of forms presented to the student
Form type 1: Student selects a form then fill in all fields. After hitting the submit button, data will be saved as a node.
Form type 2: Similar as form type 1, except the same student visits the same form, s/he will see the previous data s/he entered.
Very similar situation for staff.
I wonder what are the basic steps I need to take.
Answer: I can't give the complete solution, Yet I will try to relate things what you have asked to things what we have in Drupal,

Form type 1 =>  Any Node type (say Article)
Form type 2 =>  Any Node type (say blog)
Student => Drupal User (has a profile of student, use profiles2 module )
Teacher => Drupal User (has a profile of Teacher, use profiles2 module )

User Permissions for Node creation, Node edit by its own author. Views to display the forms and user redirection module to get something you want.

Drupal 7: how to build a form system


What is the nature of the series $\sum \frac{5^n - 3^n}{3^n + n^4 } $

Question:
What is the nature of the series with the general term $u_n = \frac{5^n - 3^n}{3^n + n^4 } $ ?

I have tried to find an inequality from which I can derive the convergence or non convergence of the serie but I could not progress much beyond:
$ u_n \geq \frac{5^n}{3^n + n^4 } \ge \frac{3^n}{3^n + n^4 } $
And: $\lim  \frac{3^n}{3^n + n^4 }  = 1$
which is not helpful.
I tried also to write $(u_n)$ in the exponential form but I could not proceed either.
What convergence criteria will be used in this case?
Thank you.
Comment: Your first inequality is backwards, since $$u_n=\frac{5^n-3^n}{3^n+n^4}= \frac{5^n}{3^n+n^4}-\frac{3^n}{5^n+n^4}<\frac{5^n}{3^n+n^4}.$$
Comment: I think it is a sequence, what want you to know?
Comment: @Dr.SonnhardGraubner I want to know if $\sum u_n$ converges or not.
Answer: If a series $\sum u_n$ converges, then $\displaystyle\lim_{n\to\infty} u_n = 0$.
But
$$
\lim_{n\to\infty} \frac{5^n - 3^n}{3^n + n^4 } = +\infty
$$
and so the series diverges.
Answer: Hint: We get
$$\lim_{n->\infty}\frac{5^n-3^n}{3^n+n^4}=\infty$$
Answer: Your first inequality, that is, $u_n\geqslant\frac{5^n}{3^n+n^4}$, is a good starting point. Now, use the fact that$$\lim_{n\to\infty}\frac{\frac{5^n}{3^n+n^4}}{\frac{5^n}{3^n}}=1.$$
Comment: I don't know how to derive the convergence of $\sum u_n$ from that. Can you elaborate more?
Comment: @ZouhairElYaagoubi Use the [comparaison test](https://en.wikipedia.org/wiki/Limit_comparison_test).


Is there any relationship between growth rate and amenability?

Question: Let $G$ be a finitely generated group, I'm interested in whether there is any relationship between amenability of $G$ (as a discrete group) and its growth rate. To make the question more precise let's divide the class of finitely generated groups into groups of polynomial, intermediate and exponential growth and into groups which are not amenable, elementary amenable and amenable but not elementary so. This gives $9$ possible combinations of growth rate and amenability, can they all occur? Thanks to Ycor's comments the table is now complete.
$$\begin{array}{c|ccc} \text{amenable/growth} & \text{polynomial} & \text{intermediate} &\text{exponential} \\
\hline
\text{no} & \varnothing & \varnothing & F_2 \\
\text{elementary} & \Bbb Z & \varnothing & BS(1,n)\\
\text{yes but not elementary} & \varnothing & \Gamma & \Bbb Z/(2)\wr\Gamma\end{array}$$
where $F_2$ is the free group on two generators, $BS(1,n)=\langle a,b\mid b^{-1}ab=a^n\rangle$ is a Baumslag-Solitair group, and $\Gamma$ is Grigorchuk's group.
I'm looking for examples to fill in the remaining cells or proofs that some of them are empty
Comment: Finitely generated groups of subexponential growth are amenable.
Comment: Thanks @mathworker21, that settles two cases! Do you have a reference I can read for a proof?
Comment: I copied and pasted that from wikipedia. I'm sure wikipedia has references. If not, there's a book on amenability by paterson, and there are course notes on amenability by Kate Juschenko
Comment: The box (elementary amenable group of intermediate growth) is $\emptyset$. Indeed for such group Chou showed that unless virtually nilpotent, they have a free subsemigroup on 2 generators, and hence exponential growth.
Comment: The box (amenable but not elementary amenable)—(polynomial growth) is empty by Gromov's theorem.
Comment: The box (amenable but not elementary amenable)—(exponential growth) contains the wreath product $Z/2Z\wr\Gamma$ for $\Gamma$ the Grigorchuk group.
Comment: @YCor thanks for the comments, I added those to the question and accepted your answer!
Answer: Here the short proof of the fact that every f.g. group of subexponential growth is amenable.
Let $S$ be a symmetric generating subset with 1. If $G$ has subexponential growth, then clearly $\liminf |S^{n+1}|/|S^{n}|=1$. So we can extract from $(S^n)$ a Følner sequence.
The converse fails: many f.g. solvable groups have exponential growth.


Return True ou False no Success do jQuery

Question:

< script type = "text/javascript" >

  $(document).ready(function() {

    $('#btnEnviarDados').click(function() {

      var strFomr = $("form").serialize();

      $.ajax({
        url: $("form").submit(),
        type: "POST",
        data: strFomr,
        contentType: 'application/json; charset=utf-8',
        cache: false,
        success: function(ret) {
          if (ret == true) {
            alert('funcionaou');
            location.href = "@Url.Action("
            Contact ")"
          } else
            alert("noa funcionou a rquisicao");
        }
      });
    });
  }) < /script>

Meu Controller:
 public JsonResult CadastroUsuario(Usuario _usuario )
    {
        if (ModelState.IsValid)
        {
            return Json(new{ret = true });
        }
        else
        {
            return Json(new { ret = true });
        }
    }

o problema é que na View retorna apenas o valor true ou false como mostra a imagem, e eu queria que o retorno fosse no success do jquery.

Alguém tem algum ideia de como retorno o valor true ou false no success do jQuery para exibir um alert do retorno?
Comment: Creio que o correto seria algo como: `success: function(data) {
          if (data.ret == true) {`
Comment: Possível duplicidade: http://pt.stackoverflow.com/questions/29382/fun%C3%A7%C3%A3o-ajax-retornar-valor
Answer: Tente fazer da seguinte forma: no JS, valide direto o objeto retornado e no C# retorne o boolean direto sem criar um objeto pra armazenar esse valor. Como no exemplo que deixei abaixo e veja se funciona:


How to get the right JSON credentials file from google cloud console project?

Question: I am trying to authenticate my flask web app to send password reset emails using the google Gmail API, I have already set up my project and acquired my credentials json file in the google console. When I run my code, the following method in the class handling the whole authentication process catches the DefaultCredentialsError

def get_credentials(self, authorization_code=None):
    if self.credentials is not None:
        return self.credentials

    # Load the saved credentials
    try:
        creds = google.auth.load_credentials_from_file(Config.Config.PATH)
    except DefaultCredentialsError:
        flash('SETUP INCOMPLETE', 'warning')
        return redirect(url_for('home'))

the problem is with the file having a type None instead of one of the expected file types,,, this is the error message from the browser
google.auth.exceptions.DefaultCredentialsError: The file C:\Users\MARK KARIUKI\OneDrive\Documents/googleDocs/creds.json does not have a valid type. Type is None, expected one of ('authorized_user', 'service_account', 'external_account', 'external_account_authorized_user', 'impersonated_service_account', 'gdch_service_account').
how can I get a json file that has the required type? ,,, for my application I need the 'authorised user' type.
I have tried recreating the credentials a couple of time but the same details are included in the json file and no type key is included in the dictionary contained in the json file.
Answer: If you are creating a flask web app then you would probably want to create web application credentials.   This will use Oauth2 to request consent of the user to access their gmail account and send emails on their behalf.
You appear to have maybe created service account credentials.  A service account is like a dummy user if you configure domain wide delegation on your google workspace account you can then impersonate any user on the domain and send emails on their behalf.  however the code to authorize a service account is different then the code used for Oauth2 authorization
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE_PATH,
    scopes=SCOPES)

credentials = credentials.create_delegated(user_email)

Remember service accounts only work with the gmail api if you use them with a google workspace domain account.
Comment: No I am using OAuth client ID instead,,, the problem is with the json file generated, its type is None but it is supposed to have a valid type in my case authorized_user and I think the problem is the way I am generating my credentials but I don't know where I'm doing it wrong
Comment: Then generate a new client it should be type web.  [Video](https://www.youtube.com/watch?v=pBVAyU4pZOU)


Angular 6 ngx-bootstrap Datepicker global locale

Question: I'm using the ngx-bootstrap datepicker for my Angular 6 project and I need to use the italian locale; with the official guide (https://valor-software.com/ngx-bootstrap/#/datepicker#locales) i figured out this problem and now my datepickers look in italian, but I have another problem.
To have datepicker in italian, I had to import in every component the BsLocaleService and use in the onInit function the _localeService.use('it') method;
my question is, can I se globally the italian locale in my app, without call the function to set locale in every component?
I tried to use the set locale function in the AppComponent, but it doesn't work.
Thanks guys
Answer: For future readers, this is how i did this:
<code>import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

import { BsDatepickerModule } from "ngx-bootstrap";
import { BsLocaleService } from 'ngx-bootstrap/datepicker';
import { defineLocale } from 'ngx-bootstrap/chronos';
import { itLocale } from 'ngx-bootstrap/locale';

import { MyComponent } from "./my.component";

@NgModule({
    imports: [CommonModule, BsDatepickerModule.forRoot()],
    declarations: [MyComponent],
    providers: []
})
export class MyModule {
    constructor(localeService: BsLocaleService) {
        defineLocale('it', itLocale);
        localeService.use('it');
    }
}
</code>


Add a CSS class to field in content type

Question: I'm fairly new to Drupal and I want to add a custom CSS class to a custom field in content type.
I've created a content type called 'custom page' and I have a field called 'custom_page_main_title' the only thing I would like to do is to add a custom CSS class or iD to this
How can I do this please? Thanks!
Comment: Are you using a custom theme?
Answer: I wrote a blog post about this a little while ago.  It mostly serves as a reference for understanding the method for targeting the markup for specific fields in specific content types utilizing theme functions in template.php which is stored in your theme's directory.
Definitely check it out.  If you can understand it, then in the future changing any of the HTML for particular fields, including the classes generated, becomes trivial.
To bring the pertinent content from my blog post into this thread, we have the following function in template.php:
function theme_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

What you would do would be to replace the word theme in the function name to the name of your theme, and since you're targeting a specific field in a specific content type, you would append to the word field in the function name with __custom_page_main_title__custom_page.  So the function would look something like:
function themename_field__custom_page_main_title__custom_page($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Now you need to decide where in the structure of the field the class needs to be added, so perhaps add that on as an addition to your original question.
Comment: Are you sure this can't be addressed with a preprocess function? It is way simpler and avoids the theme duplication maintenance burden.
Comment: btw, here's another guide: http://atendesigngroup.com/blog/adding-css-classes-fields-drupal
Comment: Interesting post, that does seem much more efficient and clever.  One question though: in his post, he makes a reference to `$field` but that variable is never once defined in his code example.  Any idea what that's all about?
Comment: Yeah, that's an error. The author actually means $name (or `$vars['element'][#field_name]`).
Answer: The best way is to create your own theme, then check the html generated and update the theme css, a good point to start is using Fusion theme.
Another option is using a module called CSS Injector.
Answer: You could install Display Suite It gives you an option to  append class to each field in your custom content type.
Comment: which module of display suite do you need to enable for this feature?
Comment: I might be wrong but enabling display suite, display suite extras and display suite UI should be sufficient.
Answer: There's a very simple module called Field Formatter CSS Class that does exactly this. When activated it allows you to add a CSS class to your field via the Manage display tab of your content type.