Is the formal semantics of first-order logic ambiguous?

Question: When defining the semantics of propositional and particularly first-order logic, it has always made me uneasy when reading, for example:
$$M \models A \lor B \quad\text{iff}\quad M \models A \text{ or } M \models B$$
Where does the "or" on the right hand side comes from? What's its definition?
I know this is supposed to be in the "meta" language and, somehow, we all mathematicians agree on what that "or" is supposed to mean. You could even be a bit more cautious, point me to a truth table and say: "That! Use that if are unsure of what we mean". Fine.
But then it baffles me even more when I read something along the lines of
$$M \models \forall x A \quad\text{iff}\quad M_x \models A \text{ for all $x$-variants $M_x$ of $M$}$$
What is the meaning of this "for all"?? Most of our intuitions would probably agree on what to do if the domain of $M$ is finite, check all the possibilities one by one; but what if the domain is some weird infinite non-recursively enumerable monstrous set, how can we know whether $M_x \models A$ is true "for all" values of $x$?
A bit more to the point, how would you argue whether
$$\lnot\forall x A \rightarrow \exists x \lnot A$$
is valid or not? (from a purely semantical point of view)
It seems, at least to me, that the given definitions are not enough, as you also have to specify what sorts of arguments do mathematicians accept at the "meta" language (e.g. is proof by contradiction valid to show the existence of elements? or did you meant a constructive/intuitionistic proof?)
Update:
Ok, now I am firmly convinced that the answer to my original question (is the definition of FOL semantics ambiguous?) is: No. All sensible mathematicians should agree that the semantics are well defined.
Indeed, as Carl argues on his answer:

Given some structure M, and a property A that each element of M may or may not have, either every element of M has the property, or there is some element that does not have the property

That is, the definition does make the assumption that, with respect to the model, each property is either true or is false. No other options are allowed. Now a constructivist or even a paraconsistent mathematician may not agree on this assumption, and suggest that other options should be considered as well. And that's why they can get away with rejecting things like the law of the excluded middle; not because they think "or" should mean something different, but because they are making different assumptions about their logic systems.
Furthermore, even they would agree that if one assumes that a property can only be true or false, as FOL definition states, then for a model $M$ we have that either every element of the domain has the property, or some element of the domain does not have the property. End of story.
And this is why we can unambiguously state that $\lnot\forall x A \rightarrow \exists x \lnot A$ is valid with respect to this definition of the semantics.
Furthermore, this is true even if there might be some particular model $M$ and property $A$ for which we might never know whether $M \models \forall x A$ or not (because $M$ is "monstrous" or the property A is strange, and mathematicians are never able to figure it out).
Comment: Concerning "what does it mean to check whether $M_x\models A$ "for all" values of $x$", it may be worthwhile to point out that the definition says nothing about "checking". It only says when $M\models\forall x A$ *is true*.  Checking whether it's true is a different matter, rather more complicated since it depends on what tools or methods are available for checking.
Comment: I think it's important to understand that we logicians (at least most of us) don't accept any responsibility for defining the language you use on the street for you. Without meaning to be rude, I could ask you to define each and every word you used in your question, because I'm pretending not to understand anything you say. It's not the purpose of logic to build the whole of mathematics out of nothing; it is to study the way mathematicians think *using* the way mathematicians think.
Comment: There is no problem when we use our reasoning capacities to prove theorems about groups, or elliptic curves, or partial differential equations. Equally, there is no problem when we use our reasoning capacities to prove theorems abot formal systems.
Comment: I think your views are well aligned with constructive mathematics. Check out wikipedia article on constructivism http://en.wikipedia.org/wiki/Constructivism_%28mathematics%29
Comment: Thanks for your comments, to push the issue a bit further: (1) I know about constructive and intuitionistic logic, and this is precisely the basis of my question: given than mathematicians themselves do not generally agree on what "or", "implies" or "for all" mean (depending on your flavour of logic), how are supposed to make sense of these definitions?
Comment: (2) yes, I think that a proof theoretical view addresses these concerns. If you give me either the axioms of classical or intuitionistic logic, I don't have questions any more about the validity of my example formula above. But then how are we supposed to make sense of soundness/completeness theorems of the proof theoretic view w.r.t. the semantics as defined above?
Comment: (3) another example to stress the point of my concern. I know that the semantics of intuitionistic logic can be defined, e.g., in terms of [Kripke models](http://en.wikipedia.org/wiki/Kripke_semantics#Semantics_of_intuitionistic_logic). But when we say "$w \models A \rightarrow B$ iff ... implies ...", does the word "implies" refer to the classical or intuitionistic implication?
Comment: Once you agree on what the semantics of the basic logical connectives and quantifiers, you can show that the _purely syntactic_ inference rules only allows you to deduce true statements from other true statements.
Comment: @AndreasBlass, I rephrased slightly my question trying to avoid your objection.
Answer: How would I argue semantically that $\lnot (\forall x) A \to (\exists x) \lnot A$?

Assume $M$ is a model of the theory at hand and assume that $M$ satisfies $\lnot (\forall x) A(x)$. Then, by the definition of the satisfaction predicate, it is not the case that $M$ satisfies $(\forall x) A(x)$. Thus, looking at the definition of the satisfaction predicate, there is some $z$ in $M$ such that $M$ does not satisfy $A(z)$. Hence $M$ satisfies $\lnot A(z)$, and thus $M$ satisfies $(\exists x)\lnot A(x)$.

Most mathematics takes place in an informal natural-language metatheory, and mathematical logic is no exception. The above argument is not particularly different from the argument that every cyclic group is isomorphic to either $\mathbb{Z}$ or to $\mathbb{Z}_n$ for some $n$, which does not show that we can tell which case holds in an algorithmic way.
Just like any other area of mathematics, we can use a formal metatheory such as ZFC to formalize these informal arguments. Both arguments I have mentioned here can be easily formalized in ZFC. But mathematics itself is typically carried out in an informal metatheory, with few mentions of any formal metatheory.
The question was edited to replace "check" with "know", but that still misses the point of classical logic. Classical logic is designed for studying the properties of abstract structures that have truth values regardless whether we have any effective way to determine those truth values. Given some structure $M$, and a property $A$ that each element of $M$ may or may not have, either every element of $M$ has the property, or there is some element that does not have the property; that claim is not related to our ability to find the element, only to our abstract reasoning about what "all elements have the property" and "not all elements have the property" mean in English. We may never know whether all elements have the property $A$, but we can still argue abstractly that $\lnot (\forall x) A \to (\exists x) \lnot A$.
The definition of the satisfaction predicate is not meant to tell us how to effectively verify truth values; it is just meant to capture the relationships between truth values of compound statements and truth values of simpler statements.  Intuitively, this is why the completeness theorem for first-order logic links provability with truth in all structures - we may never really know everything about a particular structure, but when we reason abstractly about the properties that an arbitrary structure must have we end up proving results that are true for all structures.
Comment: Thanks! This cleared up things for me. The key sentences seems to be: "a property A that each element of M may or may not have". Indeed, the semantics does define that the only two options for a property is to be either true or false. Will try to elaborate a bit more adding some comments to my question.
Comment: @Juan A. Navarro: your expanded comments on the question look correct to me.


How to redirect /user to /user/login

Question: My client wants the only login url to be /user/login
So I need to redirect /user to /user/login
any idea how to accomplish this?
Comment: You should consider that '/user' url can be access by _authenticated_ user also. So, if you redirect '/user' to '/user/login', then its should be redirect to only _anonymous_ user, not _authenticated_ user.
Comment: @JayendraKainthola no problem. but how do i redirect?
Comment: possible duplicate of [How to direct a specific role to a specific page](http://drupal.stackexchange.com/questions/36479/how-to-direct-a-specific-role-to-a-specific-page) - "anonymous" and "authenticated" are roles, too.
Answer: You can use rules module to create a redirect when anonymous user view the /user page.

The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

You can follow below step:

Go to Administration -> Configuration -> Workflow -> Rules
Click on Add new rule link in top of page
Fill the name and select Drupal is initializing from React on Event drop down in the form and save the form.
click on Add Condition link in the page and select User has role(s) from the "Condition to add" drop-down and select anonymous user as user role and save the form.
Click on Add condition link and select "Data comparison" from the "Condition to add" drop-down and set site:current-page:path as "Data selector" and click on continue button and set 'user' in the value field and save the form.
Click on Add Action link and select Page redirect event and set user/login in the value field and save the form.
Answer: You can use the hook_menu_site_status_alter():
/**
 * Implements hook_menu_site_status_alter().
 */
function MODULENAME_menu_site_status_alter(&$menu_site_status, $path) {
  if (user_is_anonymous()) {
    if ($path == 'user') {
      drupal_goto('user/login');
    }
  }
}

Here is an example on how another module implement this hook.
Comment: Please don't post code-only answer. This only helps someone if they know what to do with the code; it doesn't help them understand why the code solves the problem.
Answer: Option 1: Refer the https://www.drupal.org/project/rename_admin_paths module. The purpose of this module is to secure drupal backend by overriding admin path.
Option 2: You can also redirect /user to /user/login by writing redirect rule in .htaccess file.

How to redirect /user to /user/login


Valid CSV filed import fails with Data between close double quote (") and field separator: field starts with

Question: I am trying to import a CSV file into BQ from GS.
The cmd I use is:

$ bq load --field_delimiter=^ --quote='"' --allow_quoted_newlines
  --allow_jagged_rows --ignore_unknown_values wr_dev.drupal_user_profile gs://fls_csv_files/user_profileA.csv
  uid:string,first_name:string,last_name:string,category_id:string,logo_type:string,country_id:string,phone:string,phone_2:string,address:string,address_2:string,city:string,state:string,zip:string,company_name:string,created:string,updated:string,subscription:string

the reported error is
File: 0 / Line:1409 / Field:14, Data between close double quote (")
and field separator: field starts with: <Moreno L>

sample data is:
$ sed -n '1409,1409p' user_profileA.csv
$ 1893^"Moreno"^"Jackson"^17^0^1^"517-977-1133"^"517-303-3717"^""^""^""^""^""^"Moreno L Jackson \"THE MOTIVATOR!\" "^0^1282240785^1

which was generated from MySQL with:
SELECT * INTO OUTFILE '/opt/mysql_exports/user_profileA.csv'
FIELDS TERMINATED BY '^'
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM p;

Why I get the error message in BQ? How to properly export from MySQL CSV files that have newlines (CR and LF mixed, as it was user input from Windows or Mac)
Couple of job IDs:
Job ID: aerobic-forge-504:bqjob_r75d28c332a179207_0000014710c6969d_1
Job ID: aerobic-forge-504:bqjob_r732cb544f96e3d8d_0000014710f8ffe1_1
Update
Apparently it's more to this. I used 5.5.34-MariaDB-wsrep-log INTO OUTFILE, and either is a bug or something wrong, but I get invalid CSV exports. I had to use other tool to export proper CSV. (tool: SQLYog)
it has problems with double quotes, for example Field 14 here has error:
3819^Ron ^Wolbert^6^0^1^6123103169^^^^^^^""Lil"" Ron's^0^1282689026^1

Comment: Try going thru Cloud SQL as an alternative: https://medium.com/google-cloud/loading-mysql-backup-files-into-bigquery-straight-from-cloud-sql-d40a98281229
Answer: UPDATE 2019:
Try this as an alternative:

Load the MySQL backup files into a Cloud SQL instance.
Read the data in BigQuery straight out of MySQL.

Longer how-to:

https://medium.com/google-cloud/loading-mysql-backup-files-into-bigquery-straight-from-cloud-sql-d40a98281229

The proper way to encode a double quote in CSV is to put another double quote in front of it.
So instead of:
"Moreno L Jackson \"THE MOTIVATOR!\"...

Have:
"Moreno L Jackson ""THE MOTIVATOR!""...


Why do we sum the cost function in a logistic regression?

Question: I get the intuition behind the loss function for linear regression, which happens to be the MSE function. We have a set of points and we try to fit a line between them so that the line is at a minimum distance from all the points.
So it makes sense to add up the distances from all the points and then try to minimize that distance.
However, in logistic regression, why do we take the sum of the loss function? Can't we calculate the losses for each training example, minimize that and move on to the next? We could then average out the weights for each example over all the iterations.
My question is: What is the intuitive sense behind taking the sum of the training example losses and them summing it up and minimizing that. It makes more sense to me to minimize the individual training example and then move on to the next.
Comment: Let's assume you have 100 training examples and 5 independent variables.  If you look at each training example separately, you only need one independent variable, e.g., the constant term, with value $+/- \infty$ to predict that training example perfectly.  The value of the constant term will change from training example to training example, so it is not in fact a constant.  When you are done, you will have learned... nothing at all about the relationship between the independent variables and the target variable, and you will have a "model" with no predictive power.
Answer: Let's assume you have 100 training examples and 5 independent variables. If you look at each training example separately, you only need one independent variable, e.g., the constant term, with value $\pm \infty$ to predict that training example perfectly ($+\infty$ if the target value is $1$, $-\infty$ if it's $0$.) The value of the constant term will change from training example to training example, so it is not in fact a constant - but, because you are looking at the data one observation at a time, you have no way to force it to be a constant.  When you are done, you will have learned... nothing at all about the relationship between the independent variables and the target variable, and you will have a "model" with 100% "explanatory" but no predictive power.  You will have missed seeing the forest because you will have been looking at the trees, so to speak.


Erro no procedimento case 3

Question: Estou com problemas no meu case 3 do meu código em C, ele deveria comparar as duas strings com a função strcmp
filmeIgual=strcmp(filmePesquisa,v[x].nome);

e se o resultado for zero, if(filmeIgual == 0), as strings serão iguais.
Porém meu código quando executado, dá toda hora que o programa parou de funcionar, já testei de várias maneiras.
Segue o código que estou com problema no case 3, o link do código também está no paste bin caso ajude a entender: https://pastebin.com/F9cPyRkK
O Case 3 deve ser uma função que receberá o a palavra (string) que o usuário digitar e ver se ela existe no vetor v[] que está armazenando estes dados na struct Filme com a variável que representa-á filmes
SEGUE CODIGO RESOLVIDO, ABRACOS.
#include <stdio.h>
#include <stdlib.h>
#define T 51 // Tamanho maximo sera 50 da constante das strings que vou utilizar
#define Tfilmes 2 // Alterar aqui nessa constante caso deseje alterar quantidade de filmes disponivel para cadastro

struct Filme
{
    char nome[T];
    char diretor[T];
    int anoLancamento, quantAtores;
    float nota;
};

void cadastraFilmes(struct Filme v[], int x) //Procedimento 1 cadastra filmes ao vetor
    {
        if(x < Tfilmes) // Controla quantidade maxima de filmes segundo constante Tfilmes
        {
                printf("Digite o nome do filme: ");
                gets(v[x].nome);
                printf("Digite o nome do diretor: ");
                gets(v[x].diretor);
                printf("Digite o ano do lancamento do filme: ");
                scanf("%d%*c",&v[x].anoLancamento);
                while(v[x].anoLancamento < 2010) // Verifica se o ano de lancamento digitado e superior a 2010
                    {
                        printf("\nSo podem ser cadastrados filmes lancados a partir de 2010, tente novamente!\n");
                        printf("\nDigite o ano do lancamento do filme: ");
                        scanf("%d%*c",&v[x].anoLancamento);
                    }
                printf("Digite a quantidade de atores: ");
                scanf("%d%*c",&v[x].quantAtores);
                printf("Digite a nota recebida pela critica: ");
                scanf("%f%*c",&v[x].nota);
                printf("\n");
                printf("\tFilme cadastrado com sucesso!\n\n"); // Confirmacao de cadastro efetuado com sucesso
                system("pause");
        }
        else // Se a quantidade maxima de filmes já estiver sido cadastradaa, avisa o usuario e nao deixa o mesmo cadastrar mais
        {
            printf("\t\nQuantidade maxima de filmes ja cadastrada no vetor!\n\n");
            system("pause");
        }
    }

void diretorAno(struct Filme v[]) // Procedimento 2 pesquisa se a string nomeDiretor digitada e a data de lancamento desejada existem
    {
            char nomeDiretor[T];
            int x,pesquisaAno,nomeDiretorIgual;
            printf("Digite o nome do diretor para pesquisa: ");
            gets(nomeDiretor);
            printf("Digite a data de lancamento desejada: ");
            scanf("%d%*c",&pesquisaAno);
            for(x=0;x<Tfilmes;x++)
            {
                nomeDiretorIgual=strcmp(nomeDiretor,v[x].diretor); // funcao strcmp verifica se duas strings sao iguais
                if(nomeDiretorIgual == 0 && pesquisaAno == v[x].anoLancamento) // se nome diretor e data lancamento forem iguais as digitadas e existirem no vetor, lista na tela
                    {
                        printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
                        printf("\n\tNome do filme: %s", v[x].nome);
                        printf("\n\tNome do diretor: %s", v[x].diretor);
                        printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
                        printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
                        printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
                        printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
                        system("pause");
                    }
                else // caso nao sejam encontrados e mostrado na tela a negativa
                    {
                        printf("\t\nDiretor e data de lancamento nao encontradas, por favor tente novamente.\n\n");
                        system("pause");
                    }
            }
    }

void nomesFilme(struct Filme v[]) // Procedimento 3 pesquisara se o nome informado de filme existe
    {
            char nome[T];
            int x, filmeIgual;
            char filmePesquisa[Tfilmes];
            printf("Digite o nome do filme para pesquisa: ");
            gets(filmePesquisa);
            for(x=0;x<Tfilmes;x++) // percorre vetor com limite maximo definido pela constante la em cima
            {
                filmeIgual=strcmp(filmePesquisa,v[x].nome); // funcao strcmp compara 2 strings
                if(filmeIgual == 0) // se o da strcmp for zero, significa que sao iguais
                    {
                        printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
                        printf("\n\tNome do filme: %s", v[x].nome);
                        printf("\n\tNome do diretor: %s", v[x].diretor);
                        printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
                        printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
                        printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
                        printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
                        system("pause");
                    }
                else // se nao for igual, neste caso, ja podemos definir que o filme nao foi encontrado no vetor
                    {
                        printf("\t\nFilme nao encontrado.\n\n");
                        system("pause");
                    }
            }
    }

void mostraFilmes(struct Filme v[]) // Procedimento 4 que vai listar todos os filmes ja cadastrados no vetor
    {
        int x;
        for(x=0;x<Tfilmes;x++)
        {
            printf("\n================================================\n");
            printf("\n\tNome do filme: %s", v[x].nome);
            printf("\n\tNome do diretor: %s", v[x].diretor);
            printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
            printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
            printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
            printf("\n================================================\n");
        }
        system("pause");
    }

int menu() // Menu central
    {
        int z;
        printf("\n================================================\n");
        printf("\n\n\t\tMENU:\n");
        printf("\n\tDigite a opcao desejada:\n");
        printf("\n\t(1) Cadastrar Filme \n");
        printf("\n\t(2) Pesquisar por ano e diretor \n");
        printf("\n\t(3) Pesquisar por nome do filme \n");
        printf("\n\t(4) Lista todos os filmes cadastrados \n");
        printf("\n\t(5) Sair\n\n");
        printf("\n================================================\n");
        scanf("%d%*c", &z);
        system("cls");
        return z;
    }

int main()
{
    int x=0;
    int op;
    struct Filme filmes[Tfilmes];
    do
    {
        op=menu();
        switch(op)
        {
            case 1:
                cadastraFilmes(filmes,x);
                x++;
                system("cls");
                break;
            case 2:
                diretorAno(filmes);
                system("cls");
                break;
            case 3:
                nomesFilme(filmes);
                system("cls");
                break;
            case 4:
                mostraFilmes(filmes);
                system("cls");
                break;
            case 5:
                system("pause");
                break;
            default:
                printf("\n\tOpcao invalida, tente novamente.\n");
                break;
        }
    }while(op!=5); // coloquei este while e coloquei tambem um case 5 la no menu, nao precisaria portanto o case 5 SE eu nao quisesse colocar um system pause que com o mesmo fica mais claro que o programa foi finalizado.

return 0;
}

Comment: Roda o programa com um debbuger e veja o erro que aparece.
Answer: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
#define T 51
#define Tfilmes 2

struct Filme
{
    char nome[T];
    char diretor[T];
    int anoLancamento, quantAtores;
    float nota;
};
void cadastraFilmes(struct Filme v[], int x)
{
    if (x < Tfilmes)
    {
        printf("Digite o nome do filme: ");
        gets(v[x].nome);
        printf("Digite o nome do diretor: ");
        gets(v[x].diretor);
        printf("Digite o ano do lancamento do filme: ");
        scanf("%d%*c", &v[x].anoLancamento);
        while (v[x].anoLancamento < 2010)
        {
            printf("\nSo podem ser cadastrados filmes lancados a partir de 2010, tente novamente!\n");
            printf("\nDigite o ano do lancamento do filme: ");
            scanf("%d%*c", &v[x].anoLancamento);
        }
        printf("Digite a quantidade de atores: ");
        scanf("%d%*c", &v[x].quantAtores);
        printf("Digite a nota recebida pela critica: ");
        scanf("%f%*c", &v[x].nota);
        printf("\n");
        printf("\tFilme cadastrado com sucesso!\n\n");
        system("pause");
    }
    else
    {
        printf("\t\nQuantidade maxima de filmes ja cadastrada no vetor!\n\n");
        system("pause");
    }
}

void mostraFilmes(struct Filme v[])
{
    int x;
    for (x = 0; x<Tfilmes; x++)
    {
        printf("\n================================================\n");
        printf("\n\tNome do filme: %s", v[x].nome);
        printf("\n\tNome do diretor: %s", v[x].diretor);
        printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
        printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
        printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
        printf("\n================================================\n");
    }

}
void diretorAno(struct Filme v[])
{
    char nomeDiretor[T];
    int x, pesquisaAno, nomeDiretorIgual;
    printf("Digite o nome do diretor para pesquisa: ");
    gets(nomeDiretor);
    printf("Digite a data de lancamento desejada: ");
    scanf("%d%*c", &pesquisaAno);
    for (x = 0; x<Tfilmes; x++)
    {

        nomeDiretorIgual = strcmp(nomeDiretor, v[x].diretor);
        if (nomeDiretorIgual == 0 && pesquisaAno == v[x].anoLancamento)
        {
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
            printf("\n\tNome do filme: %s", v[x].nome);
            printf("\n\tNome do diretor: %s", v[x].diretor);
            printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
            printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
            printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
            system("pause");
        }
        else
        {
            printf("\t\nDiretor e data de lancamento nao encontradas, por favor tente novamente.\n\n");
            system("pause");
        }
    }

}
void nomesFilme(struct Filme v[])
{
    char nome[T];
    int x, filmeIgual;
    char filmePesquisa[Tfilmes];
    printf("Digite o nome do filme para pesquisa: ");
    gets(filmePesquisa);
    for (x = 0; x<Tfilmes; x++)
    {
        filmeIgual = strcmp(filmePesquisa, v[x].nome);
        if (filmeIgual == 0)
        {
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
            printf("\n\tNome do filme: %s", v[x].nome);
            printf("\n\tNome do diretor: %s", v[x].diretor);
            printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
            printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
            printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
            system("pause");
        }
        else
        {
            printf("\t\nFilme nao encontrado.\n\n");
            system("pause");
        }
    }

}
int menu()
{
    int z;
    printf("\n================================================\n");
    printf("\n\n\t\tMENU:\n");
    printf("\n\tDigite a opcao desejada:\n");
    printf("\n\t(1) Cadastrar Filme \n");
    printf("\n\t(2) Pesquisar por ano e diretor \n");
    printf("\n\t(3) Pesquisar por nome do filme \n");
    printf("\n\t(4) Lista todos os filmes cadastrados \n");
    printf("\n\t(5) Sair\n\n");
    printf("\n================================================\n");
    scanf("%d%*c", &z);
    system("cls");
    return z;
}
int main()
{
    int x = 0;
    int op;
    struct Filme filmes[Tfilmes];
    do
    {
        op = menu();
        switch (op)
        {
        case 1:
            cadastraFilmes(filmes, x);
            x++;
            system("cls");
            break;
        case 2:
            diretorAno(filmes);
            system("cls");
            break;

        case 3:
            nomesFilme(filmes);
            system("cls");
            break;
        case 4:
            mostraFilmes(filmes);
            system("cls");
            break;
        case 5:
            system("pause");
            break;
        default:
            printf("\n\tOpcao invalida, tente novamente.\n");
            break;
        }
    } while (op != 5);

    return 0;
}

Comment: Percebi que você é novo e que tem boas intenções no site, mas recomendo que antes de responder algumas perguntas, dê uma olhada em [ask] e [answer].
Comment: ok vou ja ler o codigo
Comment: Obrigado ainda principiante no site
Comment: Deu certo Claudio, muito grato, estava declarando como int a variavel string, mas agora a case 4 parou de funcionar, nada acontece quando a digito, editei o codigo e comentei todo ele pra ficar mais claro, mas mais uma vez obrigado!
Comment: queres que arranje a case 4 ??
Comment: Na realidade, queria uma ajuda do que esta acontecendo com meu vetor no case 4 pois antes funfava e agora nada fica nao respondendo tambem, ela só mostra o vetor preenchido, agora como arrumei a case 3, nao sei por que parece que nao tem nada armazenmado no vetor, mas esta preenchendo certo a case 1
Comment: @Claudio ao invés de escrever em outra resposta, é recomendável que você edite esta.
Answer: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
#define T 51
#define Tfilmes 2

struct Filme
{
    char nome[T];
    char diretor[T];
    int anoLancamento, quantAtores;
    float nota;
};
void cadastraFilmes(struct Filme v[], int x)
{
    if (x < Tfilmes)
    {
        printf("Digite o nome do filme: ");
        gets(v[x].nome);
        printf("Digite o nome do diretor: ");
        gets(v[x].diretor);
        printf("Digite o ano do lancamento do filme: ");
        scanf("%d%*c", &v[x].anoLancamento);
        while (v[x].anoLancamento < 2010)
        {
            printf("\nSo podem ser cadastrados filmes lancados a partir de 2010, tente novamente!\n");
            printf("\nDigite o ano do lancamento do filme: ");
            scanf("%d%*c", &v[x].anoLancamento);
        }
        printf("Digite a quantidade de atores: ");
        scanf("%d%*c", &v[x].quantAtores);
        printf("Digite a nota recebida pela critica: ");
        scanf("%f%*c", &v[x].nota);
        printf("\n");
        printf("\tFilme cadastrado com sucesso!\n\n");
        system("pause");
    }
    else
    {
        printf("\t\nQuantidade maxima de filmes ja cadastrada no vetor!\n\n");
        system("pause");
    }
}

void mostraFilmes(struct Filme v[])
{
    int x;

    for (x = 0; x<Tfilmes; x++)
    {
        printf("\n================================================\n");
        printf("\n\tNome do filme: %s", v[x].nome);
        printf("\n\tNome do diretor: %s", v[x].diretor);
        printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
        printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
        printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
        printf("\n================================================\n");
        system("pause");
    }

}
void diretorAno(struct Filme v[])
{
    char nomeDiretor[T];
    int x, pesquisaAno, nomeDiretorIgual;
    printf("Digite o nome do diretor para pesquisa: ");
    gets(nomeDiretor);
    printf("Digite a data de lancamento desejada: ");
    scanf("%d%*c", &pesquisaAno);
    for (x = 0; x<Tfilmes; x++)
    {

        nomeDiretorIgual = strcmp(nomeDiretor, v[x].diretor);
        if (nomeDiretorIgual == 0 && pesquisaAno == v[x].anoLancamento)
        {
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
            printf("\n\tNome do filme: %s", v[x].nome);
            printf("\n\tNome do diretor: %s", v[x].diretor);
            printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
            printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
            printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
            system("pause");
        }
        else
        {
            printf("\t\nDiretor e data de lancamento nao encontradas, por favor tente novamente.\n\n");
            system("pause");
        }
    }

}
void nomesFilme(struct Filme v[])
{
    char nome[T];
    int x, filmeIgual;
    char filmePesquisa[Tfilmes];
    printf("Digite o nome do filme para pesquisa: ");
    gets(filmePesquisa);
    for (x = 0; x<Tfilmes; x++)
    {
        filmeIgual = strcmp(filmePesquisa, v[x].nome);
        if (filmeIgual == 0)
        {
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n");
            printf("\n\tNome do filme: %s", v[x].nome);
            printf("\n\tNome do diretor: %s", v[x].diretor);
            printf("\n\tAno de lancamento do filme: %d", v[x].anoLancamento);
            printf("\n\tQuantidade de atores: %d", v[x].quantAtores);
            printf("\n\tNota recebida pela critica: %.2f\n", v[x].nota);
            printf("\n=================DIRETOR E DATAS DE LANCAMENTOS ENCONTRADOS===========================\n\n");
            system("pause");
        }
        else
        {
            printf("\t\nFilme nao encontrado.\n\n");
            system("pause");
        }
    }

}
int menu()
{
    int z;
    printf("\n================================================\n");
    printf("\n\n\t\tMENU:\n");
    printf("\n\tDigite a opcao desejada:\n");
    printf("\n\t(1) Cadastrar Filme \n");
    printf("\n\t(2) Pesquisar por ano e diretor \n");
    printf("\n\t(3) Pesquisar por nome do filme \n");
    printf("\n\t(4) Lista todos os filmes cadastrados \n");
    printf("\n\t(5) Sair\n\n");
    printf("\n================================================\n");
    scanf("%d%*c", &z);
    system("cls");
    return z;
}
int main()
{
    int x = 0;
    int op;
    struct Filme filmes[Tfilmes];
    do
    {
        op = menu();
        switch (op)
        {
        case 1:
            cadastraFilmes(filmes, x);
            x++;
            system("cls");
            break;
        case 2:
            diretorAno(filmes);
            system("cls");
            break;

        case 3:
            nomesFilme(filmes);
            system("cls");
            break;
        case 4:
            mostraFilmes(filmes);
            system("cls");
            break;
        case 5:
            system("pause");
            break;
        default:
            printf("\n\tOpcao invalida, tente novamente.\n");
            break;
        }
    } while (op != 5);

    return 0;
}

Comment: Nesta Resposta o case 4 mostra todos os dados do vetor que antes nao dava.
Comment: O que este código tem de diferente da outra resposta? Por que não editar a que você já respondeu?
Comment: Não vejo a necessidade de uma nova resposta pra uma alteração tão pequena. Seria melhor editar o código da outra.
Comment: Entendi o system pause Claudio, porém ela tem que quando ser utilizado o case 4, mostrar TODOS os filmes de uma vez só, e o system pause vai fazer com que eu tenha que ficar apertando alguma tecla para que mostre o proximo filme cadastrado entende

Erro no procedimento case 3


Azure function created by Java is saying "Your app is currently in read only mode because you are running from a package file" , how to resolve it?

Question: Currently, I'm working on Azure function created by Java. I am able to publish Java function to Azure portal and I'm able to make a GET and POST request but I'm having issue with enabling function in write mode. So, what I am supposed to do to resolve this issue?
Answer: This is expected behavior when your function app is deployed in Run From Package mode, which means it's reading the files directly from the uploaded ZIP and so there's no way to edit it.
You can turn that off by deleting the WEBSITE_RUN_FROM_PACKAGE application setting in the portal.
Note: This will clear your function app until the next time you publish if you delete the setting.
For more details, Please check here.
Comment: Thank you so much for your reply. I was thinking that if I can enable function in write mode then I can configure input and output trigger from Azure portal. Now, I have found some other ways to manage the input and output operations from Azure functions.


Error exponent in hypothesis testing

Question: In hypothesis testing, one must decide between two probability distributions  $P_1(x)$ and $P_2(x)$ on a finite set $X$, after observing $n$ i.i.d. samples $x_1,...,x_n$ drawn from the unknown distribution. Let $A_n\subseteq X^n$ denote the chosen acceptance region for $P_1$.
The error probabilities of type I and II can be expressed thus
$$ \alpha_n = P^n_1(A^c_n)$$
$$ \beta_n = P^n_2(A_n)$$
(Cover & Thomas, Ch. 11 is an excellent reference for the definitions and facts mentioned in this post).
Assume we have chosen the acceptance regions $A_n$'s ($n\geq 1$), so that both error probabilities approach zero as the number of observations grows: $\alpha_n\rightarrow 0$ and $\beta_n\rightarrow 0$ as $n\rightarrow \infty$.  Stein's Lemma tells us that  the maximum rate of deacrease of both error probabilities is determined, to the first order of the exponent, by the the  KL-distance between the given distributions. More precisely
$$ -\frac 1 n \log \alpha_n \rightarrow D(P_2||P_1)\tag{1}$$
$$ -\frac 1 n \log \beta_n \rightarrow D(P_1||P_2)\tag{2}$$
Now, consider the Bayesian version of the hypothesis testing problem. In this case, $P_1$ and $P_2$ are given prior probabilities $\pi_1$ and $\pi_2$, respectively, and the error probability is obtained by weighting $\alpha_n$ and $\beta_n$:
$$ e_n = \pi_1\alpha_n + \pi_2\beta_n.\tag{3}$$
In this case, the optimal exponent for $e_n$ is given by Chernoff distance between the given distributions:
$$  -\frac 1 n \log e_n \rightarrow C(P_1,P_2).$$
Question: what is wrong in the reasoning below? (Disclaimer: I'm not trying to be fully formal/detailed here).
By (3), the decrease rate of $e_n$  is the minimum deacrease rate of $\alpha_n$ and $\beta_n$:
$$  \lim -\frac 1 n \log e_n = \min\{\lim -\frac 1 n \log \alpha_n, \lim -\frac 1 n \log \beta_n\}$$.
Since $e_n\rightarrow 0$, one must have  both $\alpha_n\rightarrow 0$ and $\beta_n\rightarrow 0$ as $n\rightarrow \infty$. So, by the previous considerations on Stein's Lemma, and (1) and (2), one would get
$$  \lim -\frac 1 n \log e_n = \min\{D(P_1||P_2), \,\,D(P_2||P_1)\}$$
which is quite different from $C(P_1,P_2)$.
EDIT: I realize that now that (1) and (2) cannot hold simultaneously, for the same regions $A_n$'s, so this must be the bug in the reasoning.
What one can infer through a similar reasoning is just, I think,
$$C(P_1,P_2)\leq \min\{D(P_1||P_2), \,\,D(P_2||P_1)\}.$$
Answer: Essentially, the answer to your question is that the behavior of $\alpha_n$ and $\beta_n$ is somewhat different when the Bayesian minimum-error-probability rule is used and one is trying to minimize $e_n$.  This is
because the decision regions $A_n$ and $A_n^c$ are different.  In contrast to your (1) and (2), the behavior is of the form
$$\begin{align*}
-\frac{1}{n}\log \alpha_n &\rightarrow D(P_\lambda||P_1)\\
-\frac{1}{n} \log \beta_n &\rightarrow D(P_\lambda ||P_2)
\end{align*}$$
so that
$$
\lim -\frac{1}{n} \log e_n = \min\{D(P_\lambda||P_1), \,\,D(P_\lambda||P_2)\}.
$$
Since $D(P_\lambda||P_1)$ is an increasing function of $\lambda$
while $D(P_\lambda||P_2)$ is a decreasing function of $\lambda$,
choosing $\lambda$ such that $D(P_\lambda||P_1)=D(P_\lambda||P_2)$
gives $C(P_1,P_2)$.
All this is described in Chapter 12
of the first edition of Cover and Thomas. Has it been deleted in
the second edition since you refer us to Chapter 11 of Cover and Thomas?
Comment: @Elvis: The distributions are over a common discrete set. $P_\lambda$ should just indicate a convex mixture of $P_1$ and $P_2$ with one of them having weight $\lambda$ and the other (obviously) $(1-\lambda)$. In this case, the mixture should correspond to the prior probabilities.
Comment: @Elvis: The definition of $P_\lambda$, for $\lambda\in [0,1]$, is, for each $x\in X$: $$P_\lambda(x) = \frac{P^\lambda_1(x)P^{1-\lambda}(x)}Z$$ where $Z$ is a normalization factor. Chernoff information $C(P_1,P_2)$ is $D(P_{\lambda^*}||P_1)$, for the (unique) $\lambda^*\in [0,1]$ s.t. $$D(P_{\lambda^*}||P_1)=D(P_{\lambda^*}||P_2)$$ (cf. p. 378--380 of Cover-Thomas, 2/e).
Comment: @Dilip: Many thanks, I think I got the point now. Concerning my reasoning as exposed in my post: I realized that in (non Bayesian) hypothesis testing, one in general cannot have _both_ error probabilities decrease at maximum rate, in other words, it appears that (1) and (2) cannot hold simultaneously for the same regions $A_n$. Concerning Cover-Thomas, in the 2nd edition Ch. 11 deals with hypotesis testing. The derivation of the optimal exponent for Bayesian h.t. (Chernoff inf.) is the one you outlined in your answer (so the definition of $P_\lambda$ is there, @Elvis).
Comment: @Michele Thanks, this is very nice. Welcome to the site!
Comment: I only have the first edition, but a look at Amazon appears to show that the order of Chapters 11 and 12 got swapped in the second edition.
Comment: I don't get what are $\lambda$ and $P_\lambda$, and their relationship with $A_n$. Can you develop or refer me to a textbook?
Comment: Grazie @Michele, if no more details are provided here I'll try to find a copy of the book. Is that a mixture of $P_1$ and $P_2$? I'm asking because as we don't have a full family of distributions $P_\theta$ with $\theta\in\Theta$, I don't see were this $P_\lambda$ can come from. But if it bother you to develop here, no worries, I'll find the book. I so need to read :)

Error exponent in hypothesis testing


View Field, Insert View, View Reference, Block Reference, Insert Block: which to choose to embed a view in a page

Question: I have a view I would like to embed in a page with some other content. The page is for logged-in users only. I could make a page or a block version of the view. I could make a new content type or not for the page- it's not a big deal. So I could use Viewfield, Insert View, View Reference, Block Reference, Insert Block, EVA, and maybe some others to embed the view. I could even code a page template up with views_embed_view(), though I would prefer to use an existing module for ease of future maintenance. Using the view's header and footer fields is inadequate in this case, because I want the surrounding content to be easily editable?
Are there technical reasons to choose one of these modules over the others? For instance, do any of them have issues with caching or permissions? Or, for instance, Is there a reason not to use the view as a block?
Answer: Option 1:
Just create a page for the view.
You can set which permission or role should have access to the page.
If you need to display content above or below the view use the header and footer.
Option 2
Use hook_node_view() and views_embed_view() to add the view as a field to the node you want to target:
function hook_node_view($node, $view_mode, $langcode) {

  // Add whatever logic you want here to only target the nodes you want
  if($some_check == TRUE) {
    // Add a new field to the content array
    $node->content['view_field'] = array(
      // Render you view
      "#markup"=> views_embed_view('view_name', 'view_display'),
    );
  }
}

You say it's better to not write PHP for maintenance reasons. I would argue the exact opposite - it's much easier to version control code than it is configuration stored in the DB.
Comment: I have added view header and footer content before, but in this case there's a lot of extra content which I'd like to be editable without editing the view. As for adding PHP, I'm fine with coding, but I try to avoid adding custom code when an existing module will suffice. So I'm asking for a comparison of the modules. Sorry I wasn't clearer.
Comment: @DanHalbert - Ok, I see your point. In that case what about [EVA](https://www.drupal.org/project/eva) or [Insert View](https://www.drupal.org/project/insert_view)
Comment: EVA is yet another choice - thanks - I added it in the question. Given all the modules I listed in the question, is there some reason to choose one over the other? For instance, do some inhibit caching, or not handle permissions properly? Or is one conceptually better? I am faced with wood screws, machine screws, nails, glue, etc. Which one is the best choice for this situation? Or is it just twelve kinds of peanut butter?
Comment: I've not got experience with any of those modules. If I was you I would install each of them and have a quick play and see how well it does what you want. Then just pick the best one. I'm not sure if your going to find someone here who is able to tell you which is best, and even then what may be best for their exact use case may differ from yours...


Generate sample data from Gaussian mixture model

Question: I am given the values for mean, co-variance, initial_weights for a mixture of Gaussian Models. Now how can I generate samples given those:
In brief, I need a function like
<code>X = GMMSamples(W, mu, sigma, d)
</code>
where W: weight vector, mu - mean vector, sigma - covariance vector, d - dimensions of samples
How can I implement it in python ? I found scipy library that has GaussianMixture library. It basically takes input as sample values and calculate itself mean, co-variance. But for my case it is almost reverse. I am given mean, co-variance, and parameters mentioned above and I need to generate sample data values.
Thank you.
Comment: Note that asking for code is off topic here.
Answer: Sampling from mixture distribution is super simple, the algorithm is as follows:

Sample $I$ from categorical distribution parametrized by vector $\boldsymbol{w} = (w_1,\dots,w_d)$, such that $w_i \ge 0$ and $\sum_i w_i
 = 1$.
Sample $x$ from normal distribution parametrized by $\mu_I$ and $\sigma_I$.

This thread on StackOverflow describes how to sample from categorical distribution.
Comment: Tim, can you please elaborate  more ?
Comment: What is unclear for you?
Comment: Sample I from categorical distribution means what ? What is the role of value I ?
Comment: @Shyamkkhadka Actually I found other thread that asks about exactly the same thing http://stats.stackexchange.com/questions/226834/sampling-from-a-mixture-of-two-gamma-distributions/226837#226837 , so please check it as it is a duplicate of your question.
Comment: @Shyamkkhadka the idea of a mixture is that you have $d$ components, each appearing with probability $w_i$, so $I$ is a way of saying "take $I$-th component with probability $w_i$", what follows from the definition of mixture distribution.
Comment: Ok. But in second step your mentioned algorithm that I-th component is not used anymore . I have to implement it in a code. Can you please elaborate more the algorithm ?
Comment: @Shyamkkhadka it *is* used since you sample from the $N(\mu_I,\sigma_I)$ distribution, i.e. from the distribution of $I$-th component that has mean $\mu_I$ and sd $\sigma_I$. You can check the linked thread for a code example
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/47763/discussion-between-shyamkkhadka-and-tim).


seg-faulting when trying to enqueue in priority queue in C

Question: void enQ(int* q, int value){
    if(q[0] == -1){
        q[0] = value;
        q[1] = -1;
        return;
    }
    int found = 0;
    int last_index;
    int count = 0;
    while(q[count] != -1){
        count++;
    }
    last_index = count;
    int i = 0;
    while(q[i] != -1){
        if(q[i] < value){
            int j = last_index;
            while(j != i){
                q[j+1]=q[j];
                j--;
            }
            q[i]=value;
            found = 1;
            break;
        }
    }
    if(found == 0){
        q[last_index] = value;
        q[last_index+1] = -1;
}
}

int main(int argc, char* argv[])
{
    int* q;
    q[0] = -1; // initialize queue by making first element of new queue -1...
    enQ(q,1);
}

I made a simple priority queue in C.  The problem is that when I call enQ on an int*, the program segfaults.  I have no idea why.  How do I fix the segfault?
Answer: You are using an uninitialized pointer, meaning it will point to a random location. Either declare q as an array, e.g.
int q[10];

Or dynamically allocate memory for it:
int *q = malloc(sizeof(int) * 10);

Both of these create space for ten values (index 0 to 9).
Also in the last case, where you dynamically allocate the memory, you have to remember to free the memory when you're done with it.

You might also want to keep track of the size, so you don't queue to many items.
Comment: So, I replaced the int* q with  int *q = malloc(sizeof(int) * 128);, but when I call enQ and add ONE item it segfaults again.  I really don't get why it's still doing it.


Laravel 5.3 : 2 same relationships for 2 same Tables

Question: i need help for make something  : I have 2 table :
<code>- Users
----------
id_user

 - Sports
----------
id_sport

title_sport
</code>
User can practice 1 or more sport.
User can search user who practice 1 or more sport.
Can you help me please for the model User?
Comment: It looks as a [`many-to-many`](https://laravel.com/docs/5.3/eloquent-relationships#many-to-many). Please read the docs for more info https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
Comment: Thank you for your comment , i am agree with the many to many relationships but can have 2 same relation in my model?
Comment: You can use as many as relations in your model. But the question is why you need it and what is the use-case of it.
Answer: Can i use something like this ?

<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    public function pratice()
    {
        return $this->belongsToMany('App\Sport');
    }
   public function search_user()
    {
        return $this->belongsToMany('App\Sport');
    }
}
</code>
with 2 pivots table.


How can I determine if two features, given a set of data, are the same feature or not?

Question: Thanks in advance for the help.
Suppose I have a set of data of the form [feature, rating].  For the sake of argument lets assume feature can be movie A or movie B and rating is a ranked, continuous value on the interval [0,100].  Suppose also that the data set is very large.  In reality I have several more features but I intend to isolate each pair of features so I believe this is a comparable example (still one rating though).
Under the naive assumption that having equal ratings implies features are the same, how might I be able to determine if feature A and B are different or the same ( I acknowledge it may not be possible to determine either).  Given that I know the standard deviation of how ratings are assigned (suppose I have a user or set of users that assign the scores and I know the std of the ratings they give), how might I go about this?
I apologize if I put the wrong tags on this question, I'm not sure what this should go under.
Answer: What you are doing is clustering.  That is a tag.
I would consider using a 1d gaussian mixture model to cluster on the ratings, and assume that when a particular point has higher probability of being from one member than any other, it is the same.
Moving ratings are horribly over-discretized, and are going to do a poor job of helping you classify things as being similar.
Links:

http://www.mathworks.com/help/stats/discriminant-analysis.html
http://www.mathworks.com/discovery/cluster-analysis.html
https://stats.stackexchange.com/questions/tagged/clustering


C# - How to 3D stack objects in a 3 dimensional space?

Question: The purpose of my algorithm is to stack containers on a ship.
I will explain how I modelled my 3D space to make the question more clear.
A ship has a container table. The container table contains container rows.
public class ContainerTable : IContainerTable
{
    public List<IContainerRow> Rows { get; set;}

    public ContainerTable()
    {
        Rows = new List<IContainerRow>();
    }
}

The index of the container row list determines the column of the container table and each column has a container stack.
public class ContainerRow : IContainerRow
{
    public List<IContainerStack> ContainerStack { get; set; }

    public ContainerRow()
    {
        ContainerStack = new List<IContainerStack>();
    }
}

The container stack determines the containers stacked vertically from bottom to top.
public class ContainerStack : IContainerStack
{
    public List<IContainer> Containers { get; set; }
    public int WeightOfStack { get; set; }

    public ContainerStack(List<IContainer> containers)
    {
        Containers = containers;
    }
}

The algorithm auto generates a table based on the ship length and ship width.
public IContainerTable GetNewContainerTable(int shipLength, int shipWidth)
{
    IContainerTable table = new ContainerTable();

    for (int i = 0; i < shipLength; i++)
    {
        IContainerRow row = ContainerRow();
        table.Rows.Add(row);

        for (int j = 0; j < shipWidth; j++)
        {
            IContainerStack stack = ContainerStack();
            table.Rows[i].ContainerStack.Add(stack);
        }
    }
    return table;
}

Here is where I ran into problems.
The algorithm loops through each row and adds a container to each column. It repeats from the beginning if there are still containers left.
public IContainerTable AssignContainersToShip(List<IContainer> containers)
{
    //Represents the unsorted container list index.
    int i = 0;
    //Represents the table column
    int j = 0;

    while (i < containers.Count)
    {
        //Loop through each row.
        foreach (var row in _table.Rows)
        {
            //Loop through each column
            foreach (IContainerStack stack in _table.Rows[j].ContainerStack)
            {
                stack.Containers.Add(containers[i]);
                i++;
                //Go to the next column.
                if (j < _table.Rows.Count - 1)
                {
                    j++;
                }
                //Start from the first column when looping through the second row.
                else
                {
                    j = 0;
                }
            }
        }
    }
    return _table;
}

Expected behaviour:
So, if we assume that the ship has a 2x2 table a input of 4 containers the result should be:
Row 1:
 - Column 1: Container 1
 - Column 2: Container 2
Row 2:
 - Column 1: Container 3
 - Column 2: Container 4
Actual Result:
Row 1:
 - Column 1: Container 1, Container 3
 - Column 2: Container 2, Container 4
Row 2:
 - Column 1: Empty
 - Column 2: Empty
I'm a bit lost with this result. The algorithm only stacks containers on the first row and I want it to divide the containers equally over each ship row. What did I do wrong?
Comment: You set j to 0 always inside the inner loop; don't you need an `if` there?
Answer: public IContainerTable AssignContainersToShip(List<IContainer> containers)
{
    //Represents the unsorted container list index.
    int i = 0;
    //Represents the table column
    int j = 0;

    while (i < containers.Count)
    {
        //Loop through each row.
        foreach (var row in _table.Rows)
        {
            //Loop through each column
            foreach (IContainerStack stack in _table.Rows[j].ContainerStack)
            {
                stack.Containers.Add(containers[i]);
                i++;
            }
            j++;
        }
    }
    return _table;
}


VS 2010: How to make button disabled after deleting from the text box?

Question: In Visual Studio 2010, i want that the button will be disabled if there is nothing in the text box.
It is started as disabled and becomes enabled when i'm typing something in the text box.
But when I'm deleting everything from the text box, it is still enabled.
this is what I've done:
    public Form1()
    {
        InitializeComponent();
        button1.Enabled = false;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text == null)
        {
            button1.Enabled = false;
        }
        else
        {
            button1.Enabled = true;
        }
    }

Any suggestions?
thanks!
Answer: The line
if (textBox1.Text == null)

should be
if (textBox1.Text == string.Empty)

The Text property will not be null (which generally is taken to mean the absence of any value), but rather string.Empty, which represents a string of zero length.
A shorter way to write this is:
button1.Enabled = (textBox1.Text != string.Empty);

Comment: Eric, nice call.  I posted the same shorter implementation before realizing you already had.
Comment: or, button1.Enabled = !string.IsNullOrEmpty(textBox1.Text)
Comment: @Phil: Not that it is likely to ever matter for a WinForms app, but string.IsNullOrEmpty does an extra, unnecessary check for null :-)


How to update a key/value pair in a nested array of objects in Javascript

Question: this is my data structure:
[
    0:
        key1: value,
        key2: value,
        array:
            0:
                thisId: xxxxx,
                thisValue: value,
            1:
                notThisId: someId,
                notThisValue: value,
        key3: value
    1:
        key1: value
        key2: value
        array:
            0:
                anotherId: id
                anotherValue: value
        key3: value
]

Hello, I have a query with is returning:
thisIdRef: xxxxx,
thisNewValue: newValue

Is it possible to update the nested 'thisValue' to 'thisNewValue' where 'thisIdRef' is equal to 'thisId', or 'xxxxx'?
I have done something similar below using findIndex and splice, but this is for a non-nested key/value pair and I can't work out how to find a nested id, or indeed if it's possible.
let newArray = oldArray;
const index = newArray.findIndex(post => post._id === editedPostId)
newArray.splice(index, 1, {
    ...newArray[index],
    post: editedContent
})

Any help very much appreciated.
Comment: Why is this tagged with `reactjs`. There is nothing specific to reactjs in this question.
Comment: Your array is not valid. Please check it and add valid array
Comment: Array item 1 = [0], array item 2 = [1] etc.. It's literally from the console log
Comment: The console log does not output valid JS. You should enter the structure in JavaScript syntax.
Answer: I will assume you want to create a new array, such that the original array and its nested structure is not mutated.
Here is a function that you could use:

function setDeep(original, editedPostId, editedContent) {
    return original.map(obj => {
        let i = obj.array.findIndex(item => item.thisId === editedPostId);
        if (i == -1) return obj;
        return {
            ...obj,
            array: Object.assign([], obj.array, {
                [i]: {
                    ...obj.array[i],
                    thisId: editedPostId,
                    thisValue: editedContent
                }
            })
        };
    });
}

// Example call
let original = [{
    key1: 1,
    key2: 2,
    array: [{
        thisId: "xxxxx",
        thisValue: 3,
    }, {
        notThisId: "yyyy",
        notThisValue: 4,
    }],
    key3: 5
}, {
    key1: 6,
    key2: 7,
    array: [{
        anotherId: "zzzzz",
        anotherValue: 8
    }],
    key3: 9
}];

let editedPostId = "xxxxx";
let editedContent = 42;

console.log(setDeep(original, editedPostId, editedContent));

Note that the code you have given for a non-nested structure seems to create a new array, but it still mutates the original array. When you want the original to remain in tact, you have to take care to deep-copy the parts that are affected.
Answer: The general form would be:
const found = parentArray.find(it => it.array[0] === theId)
if (found) {
   found.array[1] = theValue
}


Letters in a string double unexpectedly

Question: I'm making myself a Hangman game and basically the only problem I'm having is that the letters are doubling each time i guess a new letter. For example, if the word is "Hello World" and i guessed "l" it would print
"_ _ l l _  _ _ _ l _", right, and then if I guess "w" next, it prints "H _ _ _ l _ l _ _ _  _ _ _ _ _ _ l _ _ _" (which is hheelllloo wwoorrlldd).
My code is shown below. My thought is that it's because I have a nested for loop, but I wouldn't know how else I could go about doing this.
// This checks previous letters given through String guessedlet.

for(int spot = 0; spot < wrd[0].length(); spot++)
{
    for (int spot2 = 0; spot2 <= guessedlet.length() - 1; spot2++)
    {
        char Spot = wrd[0].charAt(spot);
        String wordletter = Character.toString(Spot);
        char Spot2 = guessedlet.charAt(spot2);
        String guessedletter = Character.toString(Spot2);
        for(int spot3 = 0; spot3 < guessedlet.length(); spot3++)
        {
            char Spot3 = guessedlet.charAt(spot3);
            String guessedletter2 = Character.toString(Spot3);
            if(letter.equals(guessedletter2))
            {
                break;
            }
        }
        if(guessedletter.equals(wordletter))
        {
            wordletter = guessedletter;
        }
        else if(guessedletter.equals(" "))
        {
            wordletter = "";
        }
        else if(!(guessedletter.equals(wordletter)))
        {
            wordletter = "_";
        }
        out.print(wordletter + " ");
    }
}

Why are the letters being duplicated?
Comment: Debug and step through your code or sprinkle your code with `System.out.println`s to find out exactly when the string changes and why.
Comment: You mean, like the title where the word "when" is doubled?
Comment: Why do you have two outer loops? That's probably what is causing your problem. Just store the guessed letters in a `Set`, then loop the sentence (2 words = sentence), and print the letters that are in the `Set` (using `contains()`).
Comment: If the second guess is `w`, why is it printing `H`?
Comment: Try my answer see if it works...I tried to simplify it also.
Comment: Andreas - because String quessedlet() is the guessed letters, so w and h, so it goes through that and picks out each letter
Answer: You need to move your output outside of the inner loop like this:
for(int spot = 0; spot < wrd[0].length(); spot++)
{
    String tempDisplay = "_";
    for (int spot2 = 0; spot2 <= guessedlet.length() - 1;      spot2++)
    {
        char Spot = wrd[0].charAt(spot);
        String wordletter = Character.toString(Spot);
        char Spot2 = guessedlet.charAt(spot2);
        String guessedletter = Character.toString(Spot2);
        for(int spot3 = 0; spot3 < guessedlet.length(); spot3++)
        {
            char Spot3 = guessedlet.charAt(spot3);
            String guessedletter2 = Character.toString(Spot3);
            if(letter.equals(guessedletter2))
            {
                break;
            }
        }
        if(guessedletter.equalsIgnoreCase(wordletter))
        {
            tempDisplay = guessedletter;
            break;
        }
    }
    out.print(tempDisplay + " ");
}

You only want to output once for each character in wrd[0]...

Letters in a string double unexpectedly


Can someone provide the intuition as to why least squares and MLE lead to the same coefficient estimates for linear regression?

Question: In books, I am seeing that the estimates for a linear regression are the same whether you do least squares estimation or maximum likelihood estimation (with certain assumptions).
I am not understanding how this is true.  Let's say the TRUE distribution of Y | X is something that is extremely non normal.  Least squares estimation makes no assumption on the distribution of Y | X, so you you can easily determine the coefficients for the equation.
Now, let's say you are a novice data scientist, and decide to estimate coefficients using MLE while making the assumption that Y | X is normal and has constant variance, even though the true distribution is very non-normal.
You are telling me that our coefficient estimates will be the same in both situations, as long as you make the assumption that the data is normal, even if it is not normal?
How does that work?
Comment: Because the maximum likelihood metric with  normal noise is mean  squared error... just like maximising Exp - (x-y)^2 is equivalent to minimising ( x-y)^2
Answer: You can think of maximum likelihood as an algorithm, just like least square. If you examine the maths behind the two algorithms, you will find that in the case where you assume normality, it is the same as least squares. Note that if the data is not normal, then that doesn't affect the validity or unbiasedness of your estimate, since ML is equivalent to least squares. However, your inference (confidence intervals, p-values, etc.) would not be accurate.
More generally, applying ML to situations where you know the distributional assumptions are violated is an established method for getting estimates. It's variously referred to estimating equations or pseudolikelihood. There are various ways to derive correct confidence intervals and p-values that are not dependent on the validity of normality.
Answer: The answer from Tim Mak is perfect and brings some further readings about what happens out of the usual distributional assumptions. But I would like to bring another view or intuition on the matter.

You are telling me that our coefficient estimates will be the same in both situations, as long as you make the assumption that the data is normal, even if it is not normal?

Yes and no matter what you assume really. You can always get those parameters, using the very same method of least-square or MLE, with arbitrarily false assumptions. At worst your model fit will be bad (and wrong). People often fit a linear model and look afterwards at the error distribution: if it is not gaussian you might find that a better model is needed.
Intuitively
First, let's remember that the MLE is a bayesian account of linear regression and treats the data themselves as random variables. It gives a probabilistic model of the data, and hence we ought to start with a distribution somewhere (the assumption on the error is a good place to start).
On the other hand, a least-square estimation is a simple approach for parameter estimation, we only assume a model and a measure of errors, parameters are the variable. Gauss himself, by trying to incorporate a probability density on the error of such model came up with the "gaussian" as we can read on the Wikipedia page:

He then turned the problem around by asking what form the density should have and what method of estimation should be used to get the arithmetic mean as estimate of the location parameter. In this attempt, he invented the normal distribution.

In one case (LSE) we find the parameter $\beta$ such as the euclidian distance (equivalently the mean squared error) is minimised. Here we decide to measure the error as the square distance.
In the other (MLE) we expect an error distributed normally around the line $y = \beta x$, which means an error that occurs more or less likely depending on the squared distance between data pairs. Then the parameter estimate that maximizes the probability of our data under this "error expectation" (or assumption) are the same parameters that we found by deciding to take the square distance as our error metric.
It simply is due to how you measure errors or discrepancy between your model (here we say a linear one such as $\beta x$) and your observables ($y$). Both LSE and MLE rely on measuring this as related to the square distance between those, although from a different starting point or way of thinking.
It can be helpful to remember that gaussianity in general "pairs well" with 2-norm errors (or also that laplacian distribution "pairs" with 1-norm errors...).

More maths
If might feel natural to come back to the equations anyway...
The key element is simply that both the classical Least Square Estimate and the Maximum Likelihood Estimation for linear regression (with gaussianity assumption for errors) rely on the square distance between each data point pairs $(y_i, \beta x_i)$ as an error metric or measure of discrepancy between both datasets.

For the least-square perspective, it feels natural to use the euclidian distance to measure how far apart our model $\beta x_i$ and the observable $y_i$ are. So our cost function will be of the form:
$$
\sum_i(y_i - \beta x_i)^2
$$
For the MLE, it is our most uninformative choice to assume a normally distributed error of data around the model mean for a given standard deviation (which is like saying that the error should remain evenly distributed around 0, a nice euclidian symmetry as offered by the square distance we see in the exponential $e^{-1/2(\frac{\epsilon}{\sigma})^2}$). So all we insist on is having a model of $y$ such as:
$$
y = \beta x + \epsilon \\
\text{with}:~~\epsilon \sim \mathcal{N}(0, \sigma)
$$

And this gives us
$$
\implies ~~ y \sim \mathcal{N} (\beta x, \sigma) = \frac{1}{\sqrt{2\pi\sigma}} . e^{-\frac{1}{2}\left(\frac{(y-\beta x)}{\sigma}\right)^2}
$$
Meaning that once again, if we were to find the most likely $\beta$ for such i.i.d. data we end up minimizing $$\sum_i(y_i - \beta x_i)^2$$


Is it possible to randomly sample from single data set (Monte Carlo style) to create new data sets?

Question: Background
I understand Monte Carlo methods only superficially, but I understand you can repeatedly randomly sample, with or without replacement, from your data set to estimate population parameters (and other things?).
Furthermore, I have been trying to understand, and avoid, common problems which occur when well-meaning researchers move back and forth between hypotheses and results.
Question
Can the two concepts be combined to create an infinite number of new data sets? For example, say I have a small data set ($n = 200$) which I split half into an exploration set (training, or whatever you want to call it), and another half for verification (hold-back, or whatever you want to call it). I come up with some hypotheses and / or models based on the first set, then, holding my breath, verify them with the second set.
Now say I'm not happy with the results. Can I then do a Monte Carlo-type manoeuvre and randomly, with replacement, pluck 100 observations from the original data set and consider that as fresh and untainted? Or is this a wild misapplication of the Monte Carlo concept? Is this going to result in a wild increase in spurious results and a guarantee that no one will let me near a statistical package again in my life?
Answer: Background
I am afraid what you describe is the bootstrap method of Efron (1979) and not the generic Monte Carlo method that is not specifically linked with statistics... Check the Wikipedia entry on bootstrap.
Question
The Monte Carlo sample you create by resampling from your data is not "fresh and untainted" since it is a replica of your data (obtained via the empirical distribution). It is useful to get statistical properties of a procedure you built on the original data (like bias, coverage, &tc.), not to create new samples. So I am also afraid the answer is that this proposal is a misapplication of the bootstrap method.


plotting of lines of regressionnof x on y and lines of regression of y on x in MS Excel

Question: I have following data:
x:1 3 5 7 9
y:2 4 5 8 12
I want to plot lines of regression of y on x as well as lines of regression of x on y on the same graph in MS excel. I tried bit it gives only line of regression of y on x.
Any help will be appreciated.
Answer: To get $y$ as a function of $x,$ you first select the $x$ column (including the label cell), then hold down Ctrl while you do the same for the $y$ column. Insert the graph, ask for a trendline, display the $R^2$ value and the equation, and you're done. Then you have to add data to the graph. Right-click the graph and use Select Data... You can add another series, selecting the appropriate $x$ and $y$ columns. Then add a trendline to that as well.


set cookies/headers for webview via code for Win Store App

Question: I want to set cookies for my webview via the code. I know it was not possible in windows phone. But is it now possible in windows 8? Can anyone guide me?
Alternate Option: Can I pass Headers while navigating to a URL in windows 8?
In windows phone
     Navigate(URL, [Flags,] [TargetFrameName,] [PostData,] [Headers])

In Windows 8
     Navigate(Uri source)

Answer: In Windows 8.1 and Windows 10 you can do:
// using Windows.Web.Http;
// using Windows.Web.Http.Filters;

Uri uri = new Uri("http://kiewic.com/your/url/");

HttpCookie cookie = new HttpCookie("fooName", uri.Host, "/");
cookie.Value = "barValue";

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = filter.CookieManager;
cookieManager.SetCookie(cookie, false);

MyWebView.Navigate(uri);

Answer: Sorry but the WebView control won't do that for you.
You can acomplish what you want creating a custom WebRequest with the desired headers, and then call WebView.NavigateToString() with the content of the WebResponse.
Comment: I have done this too but in that case the parameters I set go as post parameter and not as header or cookies. Could you help me with some code? Also the content I receive contains JS functions which throw error. Is it because the JS is not present when I do NavigateToString?


Problemas com PHPMailer e e-mails grandes

Question: Estou com um problema com o envio de e-mails de uma aplicação.
Eu já tentei PEAR_Mail em conjunto com PEAR_Mail_Mime e agora com PHPMailer (o que achei mais legível).
O que esta ocorrendo?
Quando eu envio e-mail de alerta (mensagens geralmente de uns 80 caracteres) o e-mail é enviado sem problemas. Porém quando fui testar com um e-mail de 1000 caracteres, o retorno que tenho é:
2014-06-17 14:35:06     Connection: opened
2014-06-17 14:35:06     SERVER -> CLIENT: 220 _____ ESMTP
2014-06-17 14:35:06     CLIENT -> SERVER: EHLO _____
2014-06-17 14:35:06     SERVER -> CLIENT: 250-_____
250-PIPELINING
250-8BITMIME
250-SIZE 31457280
250 AUTH LOGIN PLAIN
2014-06-17 14:35:06     CLIENT -> SERVER: AUTH LOGIN
2014-06-17 14:35:06     SERVER -> CLIENT: 334 ___
2014-06-17 14:35:06     CLIENT -> SERVER: (*      *)
2014-06-17 14:35:06     SERVER -> CLIENT: 334 ___
2014-06-17 14:35:06     CLIENT -> SERVER: (*      *)
2014-06-17 14:35:07     SERVER -> CLIENT: 235 ok, go ahead (#2.0.0)
2014-06-17 14:35:07     CLIENT -> SERVER: MAIL FROM:<_____>
2014-06-17 14:35:07     SERVER -> CLIENT: 250 ok
2014-06-17 14:35:07     CLIENT -> SERVER: RCPT TO:<_____>
2014-06-17 14:35:07     SERVER -> CLIENT: 250 ok
2014-06-17 14:35:07     CLIENT -> SERVER: DATA
2014-06-17 14:35:07     SERVER -> CLIENT: 354 go ahead
2014-06-17 14:35:07     CLIENT -> SERVER: Date: Tue, 17 Jun 2014 11:35:06 -0300
2014-06-17 14:35:07     CLIENT -> SERVER: To: ______
2014-06-17 14:35:07     CLIENT -> SERVER: From: ______
2014-06-17 14:35:07     CLIENT -> SERVER: Subject: =?iso-8859-1?Q?[______]_1_erro_|_Renova=E7=E3o_autom=E1tica?=
2014-06-17 14:35:07     CLIENT -> SERVER: Message-ID: <____@_______>
2014-06-17 14:35:07     CLIENT -> SERVER: X-Priority: 3
2014-06-17 14:35:07     CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.8 (https://github.com/PHPMailer/PHPMailer/)
2014-06-17 14:35:07     CLIENT -> SERVER: MIME-Version: 1.0
2014-06-17 14:35:07     CLIENT -> SERVER: Content-Type: text/plain; charset=iso-8859-1
2014-06-17 14:35:07     CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2014-06-17 14:35:07     CLIENT -> SERVER:
2014-06-17 14:35:07     CLIENT -> SERVER: Segue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=
2014-06-17 14:35:07     CLIENT -> SERVER: =E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:=
2014-06-17 14:35:07     CLIENT -> SERVER: 35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da =
2014-06-17 14:35:07     CLIENT -> SERVER: renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-=
2014-06-17 14:35:07     CLIENT -> SERVER: 17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o l=
2014-06-17 14:35:07     CLIENT -> SERVER: og da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 20=
2014-06-17 14:35:07     CLIENT -> SERVER: 14-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASeg=
2014-06-17 14:35:07     CLIENT -> SERVER: ue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=
2014-06-17 14:35:07     CLIENT -> SERVER: =E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:=
2014-06-17 14:35:07     CLIENT -> SERVER: 06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da ren=
2014-06-17 14:35:07     CLIENT -> SERVER: ova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 =
2014-06-17 14:35:07     CLIENT -> SERVER: 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log =
2014-06-17 14:35:07     CLIENT -> SERVER: da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-=
2014-06-17 14:35:07     CLIENT -> SERVER: 06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue =
2014-06-17 14:35:07     CLIENT -> SERVER: o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o:=
2014-06-17 14:35:07     CLIENT -> SERVER:  2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0A=
2014-06-17 14:35:07     CLIENT -> SERVER: Segue o log da renova=E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=
2014-06-17 14:35:07     CLIENT -> SERVER: =E7=E3o: 2014-06-17 11:35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:=
2014-06-17 14:35:07     CLIENT -> SERVER: 35:06=0ASegue o log da renova=E7=E3o: 2014-06-17 11:35:06=0A=0AContrato: 22=
2014-06-17 14:35:07     CLIENT -> SERVER: 0760 - =DAltimo lancamento n=E3o encontrado
2014-06-17 14:35:07     CLIENT -> SERVER:
2014-06-17 14:35:07     CLIENT -> SERVER: .
2014-06-17 14:35:17     SERVER -> CLIENT:
2014-06-17 14:35:17     SMTP ERROR: DATA END command failed:
SMTP Error: data not accepted.
Message could not be sent.Mailer Error: SMTP Error: data not accepted.2014-06-17 14:35:17       CLIENT -> SERVER: QUIT
2014-06-17 14:35:27     SERVER -> CLIENT:
2014-06-17 14:35:27     SMTP ERROR: QUIT command failed:
2014-06-17 14:35:27     Connection: closed

Apesar do servidor especificar:
250-8BITMIME

Testei forçando base64, e tive o mesmo problema.
O código que estou utilizando para realizar essa request é:
    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->Host = $host;
    $mail->Port = $port;
    $mail->SMTPAuth = true;
    $mail->Username = $username;
    $mail->Password = $password;
    $mail->From = $username;
    $mail->FromName = "________";
    $mail->addAddress($to);

    $mail->isHTML(false);

    $mail->Subject = $this->_subject;
    //$mail->msgHTML($this->_htmlMessage); estou tentando inicialmente apenas com texto

    $mail->Body = $mail->encodeString($this->_txtMessage, 'quoted-printable');
    $mail->SMTPDebug = 3;

            //$mail->Encoding = '8bit'; //ja tentei deixar explicito, ja tentei base64
            //$mail->CharSet = 'utf8'; //ja tentei deixar sem, deixar utf8 e iso8859-1
    if (!$mail->send()){
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
        return false;
    }else{
        return true;
    }

A nível de informação, este é o final do retorno de um e-mail pequeno enviado do mesmo código:
2014-06-17 14:47:03     CLIENT -> SERVER:
2014-06-17 14:47:03     CLIENT -> SERVER: .
2014-06-17 14:47:03     SERVER -> CLIENT: 250 ok 1403016424 qp 30696
2014-06-17 14:47:03     CLIENT -> SERVER: QUIT
2014-06-17 14:47:03     SERVER -> CLIENT: 221 ______
2014-06-17 14:47:03     Connection: closed

Comment: Teste: http://swiftmailer.org
Answer: O $mail->Body com uma quantidade em Kb minimamente elevada falha e dá problemas.
Experimenta passar a mensagem da seguinte forma:
$mail->MsgHTML($this->_txtMessage);

e/ou também:
$mail->AltBody = $this->_txtMessage;

Créditos da resposta para o utilizador @user2270404 nesta resposta no SOEN.
Comment: primeiramente obrigado pela ajuda, mas continua com o mesmo problema, porém agora ele cria uma parte da mensagem HTML e outra somente texto.
Comment: @RodrigoChaves Sim, o MsgHTML é a componente em HTML que segue no email, o AltBody é a componente em "texto alternativo" sem recurso a HTML para os programas cujo suporte a HTML se encontra desactivado ou é inexistente.
Comment: @RodrigoChaves O nome de utilizador é o email? Se sim, o servidor poderá exigir que o `$mail->Username` seja igual ao `$mail->From`.
Comment: $mail->Username já esta igual a $mail->From. Mas acredito que se fosse isso eu não conseguiria nem enviar mensagens pequenas, já tentei setar também com: $mail->setFrom($username, $username); Mas nada ainda :(
Comment: @RodrigoChaves Terás ultrapassado a quota diária? Será que precisas indicar o protocolo de autenticação através do `$mail->SMTPSecure = "ssl";` ou `tls` ou outro?
Comment: @RodrigoChaves Uma causa mais provável poderá ser o _timeout_ da operação, experimenta `$mail->Timeout = 60;` por defeito penso ser 10.
Comment: referente ao tls, ssl. Caso seja especificado o servidor não conecta, mas de toda forma testei em um outro servidor com tls e ocorreu o mesmo problema. Este outro servidor tenho acesso aos logs do postfix, mas não relatou nada incomum além das conexões.
Comment: @chavesfop Viste a questão que falei do `Timeout`? Acho que é a ultima coisa que me ocorreu :/
Comment: Mesmo problema, mas agora exibe no final uma mensagem de timeout do servidor. :/
Comment: @chavesfop Tiveste `timeout` com 60 segundos? Será que o servidor não está "_atolhado_" de trabalho neste momento?
Comment: um dos servidores sou eu que administro, a fila de email geralmente esta sempre vazia. Mas mesmo assim o SMTP iria colocar a mensagem em fila de envio no postfix caso a fila estivesse grande, não?
Comment: Uma coisa é bem evidente, mensagem pequena funciona, mensagem grande não funciona :/
Answer: Consegui enviar as mensagens grandes utilizando:
http://swiftmailer.org/
Ainda não verifiquei a fundo o que aconteceu, e o que ele envia para o servidor.
Portanto a solução do problema foi alterar de Pear_Mail / PHPMailer para swiftmailer.
Obrigado a todos pela ajuda.


how to save a field created by using hooks in database

Question: I added fields mobile no,landline no, using the below code to the form which i created with webform module. when i fill the fields along with two added fields and submit them .i cannot find the two added field in results.how can i make them appear in results.
function search_enhance_form_alter(&$form, $form_state, $form_id) {

if($form_id == 'webform_client_form_2') {
  $form['mobile no'] = array(
  '#type' => 'fieldset',
  '#title' => t('mobile no'),
  '#collapsible' => TRUE,
  '#weight' => 30,
);
$form['mobile no']['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action1.'),
);

$form['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action.'),
  '#title' => t('land line no'),
  '#weight' => 10,
);
}
}

Comment: Have you considered adding those fields through the user interface instead of in custom code? Then all the data saving is handled for you.  Based on the code example you provided I would think you don't need custom code.
Answer: first create submit button
$form['submit_button'] = array(
                '#type' => 'submit',
                '#value' => t('Click Here!'),
                );

when you create submit it calls this function and feilds submitted or updated to your database
function form_try_form_submit($form, &$form_state)
            {
                echo '
';
                var_dump($form_state['values']);
                echo '
';
                $insert=db_insert('DB')
                ->fields
                (
                    array
                    (
                        'phone' => $form_state['values']['phone']
                                 )
                 )
            }

Comment: The OP is altering an existing form. There is not need to add another submission button to the form, since there is one already. Plus, the OP's problem is not seeing the added form fields in the form.


Como verificar se o Termo está contido em String no PHP?

Question: Preciso verificar se uma determinada tag está dentro da string. Eu recebo essa string do banco de dados que vem em forma de tags separadas por vírgula sem espaços conforme está abaixo:
String
canais,proteses,implantes

Termo
proteses

Como verificar com PHP se Termo está contido dentro de String?
Answer: Basta usar a função strpos (ou mb_strpos para strings não ASCII):
$palheiro = 'canais,proteses,implantes';
$agulha   = 'proteses';

$pos = strpos( $palheiro, $agulha );

// exemplo de uso:

if ($pos === false) {
   echo 'Não encontrado';
} else {
   echo 'Encontrado';
}

A função strpos retorna false quando a string não é encontrada, e caso seja encontrada, sua posição numérica.
Importante notar que se a string for encontrada no começo da linha, o retorno será 0, portanto temos que usar a comparação de tipo ( === ou !== ) para diferenciar o false do 0.
Outros exemplos de sintaxe:
$encontrado = ( strpos( $palheiro, $agulha ) !== false );

if ($encontrado) {
   echo 'Encontrado';
} else {
   echo 'Não encontrado';
}

$pos = strpos( $palheiro, $agulha );
if ( $pos !== false) echo 'encontrei!';

$pos = strpos( $palheiro, $agulha );
$encontrei = ( $pos !== false ) ? 'sim' : 'não';
echo $encontrei;

Teste aqui: IDEONE.
Dicas:
Se sua aplicação for trabalhar com dados variáveis, é melhor se garantir e usar um formato que não dê efeitos colaterais caso você tenha palavras parecidas.
Por exemplo:
$palheiro = 'carro,moto,ciclomotor';
$agulha = 'moto';
// encontrado!

$palheiro = 'carro,ciclomotor';
$agulha = 'moto';
// encontrado! Opa! Peraí???

Isto ocorre pela palavra "ciclomotor" conter "moto".
A solução:
Para não precisar usar funções mais complexas, basta usar um pequeno truque:
$palheiro = 'carro,moto,ciclomotor';
$agulha = 'moto';
$pos = strpos( ','.$palheiro.',', ','.$agulha.',' );
// encontrado!

$palheiro = 'carro,ciclomotor';
$agulha = 'moto';
$pos = strpos( ','.$palheiro.',', ','.$agulha.',' );
// não encontrado!

A explicação é simples: adicionando as vírgulas nas "pontas" das duas strings, estampos procurando ,moto,dentro de ,carro,ciclomotor, e eliminando as ambiguidades, sem precisar apelar para funções mais complexas.
stripos()
Como bem lembrado pelo @DanielOmine, se quiser encontrar as palavras independentemente de estarem em maiúsculas ou minúsculas, você pode usar as funções case insensitive stripos() e mb_stripos() (várias funções do PHP tem versão com e sem o i, que é justamente de insensitive). Vale notar que estas funções internas são limitadas em relação a acentuação.
Usando com DB
Se estes dados estiverem vindo de uma base de dados, você pode filtrar isto diretamente no SELECT, temos alguns exemplos aqui no site.
Comment: Esse seu segundo código não funfou comigo!
Comment: @LeandroLobo acredito que agora ta OK, dei uma revisada
Answer: Isso pode ser feito da seguinte forma com expressão regular em PHP:
<?php

$tags = 'canais,proteses,implantes';
$termo = 'proteses';

$pattern = '/' . $termo . '/';//Padrão a ser encontrado na string $tags
if (preg_match($pattern, $tags)) {
  echo 'Tag encontrada';
} else {
  echo 'Tag não encontrada';
}

Ou também usando as funções explode e in_array da seguinte forma:
<?php

$tags = 'canais,proteses,implantes';
$tagsArray = explode(',', $tags);
$termo = 'proteses';

if (in_array($termo, $tagsArray)) {
  echo 'Tag encontrada';
} else {
  echo 'Tag não encontrada';
}

Ou também da seguinte forma:
<?php

$tags = 'canais,proteses,implantes';
$tagsArray = explode(',', $tags);
$termo = 'proteses';

$count = 0;
foreach ($tagsArray as $tag) {
  if ($tag == $termo) {
    $count++;
  }
}

if ($count > 0) {
  echo 'Tag encontrada';
} else {
  echo 'Tag não encontrada';
}


Find the coefficient of $x^3$ in the expansion of $(1+x+x^2)^3$ using Binomial theorem.

Question: Find the coefficient of $x^3$ in the expansion of $(1+x+x^2)^3$
using Binomial theorem.
Comment: What did you get as a result of $(a+b)^3$? Why couldn't you solve?
Comment: This is small enough polynomial that you can just brute force it.
Answer: Every term in the expansion is the result of the product of the three terms $1,x,x^2$ with some exponents and we can achieve $x^3$ as
$$1^0\,x^3\,(x^2)^0\text{ or }1^0\,x^1\,(x^2)^1.$$
These terms appear with counts given by the multinomial coefficient, and
$$n=\frac{3!}{0!\,3\,!0!}+\frac{3!}{0!\,1!\,1!}=7.$$

For information,
$$(1+x+x^2)^3=x^6+3x^5+6x^4+7x^3+6x^2+3x+1.$$
Comment: Can't we solve it by general term method?
Comment: @user608779: what is the "general term method" ?
Comment: Finding its general term
Comment: @user608779: this would be difficult and overkill. The above solution goes straight to the point.
Answer: Hint:
For $x\ne1,$ $$(1+x+x^2)^3=\left(\dfrac{1-x^3}{1-x}\right)^3=(1-x^3)^3(1-x)^{-3}$$
Now use Binomial series to find the coefficient of $x^3$ to  be
$1\cdot$the coefficient of $x^3$ in $(1-x)^{-3}-3\cdot$the coefficient of $x^{3-3}$ in $(1-x)^{-3}$
$$=1\cdot\dfrac{(-3)(-3-1)(-3-2)}{3!}(-1)^3-3\cdot1=\dfrac{3\cdot4\cdot5}{1\cdot2\cdot3}-3$$
Comment: Isn't that more work than direct computation would involve ? Maybe you didn't say enough.
Comment: @YvesDaoust, We are interested in $x^3$ right? Only two terms can contain $x^3$
Comment: IMO, you should elaborate, this won't be obvious to the OP.
Comment: @YvesDaoust, Thanks for tour feedback
Answer: Espress it as a product of three brackets:
$$(1+x+x^2)^3=(\underbrace{1+x+x^2}_{{x^i}})(\underbrace{1+x+x^2}_{{x^j}})(\underbrace{1+x+x^2}_{{x^k}})$$
Note that $i+j+k=3$. The possible triples $(i,j,k)$ are:
$$(0,1,2),(0,2,1),(1,0,2),(1,2,0),(2,0,1),(2,1,0),(1,1,1).$$
Hence, the coefficient of $x^3$ is $7$.


Probability that more than 220 heads appear in 400 coin flips

Question: If I toss 400 fair coins, estimate (to the nearest whole percentage point) the probability that more than 220 heads appear.
Here is my thought process:
This is a binomial variable. We know that $p = 0.5$. Therefore, the mean is 200 ($n*p$), and the variance is equal to $n*p*(1-p)$, meaning that variance is 100, and standard deviation is 10.
Therefore, would this mean the outcome of 400 flips conforms to $N(200, 100)$--that is, a normal distribution with mean 200 and variance 100?
To solve this, would I then simple solve for $P(X >= 220)$, which yields 2.28%?
Comment: That's the basic idea, but you might want to ponder if you should use a "continuity correction".
Answer: Another approach would be to calculate your answer using the cumulative distribution function. Because it is binomial distribution, it makes more sense to use this kind of calculation. The calculation you used was for normal distribution. Hope this helps!
$k$ is the amount of heads,
$n$ is the total amount of flips,
$p$ is the probability of getting either a heads or tails.
$f(k,n,p) = \displaystyle\sum_{i=k}^{n}\binom{n}{i}p^i(1-p)^{n-i} $
And $\binom{n}{k} = \frac{n!}{k!(n-k)!}$
$Pr(220) =f(220,400,0.5)= Pr(X=220) = \displaystyle\sum_{i=220}^{400}\binom{400}{i}0.5^{i}(1-0.5)^{400-i}$
When I plugged this into a calculator I found that there is about a $2.55201$% chance of flipping heads more than 220 times. Here's some more reading on it if you would like


Audio stream requested using HttpClient doesn't play until file is completely downloaded

Question: I'm trying to read an audio stream using an HttpClient because I need to modify HTTP headers. The only "working" way I found is the following :
HttpResponseMessage response = await httpClient.GetAsync("http://...");
Stream stream = await response.Content.ReadAsStreamAsync();
IRandomAccessStream content = stream.AsRandomAccessStream();
musicPlayer.SetSource(content, "audio/mpeg");   //musicPlayer is a MediaElement object
musicPlayer.Play();

The issue is that the MediaElement really starts to play when the file has been entirely downloaded, so it's quite useless for streaming. I need it to play as soon as the stream is received.
Comment: You are telling it to download the whole file before you start streaming in your code.  Stream stream = await response.Content.ReadAsStreamAsync();
Comment: You could try this link: http://stackoverflow.com/questions/18594659/how-to-play-a-video-stream-that-requires-authentication
Comment: I created a converter from `HttpClient` to `IRandomAccessStream`, please give it a try: https://github.com/kiewic/MediaElementWithHttpClient
Comment: ok i'll try it as soon as possible. sorry for late response, quit busy...
Answer: You want to use the overload of GetAsync that takes an HttpCompletionOption. The default value is ResponseContentRead, which means that stream will not be available until the content is completely read. Use ResponseHeadersRead instead, which means stream will be available immediately after just the headers have been read.
HttpResponseMessage response = await httpClient.GetAsync("http://...",
    HttpCompletionOption.ResponseHeadersRead);

Comment: it seems to be the solution indeed! thanks! but now i have an error "Cannot use the specified Stream as a Windows Runtime IRandomAccessStream because this Stream does not support seeking" which is true i guess, the stream is not seekable as this is just an mp3 file exposed, but when i do `musicPlayer.Source = new Uri("http://...");` this is working fine. I tried other ways like `IRandomAccessStream content = content.AsInputStream();` but the cast is not possible... do you have any idea how to manage this?