Proof about convex polyhedron

Question: This exercise is from The Kürschák Mathematics Competition from 1947:

Prove that exept for any tetrahedron, no convex polyhedron has the property that every two vertices are connected by an edge. Degenerate polyhedron are not considered.

Every convex polyhedron can be represented as a $3$-connected simple planar graph (proof here). ($3$ connected here means that there does not exist any set of $k-1$ vertices whose removal disconnects the graph). Now our hypothesis says that we need to have a full graph (that is all vertices are connected to every other via an edge). And the smallest such is $K_4$ which is the polyhedra (polyhedral graph) of the tetrahedron and therefore the result follows.
First of all, is my reasoning correct?
Secondly, this was an exercise for high-school students, probably without knowledge of these results. So I would like to get some HINTS and IDEAS about how to show this with other methods (both high-school level or university level, anything is welcome)
Thank you!
Comment: How about $V - E + F = 2$ for convex polyhedron?
Comment: I think you should emphasize that we are in 3-dimension . other wise any $n-$ simplex  with $n \ge 5$ serves as a counter example.
Comment: I assumed the word polyhedron means something in $3$ dimensions: https://en.wikipedia.org/wiki/Polyhedron
Answer: You can actually generalize it to say that a polytopes that has the corresponding property must be a simplex, but for a more down-to-earth proof you probably need to skip that generalization.
A strictly geometric way to prove it is to note that given such a polytope you can construct a polytope with the corresponding property in one dimension less with one vertex less by consider a cone formed from one of the vertices and consider it's intersection with a hyperplane.
In short this means that a complete pentagonal polyhedron would guarantee the existence of a complete quadrigonal polygon and so on until we realize the absurdity.
A more direct way in the same theme would be to just consider a complete pentagonal polyhedron and realize that four of the vertices must lie in a plane in order to have the "diagonals" lying on the boundary of the polyhedron. But then they're a proper diagonal and not an edge of the polyhedron.

As for your reasoning it seems correct, but I don't see how that proves that it excludes polyhedra with more than $4$ vertices.
Comment: @Vinyl_coat_jawa It should have been "polytope" (updated the answer). It's a generalization of the concept of polyhedron to possibly other dimensionalities. The old familiar examples are points (0 dimensions), line segments (1 dimension), polygons (2 dimensions) and polyhedra (3 dimensions). Polychoron is the next which is in four dimensions.
Comment: what is a polychoron?
Comment: Hey I just seen the last part of your answer. I think it excludes such polyhedra since with $5$ vertices you cannot draw a full and planar graph.

Proof about convex polyhedron


python issue with super

Question: I'm trying to learn some python and the new style class constructor doesn't seem to be working with super.
class A(object):
    def __init__(self):
        print 'Hello A'

class B(A):
    def __init__(self):
        print 'Hello B'
        super(A, self).__init__()

a = A();
b = B();

When I run this program, I get the following:
$ python classa.py
Hello A
Hello B

It should say
Hello A
Hello B
Hello A

What am I doing wrong here? I'm using python 2.7.6 on a Mac.
Comment: try super(B, self).__init__() inside class B(A)
Comment: If you are using Python 3 the easiest way is to omit the parameters of _super_: `super().__init__()`.
Answer: You're doing super(A, self).__init__() it should be super(B, self).__init__()
Answer: You are passing the wrong class to the call to super. A call to super returns a proxy object whose MRO (method resolution order) consists of the classes after the class passed as the first object. Here are the MROs for each class:
>>> A.__mro__
(<class '__main__.A'>, <type 'object'>)
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

When you call super(A, self).__init__, you are really invoking object.__init__, not A.__init__. object.__init__ doesn't output anything to the screen.
Changing the call to super(B, __init__) causes A.__init__ to run in your example.
Incidentally, good design dictates that if you use super in one class in your hierarchy, you need to call it in all the classes in your hierarchy.
class A(object):
    def __init__(self):
        super(A, self).__init__()
        print 'Hello A'

class B(A):
    def __init__(self):
        print 'Hello B'
        super(A, self).__init__()

Due to how super works (despite it's name, it does not necessarily call a method on the class's parent), this is required for the calls to work correctly in the case of multiple inheritance.

python issue with super


Rock Paper Scissors Game Best 2 out of 3 Loop Issues

Question: How do I make the computer automatically win when the wrong input (something aside from the options; rock, paper, scissors) is entered? It need these to be counted as well. Also, when the players chooses to play again, how can I remove "Welcome..." from reappearing; It is only needed when program first starts.
import java.util.Scanner;
import java.util.Random;
/**
 *
 * @author Chloe Harris
 *
 */
public class RockPaperScissorsGame {

    public static void main(String[] args) {
        // TODO code application logic here

        //Set integers for wins, losses, rounds, and user
        while(true){
            int wins = 0;
            int losses = 0;
            int round = 0;
            int Player = 0;

            //Plays 3 rounds before terminating
            //Prompt user to input Rock Paper Scissors
            System.out.print("Welcome to Rock Paper Scissors! Best 2 out of 3! \n");

            Scanner keyboard = new Scanner (System.in);
            while(round<3) {
                System.out.println("Enter \"Rock\", \"Paper\" or \"Scissors\"");
                Random Game = new Random();
                int Computer = 1+Game.nextInt(3);

                int Scissors, Rock, Paper;
                Rock = 1;
                Paper = 2;
                Scissors= 3;

                String UserInput =  keyboard.next();
                if(UserInput.equals("Rock"))  {
                    Player = 1;
                }
                if(UserInput.equals("Paper")) {
                    Player = 2;
                }
                if(UserInput.equals("Scissors")) {
                    Player = 3;
                }

                //If the user enters a value greater then 3 (Scissors) or less than 1 (Rock)
                //it will terminate the program and display an error message
                while (Player > 3 || Player < 1) {
                    losses++;
                    round++;
                    System.out.println("Not a valid input! Computer wins");
                    System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");

                }

                //Establish tie scenarios using if statements
                if(Player == Computer){
                    if(Player == Scissors){
                        System.out.println("Scissors v Scissors! Tie!");
                        round++;
                    }
                    if(Player == Rock){
                        System.out.println("Rock v Rock! Tie!");
                        round++;
                    }
                    if(Player == Paper){
                        System.out.println("Paper v Paper! Tie!");
                        round++;
                    }
                    System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");

                }

                //Establish the various winning scenarios using if and else if statements
                //Player wins
                if(Player == Scissors)
                    if(Computer == Paper){
                        System.out.println("Scissors v Paper! Player Wins!");
                        wins++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
                    }
                //Computer wins
                    else if(Computer == Rock){
                        System.out.println("Scissors v Rock! Computer Wins!");
                        losses++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
                    }
                //Player wins
                if(Player == Rock)
                    if(Computer == Scissors ){
                        System.out.println("Rock v Scissors! Player Wins!");
                        wins++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
                    }
                //Computer wins
                    else if (Computer == Paper){
                        System.out.println("Rock v Paper! Computer Wins!");
                        losses++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
                    }
                //Player Wins
                if(Player == Paper)
                    if(Computer == Rock){
                        System.out.println("Paper v Rock! Player Wins!");
                        wins++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");

                    }
                //Computer Wins
                    else if (Computer == Scissors){
                        System.out.println("Paper v Scissors! Computer Wins!");
                        losses++;
                        round++;
                        System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
                    }
            }

            //Determine final winner using if statements
            //Ask if player would like to play again by setting up string
            if(wins>losses){
                System.out.println("The Player Wins!");
            }if(losses>wins){
                System.out.println("The Computer Wins!");
            }
            System.out.println("Play again? \"Yes\" or \"No\"");
            Scanner YesNo = new Scanner(System.in);

            String YesNo_String = YesNo.next();
            if(YesNo_String.equalsIgnoreCase("yes"))    {
            }if(YesNo_String.equalsIgnoreCase("No"))    {
                System.out.println ("Goodbye!");
            }
        }
    }
}

Comment: By the way, do you know we can determine who is the winner with only 3 lines of code? I see that in order to determine who is the winner, you wrote 30 over line of codes.
Answer: You could always just change your if statements to the following:
if(UserInput.equals("Rock"))  {
    Player = 1;
}
else if(UserInput.equals("Paper")) {
    Player = 2;
}
else if(UserInput.equals("Scissors")) {
    Player = 3;
}
else {
    Player = 0;
}

You already have it set up so that if player < 1, the computer wins automatically.
Note: your while (Player > 3 || Player < 1) statement should actually be an if statement. Otherwise, you'll have an infinite loop there.
To answer your second question, just move the statement System.out.print("Welcome to Rock Paper Scissors! Best 2 out of 3! \n"); above your loop. That way it will only be asked once: at the beginning.
Answer: For both the player entering in the wrong data and checking if they have already played, create Booleans and check those Booleans in an if/else statement.  Since this may or may not be homework I'll solve this for the "Welcome... " message.
    public static void main(String[] args) {
    // TODO code application logic here
    Boolean firstPlay = true;

    //Set integers for wins, losses, rounds, and user
    while(true){
        int wins = 0;
        int losses = 0;
        int round = 0;
        int Player = 0;

        //Plays 3 rounds before terminating
        //Prompt user to input Rock Paper Scissors
        if(firstPlay) {
            System.out.print("Welcome to Rock Paper Scissors! Best 2 out of 3! \n");
            firstPlay = false;
        }

Answer: It seems like you are setting the value of "Player" to either 1, 2, or 3 with the default being 0. I would say set it to the default value at the start of every loop, and if its 0 allow the computer to win. Or change your if satements to if-elseif. I'll provide an example below.
....
if(UserInput.equals("Rock"))  {
    Player = 1;
} else if(UserInput.equals("Paper")) {
   Player = 2;
} else if(UserInput.equals("Scissors")) {
   Player = 3;
} else {
    Player = 0;
}

Since you already have a statement saying if Player < 1 or > 3 that the computer wins, you are set. Also your "Welcome" statement is inside of your while loop. Because of this every time it iterates through the loop you will see it. Try moving it outside of the loop.


php counting number of files in a directory

Question: i am trying to display a number from which is the amount of files in a folder in my directory within my website.
i have tried to do many methods of this which i have found on the net but still have no clue maybe its because i am unsure of the location of the directory
the location of the folder is
www/documents

and here is my code
<?php iterator_count(new DirectoryIterator('/documents/'));?>

i have tried a few samples i found on the net.

server details

its a usb device with UniServer

This is why i am not sure where the file structure starts
I am very novice so please play fair and not scare me with them words that means monkey beans to me :)
thanks in advance

Locations i have tried

www/documents
/www/documents/

Comment: Have you tried using full path instead ?
Comment: maybe http://stackoverflow.com/questions/12801370/count-how-many-files-in-directory-php
Comment: Try `new DirectoryIterator(__DIR__ . '/documents/')`
Comment: i will update my question with the locations i have tried
Answer: A shorter version:
<?php

echo count(glob("/var/documents/*"));

?>


Number of elements of order 4 in $\mathbb{Z}_4 \times \mathbb{Z}_2 \times \mathbb{Z}_2$

Question: I've read that number of elements of order 4 in $\mathbb{Z}_4 \times \mathbb{Z}_2 \times \mathbb{Z}_2$ is 8, but I can't figure it out where this number come from. I now that if we're searching number of elements of order 4 in $\mathbb{Z}_{16}$, we use Euler's phi function ($\phi(4)=2$). Do we use something similar here?
Answer: The order of an element in a direct product like this one is the l.c.m of the orders inside the respective coordinates. So an element of order $4$ in $\mathbb{Z}_4 \times \mathbb{Z}_2 \times \mathbb{Z}_2$ must be $1$ or $3$ in the first coordinate. In the second and third coordinate, you could have either $0$ or $1$. In each case you get elements of order $4$. There are $2 \cdot 2 \cdot 2 = 8$ such possibilities.
Comment: But what about $\mathbb{Z}_4 \times \mathbb{Z}_4$? There are 12 elements of order 4.
Comment: Yes, as there should be. You will get an element that is not of order $4$ only when both the first and second coordinate do not have order $4$. For this, there are two choices ($0$ and $2$) for the first coordinate, and two choices ($0$ and $2$) for the second coordinate. So four total choices. So there are $12$ elements of order $4$.
Comment: To view it the other way, finding elements of order $4$ directly: if the first coordinate is $0$, the second coordinate must be $1$ or $3$. That's two choices. If the first coordinate is $1$, the second coordinate can be anything. That's four choices. If the first coordinate is $2$, the second coordinate must be $1$ or $3$. Two more choices. If the first coordinate is $3$, the second coordinate can be anything. Four more choices. That's $2 + 4 + 2 +4 = 12$ total choices. The reason the "multiplication" I did above doesn't work here is because above, the first coordinate had to be $1$ or $3$.
Answer: Suppose that $(a,b,c)$ is an element of order $4$. As $2b=2c=0$, $a$ has to be an element of order $4$. Therefore $a \in \{1,3\}$.
And then $b,c$ can be whatever you want. Therefore $8$ elements of order $4$.


WebServiceHostFactory and IIS authentication

Question: I encounter a problem with using the WebServiceHostFactory in IIS.
"IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used."
I wanted to keep both authentication schemes and managed to do so by not using the factory  but setting up the endpoint manualy in web.config.
My question is what is WebServiceHostFactory doing to get this result?  I was under the impression that WebServiceHostFactory would set the binding to the same webHttpBinding that I used in my config.
Edit:
I have looked at WebServiceHostFactory in reflector and it is not doing anything clever.  It is just a simple factory for the WebServiceHost.
Does IIS still use a service host if you set up the endpoint in config?  Or is the WebServiceHost setting things up differently.
Answer: This is what worked for me.  Adding a dummy endpoint early on (before the service host is opened) as shown below seems to have done the trick. (This MSDN article hinted at this http://msdn.microsoft.com/en-us/library/bb412178.aspx.)
<code>public class MyWebServiceHost : WebServiceHost
{
    public MyWebServiceHost (Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)
    {
        // Inserting this dummy endpoint config seemingly does the trick:
        AddServiceEndpoint(typeof(IMyContract), new WebHttpBinding(), string.Empty);
    }

    protected override void ApplyConfiguration()
    {
        // Typical programmatic configuration here per:
        // http://msdn.microsoft.com/en-us/library/aa395224.aspx
    }
}
</code>
I'm guessing this prevents WebServiceHost from creating a default endpoint, and thus shutting down a bunch of functionality.
Comment: I am not able to test this answer as this was asked a while ago and I worked around the problem then got a new job but if you say it works then that's good enough for me.
Comment: I don't understand where I should reference that MyWebServiceHost
Comment: I had the same problem and I was able to get it working. I had to write two classes: `MyWebServiceHostFactory` and `MyWebServiceHost`. In the factory class, I overrode the `ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)` method and had it return an instance of `MyWebServiceHost`. `MyWebServiceHost` looks like the one in this answer, but I didn't override `ApplyConfiguration()`.
Answer: I'm not sure about the WebServiceHostFactory, but it sounds like you're hosting the service inside IIS and it's got more than one authentication method selected. If you've got IIS 5 or 6, try going into IIS and viewing the properties for the website or virtual directory containing your service. Go to the Directory Security tab, click the Edit button under "Anonymous access and authentication control", and then un-tick either "Anonymous access" or "Integrated Windows authentication". I'm not sure about IIS7.
Comment: Problem with that is that you then **can't debug an anonymously accessed** web site.  An **unsatisfactory** work around is to compile with a single authentication then just before you debug switch the other one on, in IIS.  This works but is time wasting and annoying.  I've seen .NET 3.5 sites developed for years without this issue ever happening.  With .NET 4 sites my experience has been worse.  _(There's a possibility to alter web site authentication from MSBuild file, but I couldn't find a ready built task to do that.)_
Comment: Sorry but is said he wanted to keep both authentication schemes... Your answer was not helpful in that regard.
Answer: Under IIS7 you might not find where you can manage the Integrated Windows Authentication setting. In order to see the setting in IIS7 management console, you need to follow steps described in the following article: http://msdn.microsoft.com/en-us/library/x8a5axew.aspx (titled as "Error: Debugging Failed Because Integrated Windows Authentication Is Not Enabled", if link is not functional).
Hope it helps.
Answer: disable security in web.config-> configuration tag
<code>  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding>
          <security mode="None">
            <transport clientCredentialType="Windows"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</code>
then your wcf service doesn't need authentication...
Comment: This is just some code... please provide some explanation. It's not an answer to question.
Comment: You really need to provide some form of explanation (rather than just a code sample) when providing an answer.


Posso considerar que minha aplicação está em MVC?

Question: Pesoal, seguinte: estou meio que com uma dúvida conceitual.
Comecei a implementar minha aplicação (c# - forms) pensando em seguir o desenvolvimento baseado na arquitetura MVC. Mas, intuitivamente - e não sei se conceitualmente correto - acabei efetuando a seguinte divisão (coloquei a imagem do diagrama de classes para facilitar):
Classe 'formularioPrincipal': responsável por apresentar os dados e notificar eventos e ações do usuário na interface do sistem para a classe 'arvoreCont'.
Classe 'arvoreCont': recebe as requisições do formulário, solicita dados ao banco pela classe persistence, aplica regras de negócio e retorna para a view.
Classe persistence: faz toda a comunicação com o banco para inclusão, alteração, exclusão e consulta de dados (com filtros where).
Classes 'no', 'dados' e 'transacao' que representam os objetos da aplicação que são utilizados muitas vezes para passar dados para a interface.

Não sei se conceitualmente posso considerar que utilizei o MVC, até porque, pelo que li, a classe persistence deveria estar junto com as classes que representam os objetos. Mas, para mim, faz sentido separar.
E o que inicialmente tratei como controller (classe 'arvoreCont') acabou responsável pela centralização de grande parte da regra de negócio.
Posso dizer, baseado nessa estrutura, que uso MVC? A intenção inicial era utilizar, mas no fim, não sei se consegui. O que acham?
Comment: Você só tem uma view? Ou suas views estendem `formularioPrincipal`?
Comment: Eu tenho várias views, que representam os formulários exibidos ao usuário.
Eu estou exibindo apenas um "pedaço" para não ficar muita coisa. Mas o funcionamento para as outras views é semelhante. Ela interage com um controler, que por sua vez interage com o persistence.
Elas não estendem o formulário principal.
Comment: Eu não diria que é MVC se o controller tem regra de negócio - ele deveria ter no máximo as regras de aplicativo.
Comment: O que você considera como 'regras de aplicativo'?
Comment: Exemplo de regra de aplicativo: o usuário solicita uma lista de clientes, o aplicativo sabe qual model e view selecionar enviar para o usuário - isso é uma regra de aplicativo. Então regras de aplicativo são o fluxo de navegação no sistema, as permissões de acesso, a gestão de logs, o conhecimento de quais regras de negócio acionar para atender requisições do usuário... (obs: ao dirigir-se a alguém, faça-o através do seu nome com um @ na frente, assim o usuário é notificado da sua mensagem).
Comment: @Caffé, obrigado pelas respostas. Entendi  o que colocou...
Então, como tinha imaginado eu acabei não utilizando um "padrão" de arquitetura... :(

O correto seria mover todas as regras de negócio para as entidades do model, a saber, classe: "Nó", "Função de dados" e "Funçao transacao". Certo?

Seria 'correto' dentro do MVC criar uma outra classe persisnte que centralize o acesso ao banco, ou também deveria em uma única classe com as regras de negócio - no model.? Obrigado
Comment: MVC é um design pattern de apresentação, ele não determina a responsabilidade da persistência (ele só sabe que não é uma responsabilidade dele). De qualquer modo, quanto melhor separadas estiverem as responsabilidades, em todas as camadas, melhor - ou seja: separe à vontade a persistência das regras de negócio.
Comment: @Caffé, está claro. Obrigado!
Answer: Primeiro vamos definir conceituamente o que é MVC, e então traçar um paralelo com sua solução.
Da nossa tag mvc:

Model-view-controller (MVC), em português modelo-visão-controlador, é um modelo de arquitetura de software que separa a representação da informação da interação do usuário com ele.

Neste modelo, temos três camadas muito bem definidas:

Um Modelo (model) consiste nos dados da aplicação, regras de negócios, lógica e funções, bem como a descrição do relacionamento entre outros modelos.
Uma Visão (view) pode ser qualquer saída de representação dos dados, como uma tabela ou um diagrama. É possível ter várias visões do mesmo dado, como um gráfico de barras para gerenciamento e uma visão tabular para contadores.
Um Controlador (controller) faz a mediação das entradas e estabelece como deve ser a interação entre modelos e alimentando as informações das visões.

O que você apresentou como solução basicamente tem:

Um intermediador entre apresentação e modelos, arvoreCont, que possui funções que lidam com apresentação e modelos, mas altamente acoplada a ambos;
Uma camada de apresentação ancestral, formularioPrincipal, que, aparentemente, é a base de toda e qualquer tela que você desenvolver;
Uma camada de modelos, aparentemente gerenciada pelo intermediador.

Eu não diria que esta arquitetura é MVC. Diria que isto é uma arquitetura simples de 3 camadas com grau elevado de acoplamento e baixa coesão, onde temos:

Uma camada de apresentação;
Uma camada de negócio;
Uma camada de persistência e acesso a dados.

No MVC, a estratificação faz com que a camada controladora tenha apenas o suficiente para harmonizar o fluxo de informação entre apresentação e modelos. Não parece ser seu caso.
A camada de modelo contém a maior parte das regras conceituais de negócio da aplicação, e por design. É nela que ficam as especificações de cada tipo de informação, as validações feitas sobre o conjunto de informações, as restrições, e assim por diante. Também não parece ser o caso. A camada que você implementou parece ser apenas o agente de acesso a uma base de dados, dependente da camada intermediária.
A camada que mais se assemelha a MVC, no seu caso, é a apresentação, ainda que tenha métodos de notificação de informações à camada intermediária, o que também a torna dependente de ações desta camada intermediária, o que não ocorre no MVC.


Recursividade: Calcular a soma dos primeiros valores ímpares positivos começando em 5

Question: Estou fazendo alguns exercícios sobre e parei nesse faz uns dias.
Cheguei até o seguinte código:
  /**
    * Funcao: Soma dos primeiros valores ímpares positivos começando em 5.
    * @param quantidade - quantidade de valores a somar
    *
    * valores esperados para quantidade = 1
    * 5
    * valores esperados para quantidade = 4
    * 32
    */
  public static int funcao06 (int quantidade){

    int resposta = 5;

    if(quantidade > 1){

      IO.println ("(" + quantidade + ") Valor Impar: " + (funcao06(quantidade - 1) + 2));

    } else {

      resposta = 5;
      IO.println ("(" + quantidade + ") Valor Impar: " + resposta);

    }// fim do se

    return (resposta);

  } // fim do funcao06

A saída da minha função:

O que estou fazendo de errado ?!
Answer: Eu consegui a solução seguindo o seguinte raciocínio:

Todo número ímpar é gerado pela fórmula 2*n + 1;
O caso base da recursão é f(0) = 5 (deve começar de 5);

Com essas hipóteses tentamos generalizar uma fórmula para a recursão:
f(0) = 5
f(1) = 5 + 7 = 12              = f(0) + 7
f(2) = 5 + 7 + 9 = 21          = f(1) + 9
f(3) = 5 + 7 + 9 + 11 = 32     = f(2) + 11

Pela tabela acima percebemos que acrescentamos um valor ao resultado da função anterior. Esse valor pode ser alcançado com a fórmula 2 * (n + 2) + 1 o mais 2 na fórmula dos números ímpares é por conta do início no 5.
Logo a fórmula final fica:
f(n) = f(n-1) + 2 * (n+2) + 1;
Transformando em código temos:
public int soma(int quantidade) {
    if(quantidade == 0) {
        return 5;
    } else {
        return soma(quantidade - 1) + 2*(quantidade + 2) + 1 ;
    }
}

Veja no Ideone
Comment: Observei que nesse caso quando eu quiser a soma dos três primeiros números eu teria que chamar a função no main da seguinte maneira: soma (quantidade - 1);
Pois f(0) = 5 é a primeira parcela da soma!
Comment: É questão de gosto, você pode alterar a função para começar a contar a partir do 1 (ao invés do 0) modificando o caso base para quantidade == 1, mas normalmente na programação começamos a contar do 0.
Comment: Sim, deixei o comentário como uma observação mesmo! =)
Answer: Solução recursiva para somar uma dada quantidade de números impares a partir de um valor inicial:
private static int somarImpares(int valor, int quantidade) {
    assert valor % 2 != 0 : "valor: " + valor;
    assert quantidade > 0 : quantidade;

    if (quantidade > 1)
        return valor + somarImpares(valor+2,  quantidade-1);
    else
        return valor;
}

(funciona tambem para números pares se o primeiro assert for removido, os dois assert são principalmente para documentação)
Para facilitar, o seguinte método também pode ser implementado
 public static int somarImparesAPartir5(int quantidade) {
    return somarImpares(5, quantidade);
}


Singular values of $AB$ and $BA$ where $A$ and $B$ are rectangular matrices

Question: This question is a generalisation of Eigenvalues of $AB$ and $BA$ where $A$ and $B$ are rectangular matrices which itself is a generalisation of Eigenvalues of $AB$ and $BA$ where $A$ and $B$ are square matrices.
Let $A$ be an $m \times n$ matrix and $B$ an $n \times m$ matrix. Obviously, the matrix products $AB$ and $BA$ are possible. Assume $n \leq m$, such that $AB$ is a weakly larger matrix than $BA$.
Facts:

The rank of both $AB$ and $BA$ is at most $n$ (link 1)
The number of non-zero eigenvalues of both $AB$ and $BA$ is at most $n$ (link 2)
If the eigenvalues of $AB$ are $\lambda_1, \ldots, \lambda_n$, the eigenvalues of $BA$ are also $\lambda_1, \ldots, \lambda_n$ (link 3).

Questions:

If the singular values of $AB$ are $\sigma_1, \ldots, \sigma_n$, what can be said about the singular values of $BA$?
What does Fact 3, compared with the answer to Question 1, say about the differences and the similarities between eigenvalues and singular values?
Comment: @Ian Are the eigenvalues of $(AB)(B^TA^T)$ related to those of $(A^TB^T)(BA)$?  I'm not seeing the connection.
Comment: @ErickWong You're right, I made a simple mistake.
Comment: There is a relation between the singular values but a subtle one: Singular values of both $AB$ and $BA$ satisfy the same set of linear inequalities, called Horn inequalities, in terms of singular values of $A$ and $B$. I can tell you more if you are interested.
Answer: There is almost no relationship. For example, if we take
$$A = \begin{bmatrix}x & 1 \\ 0 & 0\end{bmatrix}, \quad B = \begin{bmatrix}0 & 0 \\ 1 & y \end{bmatrix}$$
then the singular values of $AB$ are the square roots of the eigenvalues of $$(AB)^{\mathsf T} AB = \begin{bmatrix}1 & y \\ y & y^2\end{bmatrix}$$ so they are $\sqrt{1+y^2}$ and $0$. Similarly, the singular values of $BA$ are $\sqrt{1+x^2}$ and $0$. Even in this simple example, the nonzero singular value in one case can vary pretty much independently of the other case. (They must both be at least $1$, but we can tweak that by changing the $1$ in the matrices to some small $\epsilon>0$.)
By taking determinants, we can conclude that the product of the singular values of $AB$ is $\det(AB)$, while the product of the singular values of $BA$ is $\det(BA)$. So if $A$ and $B$ are both square matrices, the singular matrices in both cases have an equal product $\det(A)\det(B)$, which is some amount of dependence.
On the other hand, by taking tensor products of the construction above, we can start with $2n \times 2n$ square matrices $A$ and $B$ where

$AB$ has singular values $\sigma_1, \sigma_2, \dots, \sigma_n, 0, 0, \dots, 0$,
$BA$ has singular values $\sigma'_1, \sigma'_2, \dots, \sigma'_n, 0, 0, \dots, 0$,
and these are free to vary independently of each other.
Comment: The eigenvalue decomposition involves finding a single basis (of any kind) on which the matrix plays nicely. The singular value decomposition involves finding two different *orthonormal* bases on which the matrix plays nicely. In the end, it turns out that $A$ maps the eigenbasis of $BA$ to multiples of the eigenbasis of $AB$, hence your fact 3. For the equivalent to hold for SVD, $A$ would have to map orthonormal vectors to other orthonormal vectors, which would require special properties of $A$.
Comment: Thank you. This is somewhat surprising to me as I previously thought of singular values as just a generalisation of eigenvalues. You've shown that, although $AB$ and $BA$ have identical eigenvalues, their singular values are independent. Is there an intuitive/visual way to understand the difference between singular values and eigenvalues?


Does $\|T\|=1$ for a unitary operator?

Question:
Let $T:X\rightarrow X$ be an operator on a Hilbert space $X$ and assume it is unitary, i.e. $T^*T=TT^*=I$. I want to show that $\|T\|=1$

We know that for any operator $\|TT^*\|=\|T\|^2$ but since $T$ is unitary we also know that $\|TT^*\|=\|I\|=\sup_{\|x\|=1}\|I(x)\|=\sup_{\|x\|=1}\|x\|=1$ therefore if we combine both we get $$\|T\|^2=1\Leftrightarrow \|T\|=1$$does this work?
Comment: Yes your proof is correct but geetha's direct one is more standard. $\|Tx\|^2=\langle Tx,Tx\rangle=\langle T^*Tx,x\rangle=\|x\|^2.$
Comment: Actually $\|Tx||=\|x\|$  for all $x$ and that  gives a  simpler proof.
Comment: @geetha290krm 1) so my proof also works? 2) could you explain why your equality holds?
Answer: It depends on the vector norm $\|x\|$ you use. If it is the norm induced by the inner product with respect to which $T^\ast$ is defined, then $\|Tx\|^2=\langle Tx,Tx\rangle^2=\langle x,T^\ast Tx\rangle^2=\|x\|^2$ for every vector $x$ and hence $\|T\|=1$.
However, if $\|x\|$ is some norm other than $\sqrt{\langle x,x\rangle}$, it can happen that $\|T\|>1$. For instance, when
$$
T=\pmatrix{\frac{1}{\sqrt{2}}&-\frac{1}{\sqrt{2}}\\ \frac{1}{\sqrt{2}}&\frac{1}{\sqrt{2}}},
$$
we have $\|T\|_\infty=\sup_{\|x\|_\infty=1}\|Tx\|_\infty=\sqrt{2}$.
Comment: Of course, the OP's vector norm is implicitely the one of the Hilbert space.

Does $\|T\|=1$ for a unitary operator?


If $4x^2+y^2=40$ and $xy=-6$, find the value of $2x+y$.

Question: If $4x^2+y^2=40$ and $xy=-6$, find the value of $2x+y$.
I tried the following,
As we know, $(a+b)^2=a^2+b^2+2ab$
Therefore, $(4x^2+y^2)^2=(4x^2)^2+(y^2)+2(4x^2*y^2)$
$=16^4+y^4+8x^2y^2$
What should I do know? Please help. I am stuck.
Answer: $$(2x+y)^2=4x^2+4xy+y^2=(4x^2+y^2)+4xy=40+4(-6)=16 \Rightarrow 2x+y=\pm 4$$
Comment: Thank you! You have helped me a lot!
Comment: Thank you! I just wanted to know that why you wrote +- 4? How did you find it?
Comment: @Abhishekstudent Because,we know that if $x^2=a, a>0$,then $x=\pm \sqrt{a}$.
Answer: Hint:
$(2x+y)^2-4xy=4x^2+y^2$
You can take it from here?


Custom contraint validator: show an error message with a link

Question: We use a custom constraint on a custom entity type. In this entity type we have a string field "url basis" which is used to create aliases for many kinds of pages and data related to this entity.
Therefore it is important that this url basis is unique with every single entity. Here is the constraint:
class UniqueParliamentBasisUrl extends Constraint {
  public $notUniqueURLBasis = 'The basis URL needs to be unqiue but the set basis URL %basisurl is already in use: @parliament_link';
}

In UniqueParliamentBasisUrlValidator->validate() I try the following:
    $link = $parliament_using_basis_url->toLink($parliament_using_basis_url->label(), 'edit-form', ['attributes' => ['target' => '_blank']])->toString();
    $this->context->addViolation($constraint->notUniqueURLBasis, ['%basisurl' => $item->value, '@parliament_link' => $link]);

Here $link becomes the HTML markup for a link so that the user can easily switch to the entity which already uses this url basis in order to edit it. Unfortunately the markup becomes escaped so that the user does not see a clickable link on the form but the markup:
The basis URL needs to be unqiue but the set basis URL bundestag is already in use: Bundestag

Is there a way to add markup to the violation message without being escaped?
Answer: You shouldn't chain up placeholders / use HTML inside placeholders. And for URLs use the :placeholder notation with double dots
 $notUniqueURLBasis = 'The basis URL needs to be unqiue but the set basis URL %basisurl is already in use: @link_text';

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/class/FormattableMarkup/8.2.x
and
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8.2.x
Comment: Thank you, this solved my problem!


Divide $n$ students in 4 groups

Question: In class, a teacher proposes four different projects, which can be done by one or more students. In how many ways can $n$ students be grouped in four groups, in such a way that every student participates in exactly one group and every project is done by exactly one group?
Answer: Let us first assume that students are not distinguishable (i.e. it doesn't matter if student $A$ or student $B$ participates in project $X$, only the amount of students which participate in the project matters). Since every project must be chosen, at least one student is assigned to each project. Then, we must must divide the $n-4$ remaining students over the four projects, which is essentially a stars and bars problem. The number of ways in which to do this equals:
$${n-4+4-1 \choose 4-1} = {n-1 \choose 3}$$
If students are distinguishable, the result is different. Each student can select one of the four projects, so the total number of possible arrangements is $4^n$. However, one project must be assigned to at least one student. Let us determine the number of ways $F(k)$ in which only $k$ projects are chosen by these students:
$$F(1) = {4 \choose 1} 1^n = 4$$
$$F(2) = {4 \choose 2} \bigg(2^n - {2 \choose 1} 1^n\bigg) = 6 \cdot 2^n - 12$$
$$F(3) = {4 \choose 3} \bigg(3^n - {3 \choose 2} \bigg(2^n - {2 \choose 1} 1^n\bigg) - {3 \choose 1} 1^n\bigg) = 4 \cdot 3^n - 12 \cdot 2^n + 12$$
$$F(4) = 4^n - F(3) - F(2) - F(1) = 4^n - 4 \cdot 3^n + 6 \cdot 2^n - 4$$
For $n=4$, $F(4) = 24 = 4!$ which makes sense, since the first student can choose one of the four projects, the second student one of the remaining three, the third student on of the remaining two and the last student the only remaining project.

Divide $n$ students in 4 groups


Is there some trick to evaluating the following integral

Question: I have been staring at this integral for a while and I don't quite know how to take the first step. Is there some trick that I have to use to manipulate the function first?
Integral in question:
$$\int^{2\pi}_0 \frac{dx}{a + \cos x}$$
Any help/hints/insights is deeply appreciated.
Comment: Note the on the unit circle we have $z+z^{-1} =2 \cos(\theta)$
Comment: @kennytm, I think from the tags the OP is interested in a complex analysis approach.
Comment: @ZaidAlyafeai OK maybe http://math.stackexchange.com/questions/146761/compute-integral-int-02-pi-frac1z-cos-phi-d-phi and http://math.stackexchange.com/questions/2030472/trigonometrical-integral-of-1-b-cos-theta and http://math.stackexchange.com/questions/1760520/int2-pi-0-frac1-sqrt5-cos-tdt-int2-pi-0-frac-cos2t-5 and http://math.stackexchange.com/questions/1027486/integral-int-02-pi-fracdx2-cosx and http://math.stackexchange.com/questions/833442/contour-integral-of-int-02-pi-frac1a-cos-theta-d-theta
Answer: Hint this can be rewritten as
$$\int_{|z|=1}\frac{\frac{dz}{iz}}{a+\left(z+z^{-1} \right)/2} = -2i\int_{|z|=1}\frac{dz}{z^2+2az+1} $$
Now you need to look at the roots of $z^2+2az+1 =0$ and some conditions on $a$ to see if the poles lie inside the circle or outside.
Answer: A possible way to do this: Let $t= tan(x/2)$ and the integral will be transformed to $2 \int \frac{dt}{((a-1)t^2+(a+1))}$. Then use the Newton-Leibniz formula with a careful discussion at $x= \pi$
Comment: You have to divide the interval before doing the substitution otherwise you will get the wrong result.
Comment: @Zaid AlyafeaI Yes. And your way is more enlightening than mine.


Round Robin Qualification

Question: There are 10 teams and the top 4 go through. Teams play each other once, and may only win or lose. What is the minimum number of wins with which a team could possibly go through? What is the maximum number of wins with which a team would still be eliminated.
What about for 20 teams and top 8 going through?
For the first part, I wanted maximize points between the top 3 teams, so I gave them 9,8,7 wins, leaving (45-24)=21 wins to be distributed between the bottom 7. Hence 3 points each and one of these would qualify.
For the second part, I had a similar approach, instead minimizing points for bottom 5 teams, and then splitting the remaining.
Comment: "Hence 3 points each and one of these would qualify." So some sort of random selection is being allowed if a group with same number of wins is to qualify/be eliminated ?
Comment: Yes, a random selection is allowed.
Comment: I have accounted for that in the answer
Answer: Help for first problem
Taking 1 point for win, 0 points for loss, $\binom{10}2$ matches will have $45$ points at stake
For the highest non-selection score, rank the teams into uniquely from best to worst.
The highest non-selection score can be $5$ with  monotonically decreasing scores, viz
$9-8-7-6-\fbox5-4-3-2-1-0$
This will be a unique highest score for non-selection.
The lowest selection score has already been computed by you correctly as $3$, (there will be many with the same score, selction by lottery.)\

Work out for  "20 teams and top 8 going through" in similar fashion
Comment: Is the answer clear ?

Round Robin Qualification


c#: Draw point in panel on click event

Question: I am a beginner in c#;
I use bitmap equal to the size of the panel and set it as background image of the panel. I want to update bitmap with setpixel the panel update too on click event. But It doesn't work when I click on the panel.
Here is my code:
public partial class Form1 : Form
    {
        Bitmap bmp;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bmp = new Bitmap(panel1.Width, panel1.Height);
            panel1.BackgroundImage = (Image)bmp;
            panel1.BackgroundImageLayout = ImageLayout.None;
        }

        private void panel1_MouseClick(object sender, MouseEventArgs e)
        {
            label1.Text = (e.Location.X).ToString();
            bmp.SetPixel(e.Location.X, e.Location.Y, Color.White);
            bmp.SetPixel((e.Location.X)+1, e.Location.Y, Color.White);
            bmp.SetPixel((e.Location.X)-1, e.Location.Y, Color.White);
            bmp.SetPixel(e.Location.X, (e.Location.Y)+1, Color.White);
            bmp.SetPixel(e.Location.X, (e.Location.Y)-1, Color.White);
        }
    }

Comment: Since you are trying to create a larger pixel look into `using (Graphics g = Graphics.FromImage(bmp ) {  g.FillEllipse(Brushes.White, 2, 2);  .....}`
Answer: You are not updating the panel. Call
panel1.Invalidate();

after having drawn on the bitmap.

If you use the MouseMove event you can also draw continuously:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        bmp.SetPixel(e.Location.X, e.Location.Y, Color.Green);
        bmp.SetPixel((e.Location.X) + 1, e.Location.Y, Color.Green);
        bmp.SetPixel((e.Location.X) - 1, e.Location.Y, Color.Green);
        bmp.SetPixel(e.Location.X, (e.Location.Y) + 1, Color.Green);
        bmp.SetPixel(e.Location.X, (e.Location.Y) - 1, Color.Green);
        panel1.Invalidate(
            new Rectangle(e.Location.X - 1, e.Location.Y - 1, 3, 3));
    }
}

Make sure to draw only when the left mouse button is pressed and invalidate only the rectangle on the panel that has changed to minimize flicker.

A note on Invalidate(): Invalidate does not update the image immediately. Instead it tells Windows that we want an update. Windows then determines whether the invalidated region is visible. There could be be another window on top of it, it could be off-screen or the window could be minimized. Then it waits until the application is idle. This prevents the accumulation of too many unprocessed events (e.g. MouseMove). This means that Invalidate might skip some updates. This is good since it avoids lag.

c#: Draw point in panel on click event


How to Change Application icon from coding in iOS?

Question: I want to change my application icon daily from codeing just like  apple calendar app whaich shows daily date as icon of app.
i want same is it possible?
Comment: You can't change the icon of your app programmatically (or at least not in an official app - on a jailbroken device, or with private APIs, this may be possible.)
Answer: Unfortunately, that's not possible for third-party apps.
What the calendar app does is restricted to apps provided by Apple with elevated rights. It probably requires access to APIs that are private and not publicly documented. If you'd used them, your app wouldn't pass Apple's validation.


How do I calculate permutations?

Question: Ok in a normal set of N numbers, I might take the length of the number set, like 4 numbers long, raise that to the power of the base numbering scheme 0-9 so 10^4th=10000
and subtract 1. I get that.
Suppose I cannot reuse any number in the set. 1-9
I assume my base is 8. But i cant do 111111111... 112345678 or anything like that.
what method would I use to figure out the maximum number of permutations between 123456789 and 987654321?
oh and all the permutations must be 9 digits.
I have a guess, that it might be (8^9)/8 but I'm not sure
that makes sense.
Comment: the number of permutations in $n!$ simply by induction fix one digit $n$ choices, and permute all the other $(n-1)!$.
Answer: Suppose I cannot reuse any number in the set. 1-9 I assume my base is 8. But i cant do 111111111... 112345678 or anything like that.

I believe the base would be 9. (Count the number of integers between 1-9)
what method would I use to figure out the maximum number of permutations between 123456789 and 987654321?

I believe we could rephrase this question to "Total number of 9 digit integers with no repeated digits" That is because we are finding all the 9 digit numbers between the lowest 9 digit number (123456789) and the greatest 9 digit number (987654321). The answer to this would be P(9, 9) (which is 9!). We are permuting 9 distinct items (unique digits) into 9 spots.
A more intuitive approach might be to draw out the spots and fill them in with the number of choices we have. Imagine we have 9 empty spots and we fill each with a digit:

How many options do we have for the first spot? Well, we have 9 digits to pick from so 9.
9 _ _ _ _ _ _ _ _
How about for the second spot? We already chose a digit to put in the first spot, and because we can't repeat we have just 8 options left.
9*8 _ _ _ _ _ _ _    following this logic until all spots are filled:
$9\times8\times7\times6\times5\times4\times3\times2\times1= 9! = 362880$
Hope this helped.

How do I calculate permutations?


Why authenticate request returned 403 after successful login?

Question: I have front-end with AngularJS and its connected to drupal backend. I am using drupal services module for rest api.
I have an angularjs web app in subdomain [admin.example.com].
My authentication subdomain [account.example.com] developed with drupal 7.
I can login successfully to account.example.com from admin.example.com using http request from angularjs, so I stored newly generated token. But when i try to collect user data from [account.example.com] using previously stored token, i get 403 status. I'm sure my token is correct.
This work well with chrome disable-web-security mode, when i try from regular mode its response me 403. but i did not get any cors error.
Someone please help me, i'm stack on this stage...
My Apache Conf file [account.example.com]:
<VirtualHost *:80>
    ServerName account.example.com
    ServerAlias account.example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/example_account

    <Directory "/var/www/example_account">
        AllowOverride All
        Require all granted
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Headers "Content-Type, Accept, Authorization, X-CSRF-Token"
        Header always set Access-Control-Allow-Methods "GET,POST"
        Header always set Access-Control-Allow-Credentials true
    </Directory>

        #RewriteEngine On
        #RewriteCond %{REQUEST_METHOD} OPTIONS
        #RewriteRule ^(.*)$ $1 [R=200,L]

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Here is header requests:
Comment: Looks like a CORS issue - see https://drupal.stackexchange.com/questions/162473/how-do-i-enable-cors-on-service-endpoint
Comment: @rémy I have already enabled cors, see my conf file configs above. Is it wrong?
Comment: Access-Control-Allow-Origin: * should be changed to be specific, like Access-Control-Allow-Origin: admin.example.com
Answer: Try to be specific with the ACAO header, like
Access-Control-Allow-Origin: admin.example.com

The wildcard is not really appreciated, browsers may treat this as high security risk and block the request.
Comment: I have applied this method. I've used this same api for web and Cordoba both applications, will it work for cordova request if i fixed for admin.example.com?
Comment: Depends where this cordova request comes from, if you have requests to your API from several domains, you could follow this approach here: https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains


Percorrer linhas de uma tabela dentro de loops

Question: O que pretendo fazer é marcar horas e datas no front-end de acordo com os registros de uma tabela, porém com o código que possuo só consigo marcar a primeira linha da tabela. Como conseguir percorrer toda a tabela, marcando todas as datas correspondentes?
Tive um certo êxito com um outro while no lugar do mysqli_fetch_assoc() utilizando mysqli_fetch_array() porém ele repete a quantidade de linhas da tabela, multiplicando as horas do front-end. Segue meu código:

   <?
   for ($i=0; $i < 12; $i++) {
      $justDay=date('Y-m-d',strtotime("+$i days"));
      $days=formatDt(date('Y-m-d',strtotime("+$i days")));
      $dweek= strftime('%A', strtotime("+$i days, today"));
   ?>

      <?= $days;?>

      <?=utf8_encode($dweek); ?>

      <? $sql = "SELECT * from horas";
      $qr=mysqli_query($conexao,$sql);
      $it=0;
      while ($ft=mysqli_fetch_array($qr)) {
         $it++;
         $sqlAula = "SELECT * from monta_aula";
         $qrAula=mysqli_query($conexao,$sqlAula);
         $ftAula=mysqli_fetch_assoc($qrAula);
         $hrAula=$ftAula['hora_inicio_aula'];

         /* compara hora e data da tabela aula com a hora e data do front end e contorna o horário correspondente ao cadastrado no banco, na tabela aula*/
         if ($hrAula == $ft['hora'] and $justDay == $ftAula['dia_aula']) {
            $hc="border-class";
         } else{
            $hc="text-green-d";
         }
      ?>

         <a href="#" class="<?=$hc;?>">
         <?=$ft['hora'];?>

      <?    }//while ?>

   <? }//for ?>

Tabela a percorrer:

Tabela Horas:

Front End:
Comment: Seu código está um pouco confuso pra mim. você está fazendo dois selects, um de horas que não tenho como saber quais são os dados dessa tabale, e outro repetindo em loop dentro do while.

Acho que você resolveria tudo isso em comparação com um único select. E montando essa tabela de horários ao mesmo tempo que ja faz a comparação com os dados retornados.

Teria que ser analisado com mais tempo e reestruturar o seu código. Mas sobre o `mysqli_fetch_array($qr)`, ja tentou usar assim: `mysqli_fetch_array($qr, MYSQLI_ASSOC)`. Creio que **MYSQLI_ASSOC** evitaria a repetição.
Answer: Acredito que você tenha que criar alguma relação entre o seu for() e as consultas que estão sendo feitas posteriormente.
A cada loop do for() você busca todos os horários em todos os dias cadastrados. Não teria que trazer somente os registros daquele dia específico que é calculado em $justDay = date('Y-m-d', strtotime('+$i days'))?
Outro detalhe é que quando você faz $hrAula = $ftAula['hora_inicio_aula'], você está pegando só o primeiro registro da consulta que pode retornar n registros.
Você pode tentar fazer da seguinte forma então:
$sqlAula = "SELECT id_monta_aula FROM monta_aula WHERE dia_aula = '" . $justDay . "' AND hora_inicio_aula = '" . $ft['hora'] . "' LIMIT 1";

Dessa forma, a cada vez que o while() for executado, a consulta vai buscar uma aula (observe o LIMIT 1) no dia calculado lá em $justDay e em cada horário da query "SELECT * from horas" para esse dia.
Portanto, você só precisará verificar se existe alguma aula nessa consulta:
if (mysqli_num_rows($sqlAula) == 1)
{
    $hc = 'border-class'; // Tem aula nesse dia e horário!
}
else
{
    $hc = 'text-green-d'; // Não tem aula...
}

Não recomendo muito utilizar * nas consultas, por isso retirei, porém depois você pode colocar os campos que precisar.
Lembrando que em termos de performance, também não é muito recomendado que você traga as horas do banco de dados como está sendo feito. Entretanto, acredito que irá funcionar normalmente.
O motivo é bem simples, o for() se repete 12 vezes, ou seja, a cada vez que se repete executará 1 consulta trazendo os horários e mais 14 consultas abaixo (uma para cada horário da tabela). Isso tudo será equivalente a 12 * 15 = 180 consultas.
Espero ter ajudado! :)


What is the length of $EF$ in the following diagram?

Question:

In triangle $\triangle ABC$, angle $A=50^\circ$ , angle $C=65^\circ$ .
  Point $F$ is on $AC$ such that, $BF$ is perpendicular to $A$C. $D$ is
  a point on $BF$ (extended) such that $AD=AB$. E is a point $CD$ such
  that, AE is perpendicular to $CD$. If $BC=12$, what is the length of
  $EF$?

Source: Bangladesh Math Olympiad 2016 Junior Catagory
I tried and proved that $ABF \cong AFD$ and $BCF \cong CFD$. I am not able to find any relation of $EF$ with other sides.
Comment: $F$ is the midpoint of $BD$ and $E$ is the midpoint of $CD$. Hence $EF={1\over2}BC$.
Answer: From the congruent triangles you have already found, you can conclude that
$\triangle ABC \cong \triangle ACD.$
Use the two known angles of $\triangle ABC$ to find the third angle.
You will then be able to show that $\triangle ABC$ and $\triangle ACD$ are isosceles triangles, and that $E$ is the midpoint of $CD.$
Since $AB = AD,$ triangle $\triangle ABD$ also is isosceles and $F$ is the midpoint of $BD.$
These facts should tell you something about the relationship between $\triangle BCD$ and $\triangle FED,$
after which you can find the answer.
Comment: Thank you for the answer. I successfully found that EF = 6. That was a great explanation!
Answer: Angle $CBA=180°-50°-65°=65°=\angle ACB$, so $AB=AC=AD$. In triangle $BCF$, $CE=BC/2$, $FC=BC\cos 65°$ and $\angle FCE = 65°$, so one can find $FE$ with cosine theorem.


Is visualization a useful method of practice?

Question: Sometimes when I am not at practice, I will visualize playing scales or a particular piece on my instrument.
I know that visualization is often used by athletes, but is it often used among musicians? If so, is there advice on how it can be done most effectively?
Comment: [Slightly related question about mental practice](http://music.stackexchange.com/questions/322/do-you-count-mental-practice-when-counting-total-practice-time-for-the-day)
Comment: @Matthew, indeed that was the inspiration for this question, but I intend this to be distinct and elicit more specific suggestions about the method.
Comment: http://www.bulletproofmusician.com/does-mental-practice-work/
Answer: I would consider "visualization," as such, to be more a method of dealing with performance anxiety issues.
However, there is plenty of concrete, actual, musical practice you can do inside your head. It's no replacement for real time with the physical instrument, but time spent score studying, audiating, and practicing fingerings will almost certainly transfer.
Lots of wind instrumentalists, for example, find it easier to match notes with fingerings than with actual pitch. Sight singing an instrumental etude or piece while mimicing fingerings is one method that I have had quite a lot of success with.
Answer: Yes yes yes yes and yes. Sofronitsky and Gieseking both did huge amounts of mental practice. You have to realize that music, as physically manifested, is an epiphenomenon created by what exists in your mind. If your mental image of the music you want to create isn't perfect, how could the physical manifestation of it be? Time spent cultivating a mental image of what you're playing is always time well spent.
Answer: Visualisation and Imagination are absolutely important.
In my case, it is rare for me these days to watch my fingers on the fretboard as I've trained myself to not look.  Sometimes, in mid performance, I can close my eyes and "see the fretboard and see my hands go to certain chords/scales/shapes" well in advance of the music and I will find myself there.
Sometimes, I can do a musical follow the bouncing ball - all in my head.  But this has come over about 5-6 years of practice.  The idea of "seeing and hearing" your instrument in your mind is the first step in truly mastering the skill of improvisation and mastery of the instrument.
Answer: Yes! I watched an interview with legendary electric bassist Jaco Pastorius where he stated that most of his practice at that stage of his life was mental. He would work through different arrangements and solos mentally and when he picked his bass up to play that mental preparation would translate. Since seeing that I've done this myself and have noticed leaps forward in ability or feel within a particular piece after having worked through it mentally.
Answer: The aspect of virtuosity which has always impressed me most is the ability to intuitively navigate a genre's entire musical context (scales, their associated modes and characteristic dynamics) in a way that remains true to the expectations of the knowledgable (genre-native) listener. Underpinning this skill are years of practise - but that may change.
'Visual candy' music visualisations aside, currently we engage musically (in a practice and theory sense) in four main ways:

audio (learning by ear / what we actually hear)
semiotics (music notation / sight reading)
tactile or gesture interfaces (how we interact with instruments, their 'user interfaces').
static visualisations (instrument models, theory diagrams)

Musicians hear songs when they read music, non-musicians seek visual patterns.
Visuals are processed 60,000 times faster than text by the human
brain and 90% of information transmitted to the brain is visual.
Music visualisation in a dynamic, interactive and information-rich sense can be seen as the consummation of that 4th dimension of musical engagement, and will in the future have a profound impact on world music learning, tonal exploration (experimental music) and P2P teaching (visual tools supporting online teaching around the world).

In driving animations directly from music exchange formats such as musicxml or audio, a vast constellation of new practise and learning applications is opened up:

Perhaps 80% of the catalogue of world music instruments can be directly and simply modelled in the browser from their generic (family) base.
Similarly for the related theory tools.
complete instrument model tuning freedom, with a vast choice of automatically generated key- and fretboard roadmaps
(where desired) algorithmically optimised fingering suggestions for every instrument
instrument models and theory tools directly linked by configuration tools, so that simple changes to one are instantly reflected in the other - across the entire spectrum of world music systems.
Music-cultural (modal) landscapes can be explored, where, for example, a mixolydian melody can be visualised in the context of all possible modes of the classical 12-tone, equal temperament system
comparative world musicology (visual comparison of the musical characteristics -intervals, modes and other musical building blocks- of widely differing musical cultures) will be within anyone's reach.
the opportunity to associate unique elements of style to notation and/or instrument models (think typically traditional Irish county Clare or Balkan gypsy rhythmic accentuation, ornamentation or intonation)
every exercise or piece of music opens an own, dedicated field of study across multiple instruments, tools and associated contexts.
opportunities for synergies with other (non-musical) fields of study, such as mathematics, physics or psychology.
structural analysis of a piece of music will help with learning prioritization: which parts to practise most, where one can rely on repetition, where octavisation is required to keep notes within the tonal boundaries of a given instrument, where 'best fit' alternatives can be found, etc..
moreover (and recognising that much world music is purely aural in nature), an strong impetus is provided for the extension of exchange formats such as musicxml to cover music systems not currently represented.

Hindering knowledge advancement is pointless - and ultimately self-destructive. Music visualisation will protect existing musical diversity, enhance the teacher's role, accelerate new learner progress and promote musical experiment.
In summary, what we can expect are score- and audio-driven, highly interactive 2- and 3D visual models of music theory and instruments across the entire world music spectrum, the catalyst for fresh musical adventures.


Reverted edit results in negative reputation?

Question: Just a question ... some minutes ago my reputation was at "1665". An edit i made during the day was reverted by the questioneer, but insead of +2 and -2 I only see -2 reverted ... and reputation is at "1661" (instead of "1663")
Is this intented behavoir?
Comment: can you add the link to the question or the item in the review queue?
Comment: https://magento.stackexchange.com/questions/177678/load-left-nav-in-ajax-request
Answer: I can see the + and the - items in your rep page. See the top and bottom entries.
.
But it seems to me that there is something wrong with your rep calculation.
I ran this very ugly but effective js script in the console while viewing your reputation page:
var total = 0;var elements = jQuery('.rep-cell .rep-up');for (var i = 0 ; i<elements.length;i++) {total += parseInt(jQuery(elements[i]).html())}

The total on the first page adds up to 1609.
The total on the second page adds up to 60.
and running it for the days where you have negative rep days
var total = 0;var elements = jQuery('.rep-cell .rep-down');for (var i = 0 ; i<elements.length;i++) {total += parseInt(jQuery(elements[i]).html())}

it results into -6.
Adding all this up you end up with 1663, as you expect. but you clearly have 1661.
I advice you to post this question on http://meta.stackexchange.com since this does not look to be specific for the magento website.
Comment: Thanks you for investigating it! I'll open a ticket later there.
Comment: Answered here: https://meta.stackexchange.com/a/296889/359101
Comment: This explanation sounds good .... but ... then there must be an error in your script  .... ?!? I don't care about the -2 rep, but it would be interessting, whats wrong here :)
Comment: Could be. You can try checking manually or modifying the script.
Comment: If i sum up the days totals i come up with 1660 + 1 ... Maybe i'll do it manually again later for every entry  :P Thanks again for your time.


How do you customize the colors on the flex webchat widget when consumed through CDN?

Question: I am trying to solely change the color scheme of the widget that customers will use. We are bringing in the widget using the CDN. I have only found documentation for changing color scheme for flex UI that our agents will see. How can I change the colors on the widget?
Answer: Follow the theming guidelines as described in the Twilio documentation here.
Then when initializing the WebChat via CDN pass in your branding like this:
<code><script>
  const appConfig = {
    accountSid: "AC...",
    flexFlowSid: "FO...",
    colorTheme: {
      overrides: brandedColors
    }
  };
  Twilio.FlexWebChat.renderWebChat(appConfig);
</script>
</code>


Different behavior from ubuntu server and ubuntu client on windows

Question: #!/bin/bash

# Reading

cat /home/radiare/Desktop/first.txt | while read LINE

do
if [ "$LINE" == "false" ]; then
echo "Inside first loop"
break
fi
done

cat /home/radiare/Desktop/second.txt | while read LINE

do
if [ "$LINE" == "false" ]; then
echo "Inside second loop"
break
fi
done

In ubuntu client, I could able to execute this script and echo inside if statements are properly working. I did the same thing in ubuntu server it is not going inside the if statement. only difference is I run using sudo on the server.
Any suggestions?
Comment: We can't really debug this for you -- you need to do the legwork here. Your best bet is to print `$LINE` before each `if` statement and see what's going on. (Also I have no idea what you mean by "ubuntu client" - do you mean Ubuntu Desktop Edition as opposed Server or Cloud editions?)
Comment: What is the issue with the "on windows" part in your question title?
Comment: My Ubuntu client is hosted on windows. There is no problem with it.
Comment: I would suspect the content of the files is different on your two machines.  Can you replicate this problem with `echo` rather than `cat`?  (Assuming that the script *is* exactly the same on both machines.)
Comment: Thanks for the reply. files are replicas So the contents are same.
Answer: Try adding -x after the shebang line so it looks like this: #!/bin/bash -x.  The output will look like this:
+ read LINE
+ cat /home/radiare/Desktop/first.txt
+ '[' true == false ']'
+ read LINE
+ '[' true == false ']'
+ read LINE
+ '[' false == false ']'
+ echo 'Inside first loop'
Inside first loop
+ break
+ read LINE
+ cat /home/radiare/Desktop/second.txt
+ '[' true == false ']'
+ read LINE
+ '[' true == false ']'
+ read LINE
+ '[' false == false ']'
+ echo 'Inside second loop'
Inside second loop
+ break

Note that I created a file with these contents for this test:
true
true
false
true

second.txt was a symlink pointing to first.txt.
I also ran it with sudo and got identical results.
Alternatively, you could add an else clause to see what the input looked like when it didn't descend into the if statement:
if [ "$LINE" == "false" ]
then
  echo "Inside first loop"
  break
else
  echo "LINE is $LINE"
fi

Comment: value=$(</var/www/symmetric-ds-3.1.6/bin/my_mon.txt)
if [ "$LINE" == "false" ]; then
echo"Inside loop"
fi
This worked for me. Culprit is cat I guess


Mongo forEach function only performing updates on first row

Question: I have a problem when performing an update within a forEach function, it only updates the first row.
Ok, so I am trying to make a query that updates some fields of my documents but I have the following constraints:
1)One of the fields to update has to be looked up in another collection.
2)Based on the value of one of  the fields I have to decide whether update one way or another.
3)Based on the value of one of the fields I have to delete some fields.
The query I am executing is the following:
db.events_migration.find({'$or':[{'event.type':'EXBC'},{'event.type':'ENBC'}],'event.value.major':{'$exists':true}}).forEach(function (doc1) {
var doc2 = db.regions.findOne({ 'beaconId.major': doc1.event.value.major,'beaconId.minor':doc1.event.value.minor,'group.uuid':doc1.event.value.uuid });

    if (doc2 != null) {

        doc1.event.value.beacon = doc2._id;
        db.events_migration.save(doc1);

        if(doc1.event.type=='EXBC'){
        db.events_migration.update({'_id':doc1.id}, {$set:{'event.source':'SDK','event.type':'MOB','event.extType':'BCN','event.action':'EXT'},
                                                   $unset:{'event.value.major':'','event.value.minor':'','event.value.uuid':''}});

        }
        else{
        db.events_migration.update({'_id':doc1.id}, {$set:{'event.source':'SDK','event.type':'MOB','event.extType':'BCN','event.action':'ENT'},
                                                       $unset:{'event.value.major':'','event.value.minor':'','event.value.uuid':''}});
        }
}
});

The 1st constraint if working effectively. It looks up for a register in another collection and adds it to doc1:
var doc2 = db.regions.findOne({ 'beaconId.major': doc1.event.value.major,'beaconId.minor':doc1.event.value.minor,'group.uuid':doc1.event.value.uuid });
doc1.event.value.beacon = doc2._id;

The problem I am having is when performing the update function for constraints 2 and 3, it only updates for the first register and the others are left as they were.
db.events_migration.update({'_id':doc1.id}, {$set:{'event.source':'SDK','event.type':'MOB','event.extType':'BCN','event.action':'EXT'},
                                                   $unset:{'event.value.major':'','event.value.minor':'','event.value.uuid':''}});

I am somehow new to performing this kind of operations of mongo, so I would appreciate an explanation of why this is happening. Thanks in advance!
Answer: The problem is with the update query projection.
db.events_migration.update({'_id':doc1.id} ...

An id of any document should be accessed with the _id field. In this case id returns undefined.
Updating it as follows (notice underscore) should solve the problem:
db.events_migration.update({'_id':doc1._id} ...

Comment: Thanks Daniel, I got it to work, but I have one more question. I didn't use the multi parameter because I thought that because it was a forEach function it would call the update method for every row, how does this work? If I use the multi param will it be repeting the update for each iteration? Thanks
Comment: Well, my previous answer was misleading, The `multi` argument wasn't a problem in this case. Please extend my apologies. I've updated it. Fill free to ask for more details. I own you for my first answer ;)
Comment: Thanks Daniel!, now it is working like a charm. As I thought and after i checked the logs, the first solution you proposed was performing all the update per iteration, so I was doing it in different scripts. Now it works fine within the forEach function.


How make any array in javascript/jquery with empty elements at 3rd index like ['Aarav', 10, '', , '']

Question: $.ajax({
                            type: "POST",
                            url: "/Login/GetAllAciveProject",
                            data: '{ CountryId: 1}',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (r) {
<code>                            var data11 = [];
                            var Header = ['Name', 'On Time Projects', { role: 'annotation' }, 'Delayed Projects', { role: 'annotation' }];

                            data11.push(Header);
                            debugger;
                            for (var i = 0; i < r.length; i++) {
                                var temp = [];
                                temp.push(r[i].Name);
                                temp.push(r[i].TotalDays);
                                temp.push("");
                                temp.push(null);
                                temp.push("");
                                data11.push(temp);

                            }

                           // need arry like this --> ['Aarav', 10, '', , ''],

                            debugger;
                            var data = google.visualization.arrayToDataTable(data11);
                            var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
                            chart.draw(data, options);
                        },
                        failure: function (r) {
                            alert(r.d);
                        },
                        error: function (r) {
                            alert(r.d);
                        }
                    });
</code>
Answer: Just define the element as undefined:
<code>var arr = ['Aarav', 10, '', undefined, ''];
</code>


my Controller is working fine but Directive is not

Question: ok, so this is my AngularJs Controller which have Directive as well.
now when i run application the main page i design for this controller is working but when i tried to re-use it as directive then i cant see anything, the new HTML page is empty.
AngularJS Controller:
var app = angular.module('dropDown', []);
app.controller('DropDownController', function ($scope, $http) {
GetCountries();
function GetCountries() {
    $http({
        method: 'Get',
        url: '/Home/GetCountries'
    }).success(function (data) {
        $scope.countries = data;
    }).error(function (data) {
        $scope.message = 'Unexpected Error';
    });
}

$scope.GetStates = function () {
    var countryId = $scope.country;
    if (countryId) {
        $http({
            method: 'POST',
            url: '/Home/GetStates',
            data: JSON.stringify({ countryID: countryId })
        }).success(function (data) {
            $scope.states = data;
        }).error(function (data) {
            $scope.message = 'Unexpected Error';
        });
    }
    else {
        $scope.states = null;
    }
}

$scope.GetRegion = function () {
    var countryId = $scope.country;
    if (countryId) {
        $http({
            method: 'POST',
            url: '/Home/GetRegion',
            data: JSON.stringify({ countryID: countryId })
        }).success(function (data) {
            $scope.regions = data;
        }).error(function (data) {
            $scope.message = 'Unexpected Error';
        });
    }
    else {
        $scope.regions = null;
    }
}

$scope.GetShippingStates = function () {
    var countryId2 = $scope.country2;
    if (countryId2) {
        $http({
            method: 'POST',
            url: '/Home/GetStates',
            data: JSON.stringify({ countryID: countryId2 })
        }).success(function (data2) {
            $scope.states2 = data2;
        }).error(function (data2) {
            $scope.message = 'Unexpected Error';
        });
    }
    else {
        $scope.states2 = null;
    }
}

$scope.GetShippingRegion = function () {
    var countryId2 = $scope.country2;
    if (countryId2) {
        $http({
            method: 'POST',
            url: '/Home/GetRegion',
            data: JSON.stringify({ countryID: countryId2 })
        }).success(function (data2) {
            $scope.regions2 = data2;
        }).error(function (data2) {
            $scope.message = 'Unexpected Error';
        });
    }
    else {
        $scope.regions2 = null;
    }
}
});
app.directive('dropdowndirective', function () {
return function() {
    restrict= 'E',
    transclude= true,
    templateUrl= '@Url.Action("AddressControl","Home")',
    //templateUrl= '/Home/AddressControl',
    controller = 'DropDownController',
    replace=true

    }

});

MVC Controller:
using CountryAddressApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;using System.Web;
using System.Web.Mvc;

namespace CountryAddressApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult AddressControl()
        {
            return View();
        }
        public JsonResult GetCountries()
        {

using (CountryAddressEntities context = new CountryAddressEntities())
        {
            var ret = context.Countries.Select(x => new { x.CountryID, x.CountryName }).ToList();
            return Json(ret, JsonRequestBehavior.AllowGet);
        }
    }

    [HttpPost]
    public JsonResult GetStates(int countryId)
    {
        using (CountryAddressEntities context = new CountryAddressEntities())
        {
            var ret = context.States.Where(x => x.CountryID == countryId).Select(x => new { x.StateID, x.StateName }).ToList();
            return Json(ret);
        }
    }

    [HttpPost]
    public JsonResult GetRegion(int countryId)
    {
        using (CountryAddressEntities context = new CountryAddressEntities())
        {
            var ret = context.Regions.Where(x => x.CountryID == countryId).Select(x => new { x.RegionID, x.RegionName }).ToList();
            return Json(ret);
        }
    }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Testing()
    {
        return View();
    }
}
}

My Main-Page
AddressControl.cshtml
@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Multi-National Address</title>

            Billing Address
            Shipping Address

                        <form name="mainForm" data-ng-submit="sendForm()" novalidate>

{{message}}

                                            Select Country:

                                            <select data-ng-model="country" data-ng-options="c.CountryID as c.CountryName for c in countries" data-ng-change="GetStates()">
                                                <option value="">-- Select Country --</option>
                                            </select>

                                            Select State:

                                            <select data-ng-model="state" data-ng-disabled="!states" data-ng-options="s.StateID as s.StateName for s in states" data-ng-change="GetRegion()">
                                                <option value="">-- Select State --</option>
                                            </select>

                                            Select Region:

                                            <select data-ng-model="region" data-ng-disabled="!regions" data-ng-options="r.RegionID as r.RegionName for r in regions">
                                                <option value="">-- Select Region --</option>
                                            </select>

                                            Address:

                                            <input id="Address" name="Address" placeholder="Address" type="text" />

                                            Address 2:

                                            <input id="Address2" name="Address2" placeholder="Address 2" type="text" />

                                            City:

                                            <input id="city" name="city" placeholder="City" type="text" />

                                            Zip Code:

                                            <input id="zipcode" name="zipcode" placeholder="Zip Code" type="text" />

                                            Select Province:

                                            <select data-ng-model="state" data-ng-disabled="!states" data-ng-options="s.StateID as s.StateName for s in states" data-ng-change="GetRegion()">
                                                <option value="">-- Select Province --</option>
                                            </select>

                                            Select Region:

                                            <select data-ng-model="region" data-ng-disabled="!regions" data-ng-options="r.RegionID as r.RegionName for r in regions">
                                                <option value="">-- Select Region --</option>
                                            </select>

                                            Address:

                                            <input id="Address" name="Address" placeholder="Address" type="text" />

                                            Address 2:

                                            <input id="Address2" name="Address2" placeholder="Address 2" type="text" />

                                            City:

                                            <input id="city" name="city" placeholder="City" type="text" />

                                            Postal Code:

                                            <input id="postalcode" name="postalcode" placeholder="Postal Code" type="text" />

                        </form>

                        <form name="mainForm" data-ng-submit="sendForm()" novalidate>

{{message}}

                                            Select Country:

                                            <select data-ng-model="country2" data-ng-options="c.CountryID as c.CountryName for c in countries" data-ng-change="GetShippingStates()">
                                                <option value="">-- Select Country --</option>
                                            </select>

                                            Select State:

                                            <select data-ng-model="state2" data-ng-disabled="!states2" data-ng-options="s.StateID as s.StateName for s in states2" data-ng-change="GetShippingRegion()">
                                                <option value="">-- Select State --</option>
                                            </select>

                                            Select Region:

                                            <select data-ng-model="region2" data-ng-disabled="!regions2" data-ng-options="r.RegionID as r.RegionName for r in regions2">
                                                <option value="">-- Select Region --</option>
                                            </select>

                                            Address:

                                            <input id="Address" name="Address" placeholder="Address" type="text" />

                                            Address 2:

                                            <input id="Address2" name="Address2" placeholder="Address 2" type="text" />

                                            City:

                                            <input id="city" name="city" placeholder="City" type="text" />

                                            Zip Code:

                                            <input id="zipcode" name="zipcode" placeholder="Zip Code" type="text" />

                                            Select Province:

                                            <select data-ng-model="state2" data-ng-disabled="!states2" data-ng-options="s.StateID as s.StateName for s in states2" data-ng-change="GetShippingRegion()">
                                                <option value="">-- Select Province --</option>
                                            </select>

                                            Select Region:

                                            <select data-ng-model="region2" data-ng-disabled="!regions2" data-ng-options="r.RegionID as r.RegionName for r in regions2">
                                                <option value="">-- Select Region --</option>
                                            </select>

                                            Address:

                                            <input id="Address" name="Address" placeholder="Address" type="text" />

                                            Address 2:

                                            <input id="Address2" name="Address2" placeholder="Address 2" type="text" />

                                            City:

                                            <input id="city" name="city" placeholder="City" type="text" />

                                            Postal Code:

                                            <input id="postalcode" name="postalcode" placeholder="Postal Code" type="text" />

                        </form>

New html to re-use directive:
@{
    Layout = null;
}

Index

    <dropdowndirective>

    </dropdowndirective>

    @*

*@

Comment: What error message are you receiving?
Comment: no error, but my view is receiving nothing no data travelling from angularjs controller to view
Comment: if i comment out directive section then my application is working data is traveling, but boss want me to write it once and re-use it as many time we want like directive but what i created was controller
Answer: It looks like you have a syntax error in your directive where dropDownController should be a string like this:
app.directive('DropDownDirective', function () {
return {
    restrict: 'E',
    templateUrl: 'AddressControl',
    controller: 'DropDownController',
    replace:true,

    }

});

Not sure why you wouldn't get an error message for that though...
Comment: i have changed my directive as below

app.directive('DropDownDirective', function () {
    return {
        restrict: 'EAC',
        transclude: true,
        //template: '@Url.Action("AddressControl","Home")',
        template: '/Home/AddressControl',
        controller: 'DropDownController',
        replace:true,

        }

    });

does this looks fine ?

also i found error when i checked with browser:

Uncaught ReferenceError: angular is not defined
Comment: Now the controller is correct but you changed templateURL to just template, and I don't think that will work - you probably need to change it back to templateURL. Is it currently working for you?
Comment: i tried both but its not working, even that html is not showing into my index page
Comment: Just noticed in your previous comment that you're getting an error "angular not defined"... the problem is probably not with this directive, but with the order that scripts are loading on the page. See this question: http://stackoverflow.com/questions/21440295/uncaught-referenceerror-angular-is-not-defined-angularjs-not-working
Comment: i corrected that, now no error but still there is nothing happening.

can you suggest any tutorial to follow to create directive and controller fetching data from database
Comment: Your googling for tutorials would be as good as mine but your controller and directive look fine at a high level. I'd recommend looking at your $http request to the database, make sure you're handling the promise correctly and not doing the wrong stuff before the data comes back from the server, and I'd use breakpoints in Dev Tools to debug the page load and see where it goes awry. https://developer.chrome.com/devtools/docs/javascript-debugging, also Batarang can help with debugging angular: https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk?hl=en
Comment: can i have your email address, i can email you mu solution for your guidance ......
Comment: i m really stuck with this, only controller is working as soon as i added directive it stopped working.

even i cant see the main page (where i have designed the dropdown, textbox) html or text in my new html (where i m using directive to travel the html from main page)
Comment: Can you get the HTML in the directive's template to work if you add it directly to the main HTML page and put the directive logic in the template and remove the directive? If that works, then the problem is definitely in the directive, so that would start to narrow down the problem...
Comment: ok so i just made changes with tamplate and made it as

templateUrl: "AddressControl"

it worked, its working fine ...... thanks Jordajm ..... :)
Comment: now how can make a checkbox working says same as billing address

what should i do? how should i write and what example should i follow.
Comment: Sounds like a separate question - could you accept this answer as correct, then post another question about the checkbox with only the relevant code?


Issues trying to understand and debug simplesamlphp error

Question: Simplesamlphp used to work on the site. Something changed and now it does not.

The IDP remote config has been verified, including the cert
The SP cert and pem in the simplesamlphp/config folder have been verified
All the required settings show green on the admin page
When the ACS URL is entered as a test, a JSON file with the metadata is downloaded

All there seems correct. But when a user attempts to login, the following is thrown into the log file. I note that despite the entry about the candidate having :443, the URL with or without the port results in identical json.
This is Drupal 8.9.6, PHP 7.3.21, simplesamlphp_auth 8.x-3.2, simplesamlphp 1.18.8

simplesamlphp ERROR [ffdf5e0102] SimpleSAML\Error\Error: UNHANDLEDEXCEPTION
simplesamlphp ERROR [ffdf5e0102] Backtrace:
simplesamlphp ERROR [ffdf5e0102] 1 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/www/_include.php:17 (SimpleSAML_exception_handler)
simplesamlphp ERROR [ffdf5e0102] 0 [builtin] (N/A)
simplesamlphp ERROR [ffdf5e0102] Caused by: SimpleSAML\Error\Exception: > This SP [https://admin.mysite.gov/simplesaml/module.php/saml/sp/metadata.php/default-sp]  is not a valid audience for the assertion. Candidates were: [https://admin.mysite.gov:443/simplesaml/module.php/saml/sp/metadata.php/default-sp]
simplesamlphp ERROR [ffdf5e0102] Backtrace:
simplesamlphp ERROR [ffdf5e0102] 4 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/lib/Message.php:718 (SimpleSAML\Module\saml\Message::processAssertion)
simplesamlphp ERROR [ffdf5e0102] 3 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/lib/Message.php:640 (SimpleSAML\Module\saml\Message::processResponse)
simplesamlphp ERROR [ffdf5e0102] 2 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/www/sp/saml2-acs.php:141 (require)
simplesamlphp ERROR [ffdf5e0102] 1 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/lib/SimpleSAML/Module.php:260 (SimpleSAML\Module::process)
simplesamlphp ERROR [ffdf5e0102] 0 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/www/module.php:10 (N/A)
simplesamlphp ERROR [ffdf5e0102] Error report with id 86f8550b generated.
Comment: `Something changed` – That's the key. So what changed? Have you double-checked Apache config?
Comment: All you can do is a diff of what was there before and what is there now. https://groups.google.com/g/simplesamlphp/c/ga2enXsY3PA
Comment: Last worked in Jan. The cloud hoster's been working this with us since, as has the authenticator. It's nginx. There doesn't seem to be anything nginx related. Drupal version has changed (all 8.x), as has php (from 7.2 to 7.3). If it were either of those, the problem should be well known and reported by now, I'd think. There is no access log error accompanying the simplesamlphp log error. I think the key is why it is highlighting that binding, why 443 makes a difference, since it doesn't when hitting both url's, and whether that url should result in a json download like it does.
Comment: Not possible. For a start, cannot diff cloud environment. I need to proceed as if it never worked and figure out why, what specifically it's unhappy with.
Answer: It turns out that the issue was the entityID on the authenticator end containing the port number, and the default entityID provided by simplesamlphp not so. Having the authenticator change their config entries, dropping the explicit port reference, resolved the issue.


Melhorar a performance de um método com ponteiros

Question: Aqui vai o código funcionando:
string string_pick(string text, string tag, char caractere)
{
    int index = text.IndexOf(tag);
    return text.Substring(index + tag.Length, text.IndexOf(caractere, index + tag.Length + 1) - (index + tag.Length));
}

Exemplo de funcionamento:
string x = "kkkkkkkkkkkk jjjjjjjjjjj oloco icaro alguma coisa algumas palavras várias loucuras name:'icaro' lalala huhuasd sdiufhidf sdifuhisuhdf kkkkkkk";
string temporaria = string_pick(x,"name:'",'\'');

A temporária vai ser "icaro".
Bem, como vai mexer com uma string gigantesca, eu gostaria de apenas acessar aquela parte de memória e não copiar a string novamente (no caso do que o argumento da função está fazendo).
No C++ resolvi assim:
string string_pick(string *text, string tag, char caractere)
{
    int index = (*text).find(tag);
    return (*text).substr(index + tag.length(), (*text).find(caractere, index + tag.length() + 1) - (index + tag.length()));
}

Comment: Primeiro, se decida se é C++ ou C#. O segundo código não compila em nenhuma das duas. O primeiro parece que compila em C#. Coloque um [mcve]. Aproveite e explique melhor qual a intenção.
Comment: Cara, o segundo foi uma tentativa, ele realmente não funciona, deu errado aqui, mas eu estou explanando apenas oque eu quero entende?
Comment: Quanto ao C++ ou C#, é por que quem sabe em C++ provavelmente saberia em C# já que muda pouca coisa ali...
Comment: Eu vou responder o que dá mas se fizesse o que eu te pedi eu poderia dar uma resposta melhor.
Comment: Me desculpe, é meu primeiro post nesse overflow, eu vou ler oque você mandou
Answer: Antes de mais nada fazer coisas doidas que "funcionam" não é programar. Fazer o que é certo é programar. Funcionar não é parâmetro para saber se está certo. Não vou dizer se isto está certo ou não porque não há informações suficientes para isto.
Mesmo que fosse possível colocar o ponteiro em C# (até existe como, mas em situações bem específicas que não vale falar aqui) fazer o que está tentando não resolveria nada para economizar memória já que dentro do método já está criando uma nova instância. Se há algum problema de consumo de memória, e mesmo isto é questionável, é dentro do método e não na comunicação dele com o mundo externo que só copia a referência e é bem eficiente.
Se fosse outro problema a classe StringBuilder poderia ser uma solução. Mas o caso nem demonstra ter um problema real de performance ou alocação excessiva. E se tiver a pergunta deveria demonstrar. E só deveria se preocupar com isso se o problema for real e não apenas uma suposição.
O código escrito em C++ não é nem um pouco mais eficiente do que o escrito em C#. Alias é uma completa desnecessidade usar ponteiro ali. Só está criando uma indireção sem sentido. Provavelmente está creditando uma qualidade ao ponteiro que ele não tem.
O código pode ser simplificado e ter uma melhor nomenclatura. Pode começar em usar o nome no padrão StringPick(). Os nomes dos parâmetros poderiam indicar melhor sua função aí, não só dizer o que terá nele, isto o tipo já diz.
Só para dar uma ideia do que pode ser melhorado. Eu faria melhor se soubesse os requisitos reais.
Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: Por que string_pick: Por que eu imagino eu eu estou minerando uma palavra com uma picareta...(quanto a isso é inquestionável).
Quanto a sua funcionalidade, ele pega uma página em html e pega uma palavra que está dentro de uma tag, ex:
string_pick(htmlpage,"name:'",'\''); Nesse caso ele pega oque está entre Name:' e '
Comment: reformulei a pergunta e coloquei do modo que funcionou em c++, da uma olhada
Comment: Obrigado pela ajuda, é por que eu vi uma aula de ponteiros e do nada comecei a imaginar que ponteiros iriam diminuir o processo.

Como você perguntou ali se é um problema real ou uma suposição, vou responder, é um problema real de um programa que eu fiz pro meu tio, tem uma parte do processo que faz um _loop_ com isso ai, e no meu computador esse _loop_ demora 6 minutos, o dele é uns 11 anos mais velho e eu imagino que possa demorar até 2 horas pra realizar a tarefa, por isso eu estava querendo melhorar a função.
Comment: Olha a otimização que eu consegui: (https://s31.postimg.org/ggz0ak3ff/Sem_t_tulo.png)
Comment: E perfilou para descobrir onde ´o problema. Não parece ser onde está falando. De qualquer forma, o que dava pra ajudar nessa pergunta eu ajudei, o problema nem está claro.
Comment: O problema é que eu estava pensando em formas de deixar essa função mais rápida, eu estava imaginando se não seria melhor em vez de copiar uma nova string, simplesmente trabalhar em cima da original... Mas isso nem é muito lento, esquece kk