Android - always return to currently active activity from notification?

Question: I currently have a Tab screen in my application. I use a notification to notify the user of a state change in my application and in normal circumstances when the user clicks on the notification it will return to this tab screen.
Here is the code I use for this:
<code>        String ns = Context.NOTIFICATION_SERVICE;
        mNotificationManager = (NotificationManager) context.getSystemService(ns);

        Intent notificationIntentRegState = new Intent();
        ComponentName cn = new ComponentName(context, TabScreenActivity.class);
        notificationIntentRegState.setComponent(cn);

        contentIntentRegState = PendingIntent.getActivity(context, 0, notificationIntentRegState, 0);
        notificationRegStateText = context.getString(R.string.app_name);
        notificationRegState = new Notification(icon, notificationRegStateText, 0);

        notificationRegState.setLatestEventInfo(context, notificationRegStateText, context.getString(R.string.notification_text, contentIntentRegState);
        mNotificationManager.notify(3, notificationRegState);
</code>
However in my application the user can start another activity from the TabScreen and when this activity is "active" I want the notification to bring the user to the new activity and not the tabscreen activity. But when the notification is clicked it always goes to the Tab screen.
Is it possible to make sure the notification always directs the user to the most recent activity?
Answer: You could recreate the last activity that has been created by user, in response to notification beeing clicked.
in your pending activity, you could add an extra data to remmeber which activity to show :
<code>Intent notificationIntentRegState = new Intent( "showTabScreen" );
ComponentName cn = new ComponentName(context, TabScreenActivity.class);
notificationIntentRegState.setComponent(cn);
notificationIntentRegState.putExtra( CURRENT_ACTIVITY, getCurrentActivityId() );
</code>
where getCurrrentActivityID() returnin a constant that you use to identify the last activity launched.
And, in the onCreateMethod of your tabScreen, you could check the intent that you received and the extra param to launch that activity again in response to a click on notification
<code>@Override
public void onCreate( Bundle b )
{
     String action = getIntent().getAction();
     if( action != null && action.equals( "showTabScreen" )  )
     {
        int activityToShow = getIntent().getIntExtra( CURRENT_ACTIVITY, -1 );
        if( activityToShow != -1 )
        {
           switch( activityToShow )
           {
               case ACTIVITY_ID_ONE : startActivity( ActivityOne.class );
           }//switch
           startActivity();
        }//if
     }//if
}//met
</code>
With, of course, you tabScreen filtering the intent name "showTabScreen" in your manifest.xml file.
Regards,
 Stéphane
Comment: @Donal Rafferty Oh ! I finally understood your problem (I think) : when user push the HOME button, they go back to a brand new activity : a new instance of the activity that was launched before. It's the right activity class, but not the right instance. Is that it ?

If so, it's hope less : android controls which activity is kept in memory and which one has to be recreated. So, the best you can do is to save every param that you need to RECREATE the activity as it was, and not hope that android will have kept the last instance and display it again, as it will never happen.
Comment: I've tried this method however when I use it a new Activity gets started rather than the old one being brought back to the foreground
Comment: @Donal Rafferty you want showTabScreen to show up but not new ones ? So maybe you should have another intent action name (I mean both in manifest.xml) that explicitly launches nothing from showTabScreen...
Comment: I don't want the TabScreeen to show at all, there will be another activity active, this will be the last activity the user was interacting with, when the user presses home they will be able to get back into my app via notification. This notification currently returns to the Tabscreen but should return to the active activity and not the tabscreen.


VB.NET / SQL for deleting database rows in a MS Access database

Question: I want to delete all the contents of a MS Access table however I am not sure how to set up my SQL to do so.
So far I have found this online:
Dim SqlQuery As String = "DELETE * FROM QuestionResults WHERE Quizname = " & txtQuizName.Text & ";"

I have the connection to the database linked up due to my previous code, I am just unsure how to edit this code so that it deletes the contents of the table (i want it to delete every record, not the table itself)
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Public dataFile As String = "U:\My Documents\Visual Studio 2013\Projects\COMP4 Project\COMP4 Project\bin\Debug\QuizDatabase.accdb"

Public connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader

connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()

Comment: You don't need the `*`. Also use parameters otherwise you're open to SQL injection.
Comment: Those DBObject ought not be global objects; they are all meant to be created, used and disposed in the smallest scope possible (with a few exceptions)
Answer: Simply DELETE FROM QuestionResults without a WHERE clause will delete every row.
The alternative command TRUNCATE TABLE QuestionResults will be faster, however I don't know if Access/JET supports the TRUNCATE statement or not.
Note that you must not generate SQL using string concatenation. Your program will break if someone puts "Baba O'Reilly" into your txtQuizName textbox. Instead use parameters.
Answer: What Dai said. Also you do not need an OleDbDataReaderuse an OleDbCommand:

Represents an SQL statement or stored procedure to execute against a data source.

Example use:
Dim command As New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()


What to call the set of all sets of summands of a number?

Question: The number 3 can be summed by $1 + 1 + 1$ or $1 + 2$.
The set of all multisets of summands would be $\left\{\left\{1,1,1\right\},\left\{1,2\right\}\right\}$
Is there a general term for this kind of comprehensive set of possible decompositions?
Maybe no specific word for summands exists, but there might be a word for this concept for factors? E.g. 12 is 2×6, 2×3×2, 3×4, etc.
Comment: You may want to look at the notion of *partitions* in number theory.
Comment: @VivaanDaga thank you!
Answer: The partition function $p(n)$ counts the number of partitions $\lambda$ of $n$ (denoted by $\lambda\vdash n$), i.e. sequences $\lambda$ such that
$$
1\leq\lambda_1\leq\lambda_2\leq\ldots, \quad \sum_i\lambda_i=n.
$$
The ordinary generating function for $p(n)$ is $\prod_{k=1}^{\infty}\frac{1}{1-x^k}$, which is closely related to the modular discriminant or the Dedekind eta function.  Euler noted a nice recurrence (Euler's pentagonal number theorem), Hardy and Ramanujan applied the circle method to derive asymptotics, Ramanujan noted congruences, etc., etc.  This function has a long and storied history and will continue to intrigue mathematicians for years to come.  https://en.wikipedia.org/wiki/Partition_(number_theory)


How Do I insert Data in a table From the Model MVC?

Question: I have data coming into my Model, how do I setup to insert the data in a table?
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }

    public Info()
    {
        using (SqlConnection connect = new SqlConnection(connections))
        {
            string query = "Insert Into Personnel_Data (Name, StreetAddress, City, State, Zip, HomePhone, WorkPhone)" +
                "Values('" + Name + "','" + Address + "','" + City + "','" + State + "','" + Zip + "','" + ContactHPhone + "','" + ContactWPhone + "')";

            SqlCommand command = new SqlCommand(query, connect);
            connect.Open();
            command.ExecuteNonQuery();
        }
    }

The Name, Address, City, and so on is null when the query is being run.  How do I set this up?
Answer: Add parameters to your constructor or do the Insert from a non-constructor method after the constructor is called and the properties are set.
The code you provided is vulnerable to SQL injection, so you need to fix that as well.
Also, terminology wise, calling an insert a query is confusing.  A query is a select, which is not what you are doing.
You do not need a stored procedure or an ORM, using ADO.NET as you are using it is fine.  You may find that using an ORM reduces the amount of repetitive, error prone code that you have to write and maintain, but there are downsides to using ORMs.
Answer: You need to initialize your properties in constructor before you use it:
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string ContactHPhone { get;set; }
public string ContactWPhone { get;set; }

public Info(string name, string address, string city, string state, string zip, string contactHPhone, string contactWPhone)
{
    Name = name;
    Address = address;
    City = city;
    State = state;
    Zip = zip;
    ContactHPhone = contactHPhone;
    ContactWPhone = contactWPhone;
    using (SqlConnection connect = new SqlConnection(connections))
    {
        string query = "Insert Into Personnel_Data (Name, StreetAddress, City, State, Zip, HomePhone, WorkPhone)" +
            "Values('" + Name + "','" + Address + "','" + City + "','" + State + "','" + Zip + "','" + ContactHPhone + "','" + ContactWPhone + "')";

        SqlCommand command = new SqlCommand(query, connect);
        connect.Open();
        command.ExecuteNonQuery();
    }
}

Edited:
The better way is to use parameters in your SQL string:
using (SqlConnection connect = new SqlConnection(connections))
{
    string query = "Insert Into Personnel_Data (Name, StreetAddress, City, State, Zip, HomePhone, WorkPhone) Values(@name, @address, @city, @state, @zip, @contactHPhone, @contactWPhone)";

    SqlCommand command = new SqlCommand(query, connect);
    command.Parameters.AddWithValue("name", Name);
    command.Parameters.AddWithValue("address", Address);
    command.Parameters.AddWithValue("city", City);
    command.Parameters.AddWithValue("state", State);
    command.Parameters.AddWithValue("zip", Zip);
    command.Parameters.AddWithValue("contactHPhone", ContactHPhone);
    command.Parameters.AddWithValue("contactWPhone", ContactWPhone);
    connect.Open();
    command.ExecuteNonQuery();
}

Comment: I'd upvote this if not for the SQL injection problem still being there.  :)  Use SqlParameters instead.
Comment: Michael was right.  I was leaving myself vulnerable for insert attacks.
    command.Parameters.Add(new SqlParameter("name",name));
and so on
Answer: First of all use parametrized queries if you are going to stick to your present approach
My suggestion is to go for an ORM like NHibernate, that will ease out things a lot for you
Answer: This looks like code from the object you are trying to persist (your Model.)  The code to receive the update and commit the record will go in your Controller.  Please post the code from your Controller.
Also, I would strongly recommend you consider an ORM like LINQ to SQL or LINQ to Entities.  At least create a stored procedure- don't send raw SQL to the database.


Dot product with which polynomial gives evaluation at $x_0$?

Question: I thought of following situation/problem, and was surprised that the solution did not jump out at me. Fix a positive integer $n$ and let $V_n$ be the finite-dimensional vector space of all polynomials of degree $\leq n$ with real coefficents. Make $V_n$ into a inner product space with respect to
$$ \langle p,q \rangle = \int_{-1}^1 p(x) q(x) \ dx.$$
Now, fix some point $x_0 \in \mathbb{R}$ and consider the linear functional
\begin{align*}
\varphi_{x_0} : V_n \to \mathbb{R} && \varphi_{x_0}(p) = p(x_0).
\end{align*}
Because we are in an inner product space, there is a unique polynomial $p_{x_0,n}$ such that
\begin{align*}
\varphi_{x_0}(p) = \langle p_{x_0,n},p \rangle =\int_{-1}^1 p_{x_0,n}(x) p(x) \ dx &&
\forall p \in V_n.
\end{align*}
Question: What is this polynomial!?
One approach would be to apply the Gramm-Schmidt procedure to $1,x,\ldots,x^n$ to get an orthonormal basis $p_0,p_1,\ldots,p_n$ for $V_n$ and then calculate $\varphi_{x_0}$ on this basis. The required vector should be then $\sum_{i=0}^n \varphi_{x_0}(p_i) p_i$, but I am hoping for a more enlightening representation.
Comment: Doesn't seem to be nice. The reproducing kernel is $k_n(x,y)=\sum_{k=0}^n \frac{2k+1}{2}P_k(x)P_k(y)$, where $P_k$ are the Legendre polynomials. I calculated a few: $k_1(x,y)=\frac{1+3xy}{2}$, $k_2(x)=\frac98+\frac32xy+\frac{15}{8}(x^2+y^2)+\frac{45}{8}x^2y^2$... no enlightement here. But then again, we shouldn't expect a nicer form for a reproducing kernel than one for an orthonormal basis. A search brought up [this book](https://books.google.com/books?id=9zgDCAAAQBAJ), section 8.3 (pp 94-) discusses such kernels a bit.
Comment: If anyone's interested in seeing what such polynomials look like, I [posted some pictures here](http://calculus7.org/2015/10/27/polynomial-delta-function/).
Comment: You seem to be looking for the delta "function" in that vector space. Wont be a finite linear combination of polynomials, safe to say.
Comment: @Macavity: Note I am only asking for $\int_{-1}^1 p_{x_0,n} (x) p(x) \ dx = p(x_0)$ when $p$ is a polynomial of degree $\leq n$.
Comment: There's a chance that $k_n(x,0)$ can have a nicer form; it's a certain alternating weighted sum of the Legendre polynomials of even degrees...
Comment: @MikeF Why do you say that _"vector space of all polynomials of degree $\,\leq n\,$ with real coefficients"_ is finite-dimensional?
Comment: @Vlad: Because it is? Think of the basis $\{1, x, x^2, \dots, x^n\}$. Do you have anything against it?
Comment: @AlexM. Oh, never mind, I did not read carefully the part I quoted. My bad, I apologize for my stupid question.
Answer: This will be not a very nice and effective answer but gives a more or less direct formula for the polynomial $\varphi_{x_0}$.
We will repeat the proof for Rodriguez's formula for the Legendre polynomials.
Let $q_0,q_1,q_2,\ldots,q_{n+1}$ be the sequence of polynomials such that
$$
q_0 = \varphi_{x_0}; \qquad
q_{k+1}' = q_k \quad\text{and}\quad q_{k+1}(-1)=0 \quad (k=0,1,\ldots,n).
$$
We will compute the polynomial $q_{n+1}$.
The condition, applied to the polynomial $(1-x)^k$ (with $0\le k\le n$) yields
$$
\int_{-1}^1 \varphi_{x_0}(x) \cdot (1-x)^k dx = (1-x_0)^k.
$$
Integrating by parts $k$ times,
\begin{align*}
(1-x_0)^k
&= \int_{-1}^1 q_0(x) \cdot (1-x)^k dx
= \underbrace{\Big[q_1(x) \cdot (1-x)^k\Big]_{-1}^1}_0
+ \int_{-1}^1 q_1(x) \cdot k(1-x)^{k-1} dx = \\
&= k\int_{-1}^1 q_1(x) \cdot (1-x)^{k-1} dx
= k(k-1)\int_{-1}^1 q_2(x) \cdot (1-x)^{k-2} dx = \dots = \\
&= k! \int_{-1}^1 q_k(x) dx
= k! \cdot q_{k+1}(1)
= k! \cdot q_{n+1}^{(n-k)}(1).
\end{align*}
Therefore,
$$
q_{n+1}^{(n-k)}(1) = \frac{(1-x_0)^k}{k!}.
$$
The $n$th Taylor-polynomial of $q_{n+1}$ around $1$ is
$$
\sum_{k=0}^n \frac{q_{n+1}^{(n-k)}(1)}{(n-k)!}(x-1)^{n-k} =
\sum_{k=0}^n \frac{(1-x_0)^k}{k!}(x-1)^{n-k} = \\ =
\frac1{n!} \sum_{k=0}^n \binom{n}{k}(1-x_0)^k(x-1)^{n-k} =
\frac{(x-x_0)^n}{n!}
$$
so
$$
q_{n+1}(x) \equiv \frac{(x-x_0)^n}{n!} \pmod{(x-1)^{n+1}}. \tag1
$$
By the condition $q_1(-1)=q_2(-1)=\ldots=q_{n+1}(-1)=0$ we know that
$$
q_{n+1}(x) \equiv 0 \pmod{(x+1)^{n+1}}. \tag2
$$
Since $\deg q_{n+1}\le 2n+1$, by the Chinese Remainder Theorem, the congruences (1) and (2) uniquely determine $q_{n+1}$.
A solution of the congruences (1) and (2), but with higher degree is
$$
\left(\bigg(\frac{x-1}2\bigg)^{n+1}-(-1)^{n+1}\right)^{n+1} \cdot \frac{(x-x_0)^n}{n!}.
$$
Dividing with remainders, we can see that
$$
q_{n+1}(x) = \left(\bigg(\frac{x-1}2\bigg)^{n+1}+(-1)^n\right)^{n+1} \cdot \frac{(x-x_0)^n}{n!} \mod (1-x^2)^{n+1}
$$
and therefore
$$
\varphi_{x_0}(x) =
\left(
\left(\bigg(\frac{x-1}2\bigg)^{n+1}+(-1)^n\right)^{n+1} \cdot \frac{(x-x_0)^n}{n!} \mod (1-x^2)^{n+1}\right)^{(n+1)} .
$$


Qual a utilidade do Func

Question: Estava pesquisando algumas coisas e me deparei com o Func<T, TResult>, e não entendi muito bem a utilidade dele.
Por exemplo:
//Método
public string Nome(string nome)
{
    return "Meu nome é " + nome
}

//Ao utiliza-lo eu chamaria assim
string nome = Nome("Josias");

E utilizando o Func<T, TResult>:
Func<string, string> metodo = Nome;

string nome = metodo("Josias");

Não consegui perceber nenhuma diferença em usar o Func<T, TResult>.
Em que casos seria útil utilizar o Func<T, TResult>?
Answer: Qual a utilidade
Passar para um método (ou uma função) uma outra função. É um tipo de delegate.
Como ler Func<T, TResult>

Função com um argumento do tipo T que devolve um valor do tipo TResult.

Não consegui perceber nenhuma diferença em usar o Func<T, TResult>.
Na verdade você não passou função alguma para uma variável usada em outra função. Apenas chamou a variável com o argumento. Por isso a utilidade não é bem percebida.
Em que casos seria útil utilizar o Func<T, TResult>?
A resposta do dcastro tem um bom exemplo. Vou colocar outro baseado no dele:
IEnumerable<int> AplicarOperacaoMatematicaEmLista(IEnumerable<int> lista, Func<int, int> funcao)
{
    foreach (var item in lista)
        yield return funcao(item);
}

Uso:
var potenciaDeDois = delegate(int numero) { return numero * numero; };
var listaDeInteiros = new List<int> { 2, 4, 6, 8, 10 };
var listaDeQuadrados = AplicarOperacaoMatematicaEmLista(listaDeInteiros, potenciaDeDois);
// Vai imprimir uma lista com { 4, 16, 36, 64, 100 }

Answer: Imagina que estas a escrever um metodo que transforma cada elemento duma lista num outro elemento. Queres que esta transformacao seja arbitraria, e definida pelo utilizador. Isto seria implementado assim:
IEnumerable<TResult> Map<T, TResult>(IEnumerable<T> collection, Func<T, TResult> transform)
{
    foreach(var item in collection)
        yield return transform(item);
}

Assim, o utilizador poderá passar como argumento qualquer função que receba um dos elementos da lista (de tipo T) como argumento e que o transforme num outro elemento (de tipo TResult).
var list = new List<int> {1,2,3};
var doubled = Map(list, item => item * 2);

Moral da história: Func<T, TResult> (e qualquer outro delegate em geral) serve para passares funções arbitrárias. Serve para poderes tratar funções como objectos/valores (este é o pilar do paradigma FP - functional programming).
Este método que usei como exemplo (Map) é na verdade idêntico à extensão Enumerable.Select. Aliás, as extensões LINQ dependem fortemente na passagem de delegates como argumentos (Where, Any, All, GroupBy, OrderBy, SelectMany, SkipWhile, etc).
Comment: É bom deixar claro também que `Func<>` assim como os outros `delegate`s genéricos disponibilizados na .NET servem como conveniência para facilitar a vida do programador. Não precisariam existir, mas são atalhos de programação genérica para não precisar declarar um `delegate` novo toda vez que um for necessário. Ou seja, é parte da utilidade do mesmo simplificar a declaração de um tipo de `delegate`s.
Answer: Func é um delegate (um "ponteiro" para uma função).
Neste caso, qualquer método que receba uma string como parâmetro e retorno uma string poderá ser utilizado.
aproveite para estudar Action e Predicate também:
https://stackoverflow.com/questions/4317479/func-vs-action-vs-predicate
Comment: A pergunta não é "o que é o `Func`?", mas sim "Qual a sua  utilidade?"

Qual a utilidade do Func


Add a sequence column in a query

Question: I have a query like below
select ref_leger_code,rate,sum(balance),to_char(due_date,'yyyymm')
from tbl_value_temp
group by ref_leger_code,rate,to_char(due_date,'yyyymm');

and the output is:

but I want to change the query that give me the output like below:
Comment: What determines the sequence reset? 'rate` alone? Or `rate_ledger_code, rate`? Or something else? Please provide us with the business rules you want to implement instead of expecting us to reverse engineer them from your output.
Answer: I suspect that you are looking about numbering the rows based on the rate so use an analytic function like this :
 select ref_leger_code, rate, sumbalance, due_date,
        ROW_NUMBER() OVER (PARTITION BY rate ORDER BY due_date asc ) AS sequence
 from   (
          select ref_leger_code, rate, sum(balance) sumbalance, to_char(due_date,'yyyymm') due_date
          from   tbl_value_temp
          group by ref_leger_code, rate, to_char(due_date,'yyyymm')
        );

Comment: It gives error: ORA-00924: missing BY keyword
00924. 00000 -  "missing BY keyword"
*Cause:
*Action:
Error at Line: 11 Column: 35
Comment: @navidsedigh - Dypso missed the BY after the PARTITION keyword. I have corrected their code, please try it now.

Add a sequence column in a query


Joined query, with group by and sub count based on a column

Question: I have a table called products, my query retrieves distinct and grouped rows from it, grouped by product_type_id.
This is the query, and it works
SELECT p.*, count(p.id) as count, pt.name from products p
LEFT JOIN product_types pt on pt.id = p.product_type_id
where client_id = 777
group by product_type_id

However, it's not enough and i want a sub-count by the activated column (Boolean type) and the NOT-Activated column.
I'd like to get for each row, a sub-count of the products that are set as true, and those which are set as false. I'd like to get them as another column in the relevant row.
is it possible?
Comment: Sample data would help convey what you are doing.
Comment: @GordonLinoff hi, i can't see how it will help.. (i will add some now anyway)
Answer: If you want a separate column with the count of activated, then you can use conditional aggregation:
select p.*, count(p.id) as count, pt.name,
       SUM(activated) as numActivated,
       (COUNT(*) - SUM(activated)) as numNotActivated
from products p left join
     product_types pt
     on pt.id = p.product_type_id
where client_id = 777
group by product_type_id;

MySQL treats booleans as integers in a numeric context, with 1 for true and 0 for false.  So, you can just add the values to get the count.
EDIT:
If you want separate rows, then include it in the GROUP BY:
select p.*, activated, count(p.id) as count, pt.name
from products p left join
     product_types pt
     on pt.id = p.product_type_id
where client_id = 777
group by product_type_id, activated;

Comment: thanks. I don't understand how to get the "not activated" , since the sum is 0 ... (o/c in the php i can to the math, but can it be done with SQL?)
(Now i saw that i asked only for the activated, sorry)
Answer: If you are using a BIT column type you may need to cast this into an integer.
I would suggest a CASE select statement, or a subselect.
ie,
Activated
sum(CAST(activated as INT)) as TotalActivated

or
(select sum(CAST(activated as INT)) FROM products WHERE product_type_id = p.product_type_id) as TotalActivated

Not activated
sum(case when activated = 1 then 0 else 1 end) as NotActivated

or
(select sum(case when activated = 1 then 0 else 1 end) FROM products WHERE product_type_id = p.product_type_id) as NotActivated


Saving Fractions in C

Question: so I am quite a beginner here in C and I am constructing a program that will find the roots of polynomial. I am tasked to print out the roots in fractions and whole number. But I really have no idea how to do it. I tried float but basically its for decimals, while the int doesn't print out anything other than the whole numbers. I hope you can help me.
I included the code I have written so far.
int last;
    int n=0;
    int lastfactor_arr[20];
    for(last=1; last<=input[token_counter-1]; last++)
    {
        if(input[token_counter-1]%last == 0)
            {
            lastfactor_arr[n] = last;
            printf("factors are: %d\n", lastfactor_arr[n]);
            n++;
            lastfactor_arr[n] = last * -1;
            printf("last factors are: %d\n", lastfactor_arr[n]);
            n++;
            }
    }
    printf("Total number of factors are: %d\n", n);

    int roots_arr[20];
    int answer;
    int root;
    int k, j, f=0;
    int s_root;
    int nume, deno;

    for(k=0; k<=m-1; k++) //LOOP FOR FIRST FACTOR
    {
        for(j=0; j<=n-1; j++) //LOOP FOR LAST FACTOR
        {
        answer = firstfactor_arr[k]/lastfactor_arr[j];
        if(answer==0)
            {
        nume = firstfactor_arr[k];
        deno = lastfactor_arr[j];
        s_root = (input[token_counter-1]*(nume/deno*nume/deno)) + (input[token_counter-2]*nume/deno) + input[0];
            if(s_root == 0)
                {
            roots_arr[f] = nume/deno;
            f++;
                }
            }
        else
            {
        root = (input[token_counter-1]*(answer*answer)) + (input[token_counter-2]*answer) + input[0];
            if(root == 0)
                {
            roots_arr[f] = answer;
            f++;
                }
            }
        }
    }
    int p;
    printf("The rational roots of the input polynomial are: ");
    for(p=0; p<=f; p++)
    {
    printf("%.d,", roots_arr[p]);
    }

Answer: You want either div_t or ldiv_t in <stdlib.h>.  See the documentation of the div() standard library function.  You can call this to get the quotient and remainder of your division with something like:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  static const int n = 10, d = 7;
  const div_t result = div(n, d);
  const double x = n/(double)d;

  printf("%f = %d %d/%d\n",
         x, result.quot, result.rem, d);

  return EXIT_SUCCESS;
}

An alternative is to replace result.quot with n/d and result.rem with n%d.  This lets you take out the line declaring result, which you no longer need.
Comment: The functions might well be helpful, but they're not essential (there's a `%` and a `/` operator that also work).   But you've not done very much explanation of how they might be used.
Comment: As an FYI, I checked all combinations of ±243 and ±42 with both `div()` and `/` and `%`, and I got the same result for each inputs with the function and the operators (±5 and ±33).  This was compiling with GCC 5.2.0 on Mac OS X 10.10.5, and also with clang (Apple LLVM version 7.0.0 (clang-700.0.72)) from XCode 7.  I think that's required by C99 and C11; things may have changed compared with C89/C90.
Comment: Those might not work exactly as expected for negative numbers.
Comment: Ah.  Yes, that became mandatory in C99 and C++03.  So the OP could replace `result.quot` with `n/d` and `result.rem` with `n%d` in my example.

Saving Fractions in C


Difference between using train_test_split and cross_val_score in sklearn.cross_validation

Question: I have a matrix with 20 columns. The last column are 0/1 labels.
The link to the data is here.
I am trying to run random forest on the dataset, using cross validation. I use two methods of doing this:

using sklearn.cross_validation.cross_val_score
using sklearn.cross_validation.train_test_split

I am getting different results when I do what I think is pretty much the same exact thing. To exemplify, I run a two-fold cross validation using the two methods above, as in the code below.
import csv
import numpy as np
import pandas as pd
from sklearn import ensemble
from sklearn.metrics import roc_auc_score
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import cross_val_score

#read in the data
data = pd.read_csv('data_so.csv', header=None)
X = data.iloc[:,0:18]
y = data.iloc[:,19]

depth = 5
maxFeat = 3

result = cross_val_score(ensemble.RandomForestClassifier(n_estimators=1000, max_depth=depth, max_features=maxFeat, oob_score=False), X, y, scoring='roc_auc', cv=2)

result
# result is now something like array([ 0.66773295,  0.58824739])

xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.50)

RFModel = ensemble.RandomForestClassifier(n_estimators=1000, max_depth=depth, max_features=maxFeat, oob_score=False)
RFModel.fit(xtrain,ytrain)
prediction = RFModel.predict_proba(xtest)
auc = roc_auc_score(ytest, prediction[:,1:2])
print auc    #something like 0.83

RFModel.fit(xtest,ytest)
prediction = RFModel.predict_proba(xtrain)
auc = roc_auc_score(ytrain, prediction[:,1:2])
print auc    #also something like 0.83

My question is:
why am I getting different results, ie, why is the AUC (the metric I am using) higher when I use train_test_split?
Note:
When I using more folds (say 10 folds), there appears to be some kind of pattern in my results, with the first calculation always giving me the highest AUC.
In the case of the two-fold cross validation in the example above, the first AUC is always higher than the second one; it's always something like 0.70 and 0.58.
Thanks for your help!
Comment: is your data randomized initially? If I remember right, one or both of the two methods default to splitting the data with no randomization.  That might explain the "pattern" you refer to, though it probably wouldn't explain the poorer overall results with the first method (it might though)
Comment: No, the data is not randomized initially. It does seem to be a good explanation for why the results exhibit the same pattern in cross_val_score. I guess the only random part of cross_val_score in my case is the fact that the randomForestClassifier has some randomness in its algorithm for choosing features in its trees. Other than that , if it's just cutting up the data into n folds based on the initial ordering, then maybe that's the problem. I'll check it out in a few hours when I actuallly wake up, it's the middle of the night here!
Comment: so, yeah, this worked:
    p = np.random.permutation(len(y))

    Result = cross_val_score(ensemble.RandomForestClassifier(n_estimators=1000, max_depth=5, max_features=3, oob_score=False), X[p], y[p], scoring='roc_auc', cv=2)
Answer: When using cross_val_score, you'll frequently want to use a KFolds or StratifiedKFolds iterator:
http://scikit-learn.org/0.10/modules/cross_validation.html#computing-cross-validated-metrics
http://scikit-learn.org/0.10/modules/generated/sklearn.cross_validation.KFold.html#sklearn.cross_validation.KFold
By default, cross_val_score will not randomize your data, which can produce odd results like this if you're data isn't random to begin with.
The KFolds iterator has a random state parameter:
http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.KFold.html
So does train_test_split, which does randomize by default:
http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html
Patterns like what you described are usually a result of a lack of randomnesss in the train/test set.
Comment: I have a question on **train_test_split**. In the above code `xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.50)`, how does the algorithm know what value must go into `xtrain`, `xtest` etc? How does it know that `xtrain` must contain the result of _training the independent variables_ of the dataset, and similarly on `xtest`. I don't suppose it is the fact that the variable contains 'train', or 'test' in it. Is it? Thanks for your help.
Answer: The answer is what @KCzar pointed. Just want to note the easiest way I found to randomize data(X and y with the same index shuffling) is as following:
p = np.random.permutation(len(X))
X, y = X[p], y[p]

source: Better way to shuffle two numpy arrays in unison


Display a popup once in front page

Question: Does any one know a good module I can use to set a nice popup (supporting html) on the front_page when a user visit the website for the first time??
Answer: Zerolab is right! If disclamer module is not good for you, also try Splash (Splashify on D7)
Comment: thanks, I have just installed it and it's exactly what I needed
Answer: You could give the Disclaimer module a try. It is quite easy to setup and can be used on any page.
Comment: I had some trouble using Disclaimer but I have found another module in Disclaimer related project and I used [it](http://drupal.org/project/splash), it works fine, thanks :)
Comment: glad you found a good solution ;)
Answer: Another minimal candidate is Tinybox
It is stripped down to the essential basics. Still it allows to choose which content type to display (node ID, Content Type or Views).

Display a popup once in front page


On AWS, how to filter which services are using a role?

Question: On AWS, I want to review all permissions grant or revoked to our services and redefine them when necessary.
Considering a specific role set on AWS IAM.
How can I filter which services, instances or lambda functions assumed this role?
I tried to filter, for example, Lambda functions under this role, but didn't found how I can do this.
Comment: Could you please clarify what you are seeking? Are you wanting to know entity _can_ assume a role, or which entity historically _did_ assume a role?
Answer: There is the CloudTrail service to

log, continuously monitor, and retain account activity related to actions across your AWS infrastructure

That should give you an overview which entities assumed which role.
There are also some potentially useful cli commands:
The list-entities-for-policy operation

Lists all IAM users, groups, and roles that the specified managed policy is attached to.

The get-service-last-accessed-details-with-entities operation returns a

list of entities that could have used group or policy permissions to access the specified service

But CloudTrail is the standard governance service.


Como usar um setBackground de seleção em renderer personalizado?

Question: Eu estou tentando usar um cell render, para que quando mostrar dados monetários, ela faça a formatação. Porém, quando aplico o render em determinada coluna, o foco nessa coluna não possui o background do restante da linha.
Para resolver isso, pensei em fazer o mesmo que fiz na minha AbstractTable, criar um método que mude a cor da linha selecionada, assim ela acaba pegando em todo a linha. Porém, por ser Default, não consegui fazer da mesma forma. Então se alguém souber uma maneira de aplicar o render que não "bug" ou que saiba como setar a cor.
Para ilustrar o problema:

Na minha abstract, eu faço assim:
private JTable tabela = new JTable(jtmCompra)
{
    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int linha, int coluna)
    {
        Component componente = super.prepareRenderer(renderer, linha,                  coluna);

        if (isRowSelected(linha))//Focu na linha.
            {

                componente.setBackground(new Color(147, 200, 255, 255));

            }
     }
}

Dai como "pinta linha" fica certo.

Exemplo simples:
Tela Sistema:
package telas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class TelaSistema extends JFrame implements ActionListener
{

    public static JDesktopPane jdp = new JDesktopPane();
    public JMenuBar jmb = new JMenuBar();
    public JMenu jmCadastros = new JMenu("Cadastros");
    public JMenuItem jmiE = new JMenuItem("Uma tela qualquer");

    public TelaSistema()
    {
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Sistema");
        getContentPane().add(jdp);
        setJMenuBar(jmb);
        jmb.add(jmCadastros);
        adicionaJMenuItem(jmCadastros, jmiE);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void adicionaJMenuItem(JMenu menu, JMenuItem item)
    {
        menu.add(item);
        item.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {
        if (ae.getSource() == jmiE)
        {
            TelaCadastroA a = new TelaCadastroA();
            jdp.add(a);
        }
    }

    public static void main(String args[])
    {
       TelaSistema telaSistema = new TelaSistema();
    }
}

Tela: Cadastro
package telas;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

public class TelaCadastroA extends JInternalFrame implements ActionListener
{
      public JButton jbConsultar = new JButton("Consultar");
      public JPanel jpBotoes = new JPanel();

    public TelaCadastroA()
    {
        super("");
        adicionaBotao(jbConsultar);
        setSize(500, 500);
        getContentPane().add("South", jpBotoes);
        jpBotoes.setLayout(new GridLayout(1, 1));
        Dimension tamanhoTela = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((tamanhoTela.width - getWidth()) / 2, ((tamanhoTela.height - getHeight())) / 2);
        setVisible(true);
    }

    private void adicionaBotao(JButton botao) {
        jpBotoes.add(botao);
        botao.addActionListener(this);
    }

      @Override
    public void actionPerformed(ActionEvent ae)
    {
        if (ae.getSource() == jbConsultar)
        {
            consultar();
        }
    }

    public void consultar()
    {
        TelaConsultar.getTela("Consulta",  new String[]
        {
            "Código", "A", "B", "C"
        }, new DefaultTableCellRenderer[] {null, null,  new CellRenderMonetario(), null}, this);
    }

    class CellRenderMonetario extends DefaultTableCellRenderer
    {
        private DecimalFormat df = new DecimalFormat(",##0.00");

        @Override
        public Component getTableCellRendererComponent(JTable tabela, Object valor, boolean isSelected, boolean temFocu, int linha, int coluna)
        {
            if (valor == null)
            {
                valor = 0;
            }

            if (valor instanceof String)
            {
                setText(df.format(Double.parseDouble((String) valor)) + " ");
            }

            else
            {
                setText(df.format(valor) + " ");
            }
            setHorizontalAlignment(SwingConstants.RIGHT);
            return this;
        }
    }
}

Tela Coonsulta:
package telas;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class TelaConsultar extends JInternalFrame implements InternalFrameListener, MouseListener {

    private static TelaConsultar telaConsultar = null;
    private String sql;
    private String[] titulos;
    private TelaCadastroA tela;
    private JTable tabela;
    private JScrollPane jsp;
    private DefaultTableModel dtm = new DefaultTableModel();
    private String proc;

    public TelaConsultar(String tituloJanela, String[] titulos, DefaultTableCellRenderer[] renderizadores, TelaCadastroA tela)
    {
        super(tituloJanela, true, true, false, false);
        this.sql = sql;
        this.titulos = titulos;
        this.tela = tela;
        tabela = new JTable()
        {
            @Override
            public boolean isCellEditable(int linha, int coluna)
            {
                return false;//Esta tabela não pode ser editada pois é uma consulta
            }
        };
        tabela.setModel(dtm); //Define o modelo da tabela
        tabela.getTableHeader().setReorderingAllowed(false);
        for (int i = 0; i < titulos.length; i++)
        {
            dtm.addColumn(titulos[i]);
        }
        jsp = new JScrollPane(tabela);
        getContentPane().add(jsp);
        preencher();
        //pack();
        setSize(650, 400);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
        centralizaTelaConsulta();
        setVisible(true);
        tabela.addMouseListener(this);
        addInternalFrameListener(this);

        TableColumnModel tableModel = tabela.getColumnModel();
        for (int i = 0; i < titulos.length; i++)
        {
            tableModel.getColumn(i).setMinWidth(70);
        }

        for (int i = 0; i < tableModel.getColumnCount(); i++)
        {
            if (renderizadores[i] != null)
            {
                tableModel.getColumn(i).setCellRenderer(renderizadores[i]);
                /* if (isRowSelected(i))//Focu na linha.
                {

                }*/
            }

        }
    }

    public static void getTela(String tituloJanela, String[] titulos, DefaultTableCellRenderer[] renderizadores, TelaCadastroA tela)
    {
        if (telaConsultar == null)
        {
            telaConsultar = new TelaConsultar(tituloJanela, titulos, renderizadores, tela);
            TelaSistema.jdp.add(telaConsultar);
        }
        TelaSistema.jdp.setSelectedFrame(telaConsultar);
        TelaSistema.jdp.moveToFront(telaConsultar);
    }

    private void preencher()
    {
        for (int i = 0; i < 10; i++)
        {
            dtm.addRow(new Object[]{"" + i, "Brasil - " + i});
        }

    }

    public void centralizaTelaConsulta()
    {
        Dimension tamanhoTela = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((tamanhoTela.width - getWidth()) / 2, ((tamanhoTela.height - getHeight())) / 2);
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void internalFrameOpened(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosed(InternalFrameEvent e) {
        TelaSistema.jdp.remove(telaConsultar);
        telaConsultar = null;
    }

    @Override
    public void internalFrameIconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameActivated(InternalFrameEvent e) {

    }

    @Override
    public void internalFrameDeactivated(InternalFrameEvent e) {
    }

    @Override
    public void mouseClicked(MouseEvent me) {

    }
}

Comment: Mesmo o exemplo mais básico, eu acho que vou ter que postar um link pra baixar um .rar, tem problema? Vou tentar por o "menos possível" de coisas.
Comment: Quem renderiza são os CellRenderes, defaulttablemodel em nada influi nisso. Se possivel, adicione seu renderer e um  **[mcve]** para que o código seja testável.
Comment: Complica um pouco. Faça um exemplo com alguns dados de exemplo(sem conexão com banco).
Answer: Como você está modificando a forma como esta coluna renderiza, as definições padrões da tabela não são aplicadas, por isso o método getTableCellRendererComponent possui um parâmetro isSelected, para que você mesmo defina. No caso do seu código, a solução que encontrei foi checar se o campo estava selecionado, e copiar as definições de seleção padrões da tabela:
class CellRenderMonetario extends DefaultTableCellRenderer {

    private DecimalFormat df = new DecimalFormat(",##0.00");

    @Override
    public Component getTableCellRendererComponent(JTable tabela, Object valor, boolean isSelected, boolean temFocu, int linha, int coluna) {
        if (valor == null) {
            valor = 0;
        }
        if (isSelected) {
            setBackground(tabela.getSelectionBackground());
            setForeground(tabela.getSelectionForeground());
        } else {
            setBackground(tabela.getBackground());
            setForeground(tabela.getForeground());
        }

        if (valor instanceof String) {
            setText(df.format(Double.parseDouble((String) valor)) + " ");
        } else {
            setText(df.format(valor) + " ");
        }
        setHorizontalAlignment(SwingConstants.RIGHT);

        return this;
    }
}

Com isso, o campo seguirá o mesmo padrão de cores de seleção do restante da tabela.
Tem várias coisas que poderia ser melhorado nesse código, principalmente a questão de organização e de responsabilidades de classes e métodos, mas isso fugiria o escopo da pergunta.
Comment: Nossa, deu certinho. Não havia pensando em mecher no render. Muito obrigado.
Comment: Eu tenho uma dúvida, bem próxima a do tópico, porém eu devo abrir um novo, ou posto postar nos comentários ? É que eu fiz um render para data, que não esta muito certo.
Comment: @GustavoSantos Disponha :)
Comment: @GustavoSantos te respondi la no chat.


Radio button value not in $_POST

Question: I have a form with multiple controls, tey are all passed with $_POST and treated with PHP.
BUT, 2 fields doesn't get passed with $_POST. I used print_r ($_POST); and this field is not showing. The input is nouvellePropriete
Vous nous informez de ce changement d'adresse parce que:
<input type="radio" id="nouvellePropriete_1" name="nouvellePropriete" value="o" />
 vous avez acquis une nouvelle propriété (terrain, bâtiment) ?
<input type="radio" id="nouvellePropriete_2" name="nouvellePropriete" value="n" />
 vous souhaitez simplement changer votre adresse de correspondance ?

Here is the whole code for my form:

 Changement d'adresse

 Employés de la commission scolaire ou propriétaires

    <form name="AdrForm" id="AdrForm" method="post" action="traitement.php">

 Veuillez remplir ce formulaire pour nous faire part de votre changement d'adresse

        <fieldset class="login">
            <legend>Informations personnelles</legend>

                Prénom
                <input id="pnom" name="pnom" tabindex="1"/>

                Nom
                <input id="nom" name="nom" tabindex="2"/>

                Téléphone (pour vous joindre le jour)
                <input id="telephoneJour" name="telephoneJour" tabindex="3"/>

                Poste (optionel)
                <input style="width:50px;" id="posteTel" name="posteTel" tabindex="4"/>

                Courriel (optionel)
                <input id="courriel" name="courriel" tabindex="5"/>

        </fieldset>
        <fieldset class="contact">
            <legend>Adresse actuelle</legend>

                N° civique et rue
                <input id="adresseAct1" name="adresseAct1" tabindex="6"/>

                Ville
                <input id="villeAct" name="villeAct" tabindex="7"/>

                Code postal
                <input id="codePostalAct" name="codePostalAct" tabindex="8"/>

                Téléphone
                <input id="telephoneAct" name="telephoneAct" tabindex="9"/>

        </fieldset>
        <fieldset class="contact">
            <legend>Nouvelle adresse</legend>

                N° civique et rue
                <input id="adresseNew1" name="adresseNew1" tabindex="10"/>

                Ville
                <input id="villeNew" name="villeNew" tabindex="11"/>

                Code postal
                <input id="codePostalNew" name="codePostalNew" tabindex="12"/>

                Téléphone
                <input id="telephoneNew" name="telephoneNew" tabindex="13"/>

                Date d'entrée en vigueur de la nouvelle adresse
                <input style="width:100px;" id="dateNew" name="dateNew" type="textbox" tabindex="14"/>

        </fieldset>
        <fieldset>
            <legend>Statut</legend>

                Vous êtes employé de la Commission scolaire des Sommets?
                <input type="checkbox" id="employeCSS" name="employeCSS" onclick="CSSChecked()"/>

                    Numéro de matricule
                    <input id="matricule" style="visibility:hidden;" name="matricule"/>

                    Adresse courriel CSS
                    <input id="courrielCSS" style="visibility:hidden;" name="courrielCSS"/>

                Vous êtes propritéraire d'un ou de plusieurs immeubles situés sur notre territoire (MRC de Memphrémagog, MRC des Sources et MRC du Val-Saint-François) ?
                <input style="margin-top:1em;" type="checkbox" id="proprio" name="proprio" onclick="proprioChecked();" />

Vous nous informez de ce changement d'adresse parce que:

                    <input style="margin-left:15px;margin-top:1em;width:10px;" type="radio" id="nouvellePropriete_1" name="nouvellePropriete" value="o" />  vous avez acquis une nouvelle propriété (terrain, bâtiment) ?

                    <input style="margin-left:15px;width:10px;" type="radio" id="nouvellePropriete_2" name="nouvellePropriete" value="n" />  vous souhaitez simplement changer votre adresse de correspondance ?

                    Pour chaque immeuble dont vous êtes propriétaire, vous devez fournir le n° de matricule de l'immeuble pour lequel un compte de taxe scolaire est émis. Ce numéro de 23 chiffres se trouve en haut, à droite de votre compte de taxe scolaire. (ex. 45008-0000-00-0000-00000000)
 Inscrire un n° de matricule par ligne.

                    <textarea style="margin-bottom:15px;margin-top:5px;margin-left:300px;width:250px;visibility:hidden" id="numImmeuble" name="numImmeuble" rows="3" cols=""></textarea>

        </fieldset>

            Commentaire (optionel)
            <textarea id="commentaire" name="commentaire" class="" rows="3" cols=""></textarea>

                <a class="button" href="#" onclick="$('#dialog-nom').html($('input#nom').val());
                $('#dialog-pnom').html($('input#pnom').val());
                $('#dialog-pnom').html($('input#pnom').val());
                $('#dialog-adresseAct1').html($('input#adresseAct1').val());
                $('#dialog-villeAct').html($('input#villeAct').val());
                $('#dialog-codePostalAct').html($('input#codePostalAct').val());
                $('#dialog-telephoneAct').html($('input#telephoneAct').val());
                $('#dialog-adresseNew1').html($('input#adresseNew1').val());
                $('#dialog-villeNew').html($('input#villeNew').val());
                $('#dialog-codePostalNew').html($('input#codePostalNew').val());
                $('#dialog-telephoneNew').html($('input#telephoneNew').val());
                $('#dialog-dateNew').html($('input#dateNew').val());
                (document.getElementById('nouvellePropriete_1').checked) ? $('#dialog-nouvellePropriete_1').html('
Il s\'agit de l\'acquisition d\'une nouvelle propriété.
') : $('#dialog-nouvellePropriete_1').html('');
                (document.getElementById('nouvellePropriete_2').checked) ? $('#dialog-nouvellePropriete_2').html('
Il s\'agit simplement d\'un changement d\'adresse de correspondance.
') : $('#dialog-nouvellePropriete_2').html('');
                (document.getElementById('employeCSS').checked) ? $('#dialog-employeCSS').html('- au Service des ressources humaines.
') : $('#dialog-employeCSS').html('');
                (document.getElementById('proprio').checked) ? $('#dialog-proprio').html('- au Service de la taxe scolaire.
') : $('#dialog-proprio').html('');
                $('#dialog').dialog('open');" />
                Envoyer

 </form>

Any idea ?
Answer: This is kinda tricky. If the radio button is toggled, it appears in $_POST. If it isn't toggled, it does not get submitted and therefore isn't in $_POST. The same thing is true with checkboxes.
Comment: How to know if it's toggled ? Sorry, english not my first language.
Comment: If the first radio button from your form is toggled, it will be in $_POST and it's value will be 'o', if the second is toggled, the value will bee 'n', if none of them is toggled, it won't be in $_POST.
Comment: Oh, sorry, I get it. Well at first, none of them are toggled, but depending on what the user enters in another field, the radio button has a "required" validation. So when I checked the $_POST array for the value, the radio button has been checked and therefore should be there.
Comment: Required client-side or server-side validation?
Comment: I have both, jquery validation and php validation. Everything other fields get sent except this radio button (which my only radio button).
Thats weird? Isn't it ?
Comment: Ok, found it. I bypassed my submit fonction with JQuery to show a dialog confirmation. I forgot to add my new field in my $.post(action,

Thank you for your time cypher
Answer: Aside from what was already answered, I would recommend using 'checked="checked"' attribute on one of your radio buttons. That way you will be able to debug more easily. It is also HTML 4.01 and XHTML 1.0 compliant.

Radio button value not in $_POST


What is the asymptotic behaviour of the solution of an inhomogeneous linear ODE?

Question: This is probably a pretty easy question to someone working in the field of ODEs (which I generally do not), but nonetheless, I've haven't been able to find clear a answer in the textbooks I've looked in. Consider the ODE
$X'(t) = A + BX(t)$
with some initial condition $X(0)$. Here, A is a vector of dimension $n$, and $B$ is an $n\times n$ matrix. I know that this equation has a unique solution given by
$X(t) = \exp(tB)X(0) + \int_0^t \exp((t-s)B)A ds$
with $\exp(tB)$ denoting the matrix exponential. I also know that if all eigenvalues of $B$ have strictly negative real part, then $B$ is in particular invertible, and it holds that $X(t)$ converges to $-B^{-1}A$ as $t$ tends to infinity.
My question is this: What can be said about the limit of $X(t)$ when the eigenvalues of $B$ do not all have strictly negative real parts? Ideally, I would like to know about a criterion for which coordinates of $X(t)$ tend to infinity, minus infinity or a finite limit as a function of, say, the eigenvalues of $B$.
Answer: If matrix $B$ is invertible, then you can always make a substitution $Y=X+B^{-1}A$ for which you have
$$
\dot Y=BY.
$$
If there exist an eigenvalue $\lambda>0$ of $B$ then both $Y$ and $X$ tend to infinity. If all eigenvalues have negative real parts then $Y\to 0$ and $X\to -B^{-1}A$. If the origin is Lyapunov stable for $Y$ then the solutions for $X$ will stay bounded.
Comment: Thanks for the answer! Could you elaborate on a few things? First, in the case of the existence of a positive eigenvalue $\lambda$ (I assume that you mean an eigenvalue with positive real part), can you say something about which coordinates (or linear combinations of coordinates) will tend to infinity? And is it possible to say something about the non-invertible case, or the case where there exists an eigenvalue with zero real part?
Comment: Yes, if the real part is positive. Which coordinates will tend to infinity depend on the structure of $B$. If there are eigenvalues of the form $\pm \omega i$, then $\dot Y=BY$ is Lyaponov stable, hence the solutions for X are bounded. If $B$ is non-invertible, we have two cases: $BX=A$ has no solutions, in this case $X$ will tend to infinity, or has a linear manifold of solutions, which can be either attracting or repelling.


Como fazer uma consulta SQL (MySQL) com média e várias tabelas INNER?

Question: Tenho uma instrução SQL com 5 tabelas. Observe que nela faço até um cálculo de raio.
Preciso acrescentar uma nova tabela, de avaliações com:
cod_avaliacao   int(11)
cod_cliente
cod_fornecedor
avaliacao_geral decimal(10,0)
Onde o campo avaliacao_geral quero calcular a média de acordo com os fornecedores.
Já tentei LEFT JOIN, RIGHT JOIN porque existem fornecedores que não possuem nenhuma avaliação e se colocar INNER JOIN o resultado retorna vazio.
Também sei que tenho que utilizar algo parecido com isso nesta minha instrução SQL para retornar a média:
 SELECT
       cod_avaliacao,
       cod_cliente,
       cod_fornecedor,
       AVG(avaliacao_geral)
    FROM
       avaliacao
    GROUP BY cod_fornecedor

Meu SQL (Sem a tabela de avaliação):
    SELECT
   fornecedores.cod_fornecedor,
   fornecedores.fantasia,
   fornecedores.CPF,
   fornecedores.identidade,
   fornecedores.email,
   fornecedores.cep,
   fornecedores.logradourro,
   fornecedores.complemento,
   fornecedores.cidade,
   fornecedores.estado,
   fornecedores.responsavel_contato,
   fornecedores.telefone_empresa,
   fornecedores.telefone_responsavel,
   fornecedores.celular,
   fornecedores.bairro,
   fornecedores.numero,
   fornecedores.latitude,
   fornecedores.longitude,
   cadastra_oferta.cod_oferta,
   cadastra_oferta.cod_fornecedor,
   cadastra_oferta.cod_categoria_com,
   cadastra_oferta.titulo_promocao,
   cadastra_oferta.descricao,
   cadastra_oferta.foto,
   cadastra_oferta.valor_sem_desconto,
   cadastra_oferta.valor_com_desconto,
   cadastra_oferta.desconto,
   cadastra_oferta.validade_oferta,
   cadastra_oferta.igredientes,
   cadastra_oferta.qtd_estoque,
   categoria_comida.cod_categoria_com,
   categoria_comida.nome,
   categoria_comida.data_cadastro,
   fornecedor_credito.cod_fornecedor_codigo,
   fornecedor_credito.cod_fornecedor,
   fornecedor_credito.qtd_credito,
   fornecedor_configura_frete.cod_configura_frete,
   fornecedor_configura_frete.cod_fornecedor,
   fornecedor_configura_frete.tem_delivery,
   fornecedor_configura_frete.custo_padrao,
   fornecedor_configura_frete.frete_gratis,
   fornecedor_configura_frete.valor_minimo_frete_gratis,
   fornecedor_configura_frete.tipos_pagamentos,
   fornecedor_configura_frete.prazo_entrega_min,
   fornecedor_configura_frete.prazo_entrega_max,
   fornecedor_configura_frete.agenda_comida,
   fornecedor_configura_frete.dayw_one,
   fornecedor_configura_frete.dayw_two,
   fornecedor_configura_frete.dayw_three,
   fornecedor_configura_frete.dayw_four,
   fornecedor_configura_frete.dayw_five,
   fornecedor_configura_frete.dayw_six,
   fornecedor_configura_frete.dayw_seven,
   fornecedor_configura_frete.hour_ini_one,
   fornecedor_configura_frete.hour_end_one,
   fornecedor_configura_frete.hour_ini_two,
   fornecedor_configura_frete.hour_end_two,
   fornecedor_configura_frete.hour_ini_three,
   fornecedor_configura_frete.hour_end_three,
   fornecedor_configura_frete.hour_ini_four,
   fornecedor_configura_frete.hour_end_four,
   fornecedor_configura_frete.hour_ini_five,
   fornecedor_configura_frete.hour_end_five,
   fornecedor_configura_frete.hour_ini_six,
   fornecedor_configura_frete.hour_end_six,
   fornecedor_configura_frete.hour_ini_seven,
   fornecedor_configura_frete.hour_end_seven,
   fornecedor_visual.cod_fornecedor_visual,
   fornecedor_visual.cod_fornecedor,
   fornecedor_visual.descricao_empresa,
   fornecedor_visual.facebook,
   fornecedor_visual.localizacao_mapa,
   fornecedor_visual.logomarca,
   fornecedor_visual.data_cadastro,
   fornecedor_visual.latitude,
   fornecedor_visual.longitude,
   (6371 * acos(
        cos( radians('$latitude') )
        * cos( radians( fornecedores.latitude ) )
        * cos( radians( fornecedores.longitude ) - radians('$longitude') )
        + sin( radians('$latitude') )
        * sin( radians( fornecedores.latitude ) )
        )
    ) AS distancia

FROM
   fornecedores INNER JOIN cadastra_oferta ON fornecedores.cod_fornecedor = cadastra_oferta.cod_fornecedor
   INNER JOIN categoria_comida ON cadastra_oferta.cod_categoria_com = categoria_comida.cod_categoria_com
   INNER JOIN fornecedor_credito ON fornecedores.cod_fornecedor = fornecedor_credito.cod_fornecedor
   INNER JOIN fornecedor_configura_frete ON fornecedores.cod_fornecedor = fornecedor_configura_frete.cod_fornecedor
   INNER JOIN fornecedor_visual ON fornecedores.cod_fornecedor = fornecedor_visual.cod_fornecedor
WHERE
   (fornecedor_credito.qtd_credito >= '1') AND
   (cadastra_oferta.qtd_estoque >= '1')  AND
   (cadastra_oferta.validade_oferta >= NOW())
HAVING distancia <= '$raio'
ORDER BY
   cadastra_oferta.titulo_promocao ASC

Agora meu PHP inteiro para entenderem, é um JSON:
<?php

header('Content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

/** CONFIG:START **/
$config["host"]         = "" ;      //host
$config["user"]         = "" ;      //Username SQL
$config["pass"]         = "" ;      //Password SQL
$config["dbase"]        = "" ;      //Database
$config["limit"]        = 500 ;         //limit row
$config["abs_url_images"]       = "http://" ;       //Absolute Images URL
$config["abs_url_images"]       = "http://v" ;      //Absolute Images URL
$config["abs_url_logo"]         = "/admin/vovos/_lib/file/img/app_logo" ;       //Absolute Videos URL
$config["abs_url_logo"]         = admin/vovos/_lib/file/img/app_logo" ;         //Absolute Audio URL
/** CONFIG:END **/

$data_atual = date("d-m-Y");

$rest_api = array();
function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
}

/** connect to mysql **/
$mysql = new mysqli($config["host"], $config["user"], $config["pass"], $config["dbase"]);
if (mysqli_connect_errno()){
    die(mysqli_connect_error());
}

if(!isset($_GET["json"])){

    $_GET["json"]= "route";

}

$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
$raio = $_GET['raio'];

switch($_GET["json"]){
    case "promocao":
        $sql = "SELECT
   fornecedores.cod_fornecedor,
   fornecedores.fantasia,
   fornecedores.CPF,
   fornecedores.identidade,
   fornecedores.email,
   fornecedores.cep,
   fornecedores.logradourro,
   fornecedores.complemento,
   fornecedores.cidade,
   fornecedores.estado,
   fornecedores.responsavel_contato,
   fornecedores.telefone_empresa,
   fornecedores.telefone_responsavel,
   fornecedores.celular,
   fornecedores.bairro,
   fornecedores.numero,
   fornecedores.latitude,
   fornecedores.longitude,
   cadastra_oferta.cod_oferta,
   cadastra_oferta.cod_fornecedor,
   cadastra_oferta.cod_categoria_com,
   cadastra_oferta.titulo_promocao,
   cadastra_oferta.descricao,
   cadastra_oferta.foto,
   cadastra_oferta.valor_sem_desconto,
   cadastra_oferta.valor_com_desconto,
   cadastra_oferta.desconto,
   cadastra_oferta.validade_oferta,
   cadastra_oferta.igredientes,
   cadastra_oferta.qtd_estoque,
   categoria_comida.cod_categoria_com,
   categoria_comida.nome,
   categoria_comida.data_cadastro,
   fornecedor_credito.cod_fornecedor_codigo,
   fornecedor_credito.cod_fornecedor,
   fornecedor_credito.qtd_credito,
   fornecedor_configura_frete.cod_configura_frete,
   fornecedor_configura_frete.cod_fornecedor,
   fornecedor_configura_frete.tem_delivery,
   fornecedor_configura_frete.custo_padrao,
   fornecedor_configura_frete.frete_gratis,
   fornecedor_configura_frete.valor_minimo_frete_gratis,
   fornecedor_configura_frete.tipos_pagamentos,
   fornecedor_configura_frete.prazo_entrega_min,
   fornecedor_configura_frete.prazo_entrega_max,
   fornecedor_configura_frete.agenda_comida,
   fornecedor_configura_frete.dayw_one,
   fornecedor_configura_frete.dayw_two,
   fornecedor_configura_frete.dayw_three,
   fornecedor_configura_frete.dayw_four,
   fornecedor_configura_frete.dayw_five,
   fornecedor_configura_frete.dayw_six,
   fornecedor_configura_frete.dayw_seven,
   fornecedor_configura_frete.hour_ini_one,
   fornecedor_configura_frete.hour_end_one,
   fornecedor_configura_frete.hour_ini_two,
   fornecedor_configura_frete.hour_end_two,
   fornecedor_configura_frete.hour_ini_three,
   fornecedor_configura_frete.hour_end_three,
   fornecedor_configura_frete.hour_ini_four,
   fornecedor_configura_frete.hour_end_four,
   fornecedor_configura_frete.hour_ini_five,
   fornecedor_configura_frete.hour_end_five,
   fornecedor_configura_frete.hour_ini_six,
   fornecedor_configura_frete.hour_end_six,
   fornecedor_configura_frete.hour_ini_seven,
   fornecedor_configura_frete.hour_end_seven,
   fornecedor_visual.cod_fornecedor_visual,
   fornecedor_visual.cod_fornecedor,
   fornecedor_visual.descricao_empresa,
   fornecedor_visual.facebook,
   fornecedor_visual.localizacao_mapa,
   fornecedor_visual.logomarca,
   fornecedor_visual.data_cadastro,
   fornecedor_visual.latitude,
   fornecedor_visual.longitude,
   (6371 * acos(
        cos( radians('$latitude') )
        * cos( radians( fornecedores.latitude ) )
        * cos( radians( fornecedores.longitude ) - radians('$longitude') )
        + sin( radians('$latitude') )
        * sin( radians( fornecedores.latitude ) )
        )
    ) AS distancia

FROM
   fornecedores INNER JOIN cadastra_oferta ON fornecedores.cod_fornecedor = cadastra_oferta.cod_fornecedor
   INNER JOIN categoria_comida ON cadastra_oferta.cod_categoria_com = categoria_comida.cod_categoria_com
   INNER JOIN fornecedor_credito ON fornecedores.cod_fornecedor = fornecedor_credito.cod_fornecedor
   INNER JOIN fornecedor_configura_frete ON fornecedores.cod_fornecedor = fornecedor_configura_frete.cod_fornecedor
   INNER JOIN fornecedor_visual ON fornecedores.cod_fornecedor = fornecedor_visual.cod_fornecedor
WHERE
   (fornecedor_credito.qtd_credito >= '1') AND
   (cadastra_oferta.qtd_estoque >= '1')  AND
   (cadastra_oferta.validade_oferta >= NOW())
HAVING distancia <= '$raio'
ORDER BY
   cadastra_oferta.titulo_promocao ASC";

        //AND (fornecedores.gcm_key <> '')

            // ADICIONAR QUANTO TUDO FICAR PRONTO NA INSTRUÇÃO SQL NA CLÁUSULA WHERE
            //    AND
            //(cadastra_oferta.validade_oferta >= CURDATE())

        if($result = $mysql->query($sql)){
            $z=0;
            while ($data = $result->fetch_array()){
                $rest_api[$z]['cadastra_oferta_cod_oferta'] = $data['cod_oferta']; # id
                $abs_url_images = $config['abs_url_images'].'/';
                $abs_url_logo = $config['abs_url_logo'].'/';
                $abs_url_logo = $config['abs_url_logo'].'/';

                if((substr($data['foto'], 0, 7)=='http://r/admin/vovos/_lib/file/img/app_img')||(substr($data['foto'], 0, 8)=='http://v.br/admin/vovos/_lib/file/img/app_img')){
                    $abs_url_images = $abs_url_logo  = $abs_url_logo = '';

                }if((substr($data['logomarca'], 0, 7)=='http://vr/admin/vovos/_lib/file/img/app_logo')||(substr($data['logomarca'], 0, 8)=='http://.br/admin/vovos/_lib/file/img/app_logo')){
                    $abs_url_images = $abs_url_logo  = $abs_url_logo = '';

                }

                 /** TABELA FORNECEDORES **/
                $rest_api[$z]['fornecedores_fantasia'] = $data['fantasia'];
                $rest_api[$z]['fornecedores_CPF'] = $data['CPF'];
                $rest_api[$z]['fornecedores_identidade'] = $data['identidade'];
                $rest_api[$z]['fornecedores_bairro'] = $data['bairro'];
                $rest_api[$z]['fornecedores_celular'] = $data['celular'];
                $rest_api[$z]['fornecedores_cep'] = $data['cep'];
                $rest_api[$z]['fornecedores_cidade'] = $data['cidade'];
                $rest_api[$z]['fornecedores_cod_fornecedor'] = $data['cod_fornecedor'];
                $rest_api[$z]['fornecedores_complemento'] = $data['complemento'];
                $rest_api[$z]['fornecedores_data_hora_cadastro'] = $data['data_hora_cadastro'];
                $rest_api[$z]['fornecedores_email'] = $data['email'];
                $rest_api[$z]['fornecedores_estado'] = $data['estado'];
                $rest_api[$z]['fornecedores_logradourro'] = $data['logradourro'];
                $rest_api[$z]['fornecedores_numero'] = $data['numero'];
                $rest_api[$z]['fornecedores_responsavel_contato'] = $data['responsavel_contato'];
                $rest_api[$z]['fornecedores_telefone_empresa'] = $data['telefone_empresa'];
                $rest_api[$z]['fornecedores_telefone_responsavel'] = $data['telefone_responsavel'];
                $rest_api[$z]['fornecedores_celular'] = $data['celular'];

                /** TABELA OFERTAS **/
                $rest_api[$z]['cadastra_oferta_foto'] = $abs_url_images . $data['foto']; # images
                $rest_api[$z]['cadastra_oferta_titulo_promocao'] = $data['titulo_promocao']; # heading-1
                $rest_api[$z]['cadastra_oferta_cod_fornecedor'] = $data['cod_fornecedor']; # heading-2
                $rest_api[$z]['cadastra_oferta_cod_categoria'] = $data['cod_categoria']; # heading-2
                $rest_api[$z]['cadastra_oferta_descricao'] = $data['descricao']; # paragraph
                $rest_api[$z]['cadastra_oferta_igredientes'] = $data['igredientes']; # paragraph
                $rest_api[$z]['cadastra_oferta_valor_sem_desconto'] = $data['valor_sem_desconto']; # text
                $rest_api[$z]['cadastra_oferta_valor_com_desconto'] = floatval($data['valor_com_desconto']); # text
                $rest_api[$z]['cadastra_oferta_desconto'] = floatval($data['desconto']); # text
                $rest_api[$z]['cadastra_oferta_validade_oferta'] = $data['validade_oferta']; # text
                $rest_api[$z]['cadastra_oferta_qtd_estoque'] = $data['qtd_estoque']; # text

                /**  CATEGORIA COMIDA .....  **/
                $rest_api[$z]['categoria_comida_cod_categoria_com'] = $data['cod_categoria_com'];
                $rest_api[$z]['categoria_comida_data_cadastro'] = $data['data_cadastro'];
                $rest_api[$z]['categoria_comida_nome'] = $data['nome'];

                 /** FORNECEDOR CREDITO .....  **/
                $rest_api[$z]['fornecedor_credito_cod_fornecedor'] = $data['cod_fornecedor'];
                $rest_api[$z]['fornecedor_credito_cod_fornecedor_codigo'] = $data['cod_fornecedor_codigo'];
                $rest_api[$z]['fornecedor_credito_qtd_credito'] = $data['qtd_credito'];

                   /** TABELA FORNECEDOR_VISUAL **/

//                $rest_api[$z]['fornecedor_visual_cod_fornecedor'] = $data['cod_fornecedor'];
                $rest_api[$z]['fornecedor_visual_cod_fornecedor_visual'] = $data['.cod_fornecedor_visual'];
                $rest_api[$z]['fornecedor_visual_data_cadastro'] = $data['data_cadastro'];
                $rest_api[$z]['fornecedor_visual_descricao_empresa'] = $data['descricao_empresa'];
                $rest_api[$z]['fornecedor_visual_facebook'] = $data['facebook'];
                $rest_api[$z]['fornecedor_visual_logomarca'] = $abs_url_logo . $data['logomarca']; # images
                $rest_api[$z]['fornecedor_visual_latitude'] = $data['latitude'];
                $rest_api[$z]['fornecedor_visual_longitude'] = $data['longitude'];

                 /** TABELA FORNECEDOR_CONFIGURA_FRETE **/

                $rest_api[$z]['fornecedor_configura_frete_agenda_comida'] = $data['agenda_comida'];
                $rest_api[$z]['fornecedor_configura_frete_cod_configura_frete'] = $data['cod_configura_frete'];
                $rest_api[$z]['fornecedor_configura_frete_cod_fornecedor'] = $data['cod_fornecedor'];
                $rest_api[$z]['fornecedor_configura_frete_custo_padrao'] = floatval($data['custo_padrao']);
                $rest_api[$z]['fornecedor_configura_frete_frete_gratis'] = $data['frete_gratis'];
                $rest_api[$z]['fornecedor_configura_frete_prazo_entrega_max'] = $data['prazo_entrega_max'];
                $rest_api[$z]['fornecedor_configura_frete_prazo_entrega_min'] = $data['prazo_entrega_min'];
                $rest_api[$z]['fornecedor_configura_frete_tem_delivery'] = $data['tem_delivery'];
                $rest_api[$z]['fornecedor_configura_frete_tipos_pagamentos'] = $data['tipos_pagamentos'];
                $rest_api[$z]['fornecedor_configura_frete_valor_minimo_frete_gratis'] = $data['valor_minimo_frete_gratis'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_one'] = $data['dayw_one'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_two'] = $data['dayw_two'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_three'] = $data['dayw_three'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_four'] = $data['dayw_four'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_five'] = $data['dayw_five'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_six'] = $data['dayw_six'];
                $rest_api[$z]['fornecedor_configura_frete_dayw_seven'] = $data['dayw_seven'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_one'] = $data['hour_ini_one'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_one'] = $data['hour_end_one'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_two'] = $data['hour_ini_two'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_two'] = $data['hour_end_two'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_three'] = $data['hour_ini_three'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_three'] = $data['hour_end_three'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_four'] = $data['hour_ini_four'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_four'] = $data['hour_end_four'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_five'] = $data['hour_ini_five'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_five'] = $data['hour_end_five'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_six'] = $data['hour_ini_six'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_six'] = $data['hour_end_six'];
                $rest_api[$z]['fornecedor_configura_frete_hour_ini_seven'] = $data['hour_ini_seven'];
                $rest_api[$z]['fornecedor_configura_frete_hour_end_seven'] = $data['hour_end_seven'];

                  /** TABELA AVALIAÇÕES **/
//              $rest_api[$z]['avaliacao_cod_avaliacao'] = $data['cod_avaliacao'];
//                $rest_api[$z]['avaliacao_cod_fornecedor'] = $data['cod_fornecedor'];
//                $rest_api[$z]['avaliacao_geral'] = floatval($data['avaliacao_geral']);

                $z++;
            }
            $result->close();
        }

        break;

    case "route":
        $rest_api["routes"][0]["namespace"] = "promocao";
        $rest_api["routes"][0]["methods"][] = "GET";
        $rest_api["routes"][0]["_links"]["self"] = $_SERVER["PHP_SELF"]."?json=promocao";
        $rest_api["routes"][1]["namespace"] = "restaurantes";
        $rest_api["routes"][1]["methods"][] = "GET";
        $rest_api["routes"][1]["_links"]["self"] = $_SERVER["PHP_SELF"]."?json=restaurantes";
        break;
}

header('Content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
echo json_encode(utf8ize($rest_api));

?>

Answer: utilize um sub-select:
   (select avg(avaliacoes.avaliacao_geral) from avaliacoes where avaliacoes.cod_fornecedor = fornecedores.cod_fornecedor ) as media_avaliacao

Query completa:
SELECT
   (select avg(avaliacoes.avaliacao_geral) from avaliacoes where avaliacoes.cod_fornecedor = fornecedores.cod_fornecedor ) as media_avaliacao,
   fornecedores.cod_fornecedor,
   fornecedores.fantasia,
   fornecedores.CPF,
   fornecedores.identidade,
   fornecedores.email,
   fornecedores.cep,
   fornecedores.logradourro,
   fornecedores.complemento,
   fornecedores.cidade,
   fornecedores.estado,
   fornecedores.responsavel_contato,
   fornecedores.telefone_empresa,
   fornecedores.telefone_responsavel,
   fornecedores.celular,
   fornecedores.bairro,
   fornecedores.numero,
   fornecedores.latitude,
   fornecedores.longitude,
   cadastra_oferta.cod_oferta,
   cadastra_oferta.cod_fornecedor,
   cadastra_oferta.cod_categoria_com,
   cadastra_oferta.titulo_promocao,
   cadastra_oferta.descricao,
   cadastra_oferta.foto,
   cadastra_oferta.valor_sem_desconto,
   cadastra_oferta.valor_com_desconto,
   cadastra_oferta.desconto,
   cadastra_oferta.validade_oferta,
   cadastra_oferta.igredientes,
   cadastra_oferta.qtd_estoque,
   categoria_comida.cod_categoria_com,
   categoria_comida.nome,
   categoria_comida.data_cadastro,
   fornecedor_credito.cod_fornecedor_codigo,
   fornecedor_credito.cod_fornecedor,
   fornecedor_credito.qtd_credito,
   fornecedor_configura_frete.cod_configura_frete,
   fornecedor_configura_frete.cod_fornecedor,
   fornecedor_configura_frete.tem_delivery,
   fornecedor_configura_frete.custo_padrao,
   fornecedor_configura_frete.frete_gratis,
   fornecedor_configura_frete.valor_minimo_frete_gratis,
   fornecedor_configura_frete.tipos_pagamentos,
   fornecedor_configura_frete.prazo_entrega_min,
   fornecedor_configura_frete.prazo_entrega_max,
   fornecedor_configura_frete.agenda_comida,
   fornecedor_configura_frete.dayw_one,
   fornecedor_configura_frete.dayw_two,
   fornecedor_configura_frete.dayw_three,
   fornecedor_configura_frete.dayw_four,
   fornecedor_configura_frete.dayw_five,
   fornecedor_configura_frete.dayw_six,
   fornecedor_configura_frete.dayw_seven,
   fornecedor_configura_frete.hour_ini_one,
   fornecedor_configura_frete.hour_end_one,
   fornecedor_configura_frete.hour_ini_two,
   fornecedor_configura_frete.hour_end_two,
   fornecedor_configura_frete.hour_ini_three,
   fornecedor_configura_frete.hour_end_three,
   fornecedor_configura_frete.hour_ini_four,
   fornecedor_configura_frete.hour_end_four,
   fornecedor_configura_frete.hour_ini_five,
   fornecedor_configura_frete.hour_end_five,
   fornecedor_configura_frete.hour_ini_six,
   fornecedor_configura_frete.hour_end_six,
   fornecedor_configura_frete.hour_ini_seven,
   fornecedor_configura_frete.hour_end_seven,
   fornecedor_visual.cod_fornecedor_visual,
   fornecedor_visual.cod_fornecedor,
   fornecedor_visual.descricao_empresa,
   fornecedor_visual.facebook,
   fornecedor_visual.localizacao_mapa,
   fornecedor_visual.logomarca,
   fornecedor_visual.data_cadastro,
   fornecedor_visual.latitude,
   fornecedor_visual.longitude,
   (6371 * acos(
        cos( radians('$latitude') )
        * cos( radians( fornecedores.latitude ) )
        * cos( radians( fornecedores.longitude ) - radians('$longitude') )
        + sin( radians('$latitude') )
        * sin( radians( fornecedores.latitude ) )
        )
    ) AS distancia

FROM
   fornecedores INNER JOIN cadastra_oferta ON fornecedores.cod_fornecedor = cadastra_oferta.cod_fornecedor
   INNER JOIN categoria_comida ON cadastra_oferta.cod_categoria_com = categoria_comida.cod_categoria_com
   INNER JOIN fornecedor_credito ON fornecedores.cod_fornecedor = fornecedor_credito.cod_fornecedor
   INNER JOIN fornecedor_configura_frete ON fornecedores.cod_fornecedor = fornecedor_configura_frete.cod_fornecedor
   INNER JOIN fornecedor_visual ON fornecedores.cod_fornecedor = fornecedor_visual.cod_fornecedor
WHERE
   (fornecedor_credito.qtd_credito >= '1') AND
   (cadastra_oferta.qtd_estoque >= '1')  AND
   (cadastra_oferta.validade_oferta >= NOW())
HAVING distancia <= '$raio'
ORDER BY
   cadastra_oferta.titulo_promocao ASC

Comment: @Rovan Linhalis, seria bom para a comunidade e futuros leitores se, junto da resposta, você adicionasse uma explicação, citando o motivo de ter usado um sub select. Dar a resposta "de mão beijada" não é bem visto pela comunidade por não agregar conhecimento. No mais, parabéns pela resposta.
Comment: Resolvido. Obrigado @Rovan Linhalis.
Comment: @ThiagoBarros concordo, e geralmente faço isso, mas me pareceu tão simples o subselect, que passou batido. Ramos, se houver muitos registros pode ter um desempenho ruim o subselect, se for o caso também há a possibilidade de usar uma tabela temporária.


Android(Table layout)

Question: I am trying to display a table layout.In that i have the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.budget1/com.budget1.Report}: android.view.InflateException: Binary XML file line #2: Error inflating class Tablelayout

My xml code is:
<?xml version="1.0" encoding="utf-8"?>
<Tablelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <Tablerow>
 <Textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter your name">
     </Textview>
    <Edittext android:layout_width="150px" android:layout_height="wrap_content">
        </Edittext>
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    />
    </Tablerow>

 <Tablerow>
 <Textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Spanning Two columns" android:layout_span="2">
     </Textview>
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"
    />
 </Tablerow>

</Tablelayout>

Please help me..
Answer: Android layout xml files are case sensitive. Use TableLayout, TableRow, TextView, EditText, etc.
Answer: You did not specify Ids for your layout components. Try adding a unique ID for each TableRow, TextView, ...etc using parameter android:id="@+id/your_desired_id"
Answer: I Edited your xml file like this, its working fine,
   <TableLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Enter your name"
                />

        <EditText
                  android:layout_width="150px"
                  android:layout_height="wrap_content"
                />

        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Submit"
                />
     </TableRow>

    <TableRow

        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
                android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Spanning Two columns"
                  android:layout_span="2" />

        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Cancel"
                />
    </TableRow>

  </TableLayout>

Comment: Thanks vishwa..for trying...i got the answer...I want to have space between each row in the table..How can do that.??
Comment: Hi, put  android:layout_marginTop="10px" in your second tablerow as a attribute
Comment: Thanks vishwa.Its working..One more vishwa(don't mistake me)..Is it possible to show separation between rows in table layout.
Comment: i didn't get you..what type of separation you want
Comment: Try this link http://stackoverflow.com/questions/5092116/how-can-i-add-separating-lines-between-my-tablerows-that-are-created-programmati

Android(Table layout)


Click on particular instance for a button using CSS selector

Question: I have a webpage which has multiple submit buttons. I want to loop through them and click on each of them one by one.
I know I can do it via xpath like this (//button[@class='submit'])[i] (where i = loop number).
But I wanted to know if it's possible to do via CSS selector?
I've tried button.submit but it will always click on the first button and I want to be able to loop through. I've also tried button.submit:first-child but it seems to do the same thing.
The following is similar to what the HTML is like.

    <button class="submit" type="button"></button>

    <button class="submit" type="button"></button>

    <button class="submit" type="button"></button>

Comment: Did you try to `loop()` to _be able to loop_?
Comment: The loop isnt the issue. I need the css selector for my element.
Answer: Yes, you can do this such way:
If you are using Java version less than 8 do this way:
List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

for(WebElement element: elements){
     element.click();
     confirm.click();
}

If you are using Java 8 or above, you can try this way:
List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

  elements.forEach(e->{
        e.click();
        confirm.click();
    });

Comment: If I understand correctly this will click on each element one after the other. But what if after clicking each button there is a confirmation modal where you have to click confirm?

For example you first click Submit, then you click confirm for each one.


How do I know when my results here are statistically significant for user ratings?

Question: I have a survey where I ask people their ratings for something. If they vote 0-4, I rank them as "con", 5-7 as "on the fence," and 8-10 as "pro."
So now I want to split up all my data by region, such as their state.
However, some states have a lot more replies than others.
I can't tell which of these results are significant and which aren't, or if there's anything else I need to take into account. For example some states simply have a lot more people.
Is there a simple way to determine which results in this context are meaningful and which are not?
Answer: Here are some things to consider.
1) Why are you splitting up your outcome variable into coarsing groupings? You lose variance by doing so. That may be theoretically fine, or after some modeling you may see that it is appropriate to do so. But modeling 3 levels with either a linear model (probably not appropriate, but could be after model checks) or an ordinal/multinomial logit/probit will likely give you different results than modeling the outcome as continuous. I wouldn't jump to the conclusion of breaking down the data in that way before doing some testing unless my theory was really strong; I bring this up because you haven't provided any details on why you want to do this.
2) It is relatively simple to account for differences in states - just include them as covariates. Population, for example, can be included as a covariate (consider entering it in logarithms rather than raw). This will adjust your results by each state's population. However, if this is survey data and you have sampling weights, those weights may account for that, in which case including population as a covariate would have a different interpretation.
3) To model state differences you could enter them as fixed effects (K-1 dummy variables, where K is the number of states). Alternatively, you could consider a random coefficient model, where the state is a normally distributed random effect. There are tests for this that are important to use. Without knowing more about what you are modeling or what you have done, I won't get into the details too much here.
You need to provide more context to your statement "I can't tell which results are significant." What results? Did you model it? How? What are you looking at that is confusing?
Comment: Sorry, I didn't mean to sound curt. It would help if you put some examples of the output you are looking at and said a little more about your example. You haven't given enough info to answer your question or provide guidance that gets to your exact point.
Comment: I appreciate the response, but honestly, replies like this really discourage me from stuff like this because I am totally unfamiliar with 95% of the things you reference in your post.

All I'm trying to do is say "Okay, for Washington state, we see that x number of people fall into the Con category, y number of people fall into the On-The-Fence category, and z people fall into the Pro category. Are these results significant / accurately representative, or do we need more data to be sure?"
Comment: Maybe I misunderstand but I assumed that there was a cutoff in statistics for which we can claim something is statistically significant. I am basically trying to determine at what point can we say "we have enough data for these results to be meaningful" in terms of output.
Comment: Robin, your efforts to answer the question are very much appreciated. But since you're relatively new here, please do not be offended if I remind you that when the original poster "hasn't given enough info to answer the question," then unless you are really sure you understand the question anyway, you should first consider responding with a comment requesting clarification rather than posting a full answer.
Comment: I disagree that I have not given enough information, though. What I am asking about is a very common concept in statistics, but I don't know how to properly apply it here.


remove default tab selection and also add scrollTo effect

Question: var tabLinks = new Array();
    var contentDivs = new Array();
function init() {
<code>   // Grab the tab links and content divs from the page
   var tabListItems = document.getElementById('tabs').childNodes;
   for ( var i = 0; i < tabListItems.length; i++ ) {
     if ( tabListItems[i].nodeName == "LI" ) {
       var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
       var id = getHash( tabLink.getAttribute('href') );
       tabLinks[id] = tabLink;
       contentDivs[id] = document.getElementById( id );
     }
   }

   // Assign onclick events to the tab links, and
   // highlight the first tab
   var i = 0;

   for ( var id in tabLinks ) {
     tabLinks[id].onclick = showTab;
     tabLinks[id].onfocus = function() { this.blur() };
     if ( i == 0 ) tabLinks[id].className = 'selected';
     i++;
   }

   // Hide all content divs except the first
   var i = 0;

   for ( var id in contentDivs ) {
     if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
     i++;
   }
 }
</code>
function showTab() {
        var selectedId = getHash( this.getAttribute('href') );
<code>    // Highlight the selected tab, and dim all others.
    // Also show the selected content div, and hide all others.
    for ( var id in contentDivs ) {
      if ( id == selectedId ) {
        tabLinks[id].className = 'selected';
      contentDivs[id].className = 'tabContent ';
      } else {
        tabLinks[id].className = '';
        contentDivs[id].className = 'tabContent hide';
      }
    }

    // Stop the browser following the link
    return false;
  }
</code>
In the above javascript, am looking to add scrollTo method to tabListItems and also remove default tab selection (i.e., no tab is selected by default).
cheers
venkat
Answer: // Assign onclick events to the tab links, and
// highlight the first tab
var i = 0;
for ( var id in tabLinks ) {
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function() { this.blur() };
if ( i == 0 ) tabLinks[id].className = '';
contentDivs[id].className = 'tabContent hide';
i++;
}
bolded part is been tweaked..!!
that makes, to hide the content and also deselects the default tab!!
Someone should help me with adding scrollTo() method to tabListItems part!!!