Responsive not working after converting html theme to Drupal theme

Question: While trying to convert a HTML responsive theme to Drupal 7 theme, it's responsive is not working!!!
Can anyone help me with this to sort the issue? We have copied Bartik theme and removed the CSS and pasted the HTML5 theme CSS and JS that we created. changed the index.tpl into page --front.tpl.php and copied it into the template folder. In the page-- front.tpl.php we give all the path for CSS and JS as:
<?php $path="http://".$_SERVER['HTTP_HOST']; ?>
<link rel="icon" href="$path.">
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="<?php echo $path.base_path().path_to_theme()?>/css/style.css">.

"As specified we gave path for all CSS and JS files, but don't know where we went wrong!!"
Answer: To create or convert a Drupal 7 responsive theme, it is not a good idea to start with stripping down and modifying a fully developed, non-responsive theme such as Bartik.
Instead you start out with a responsive starter theme or base theme framework, where the css is already reset for you and where the the framework is already prepared for you to add your own classes to construct whatever look and feel you're after.  Basically, you install your framework, then create a sub-theme, and use that you build your own responsive theme.
Good foundations for this is IMHO Zen, Omega or AdaptiveTheme (suggested by @Kojo in a comment), but many other alternatives exist.
Comment: And from the most complete responsive theme frameworks I would name also adaptive theme :)
Answer: For converting HTML templates into Drupal templates you have to follow the given steps :
Starting your page
If you're using Drupal 5:
" xml:lang="">
If you're using Drupal 6:
language ?>" xml:lang="language ?>" dir="dir ?>">
If you're using Drupal 7:
If you are using Drupal 7, your page.tpl.php file starts after the  tag and end before the  tag, so you do not need to worry about the doctype, html, or head tags. If you'd like to override these, copy the html.tpl.php file from your modules/system folder and make whatever changes you'd like.
The  section of your site

In the above section given how we can convert HTML template into Drupal theme templates please refer this link for more info https://drupal.org/node/313510
Comment: Thank you for your response sir..we need to know the how to delete or remove the css file permenanently from a theme and add our created css into the theme and where to add this code i.e in which file?as stated below  we used hook_css_alter to unset that css ,but its not working...function will_css_alter(&$css)
{
    if () { //Unset CSS file if the current page is your custom page
        $path = drupal_get_path('theme', 'will');
        unset($css[$path . '/css/main.css']);
    }
}   "As we are beginners to drupal and trying to create a responsive single page website"
Comment: For adding css into theme you can use theme .info file and add css here if you want to replace any css just add the css into info file with same name whatever you want to replace ex. stylesheets[all][] = theStyle.css into info file and if you want to add css dynamically you can use function drupal_add_css()  see https://drupal.org/node/171209 and https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7
Comment: Even after doing that the responsive is not working ,responsive is set for first page,but rest 4 pages there's no effect,without getting responsive right we can't proceed further.Any idea why is it not working for other 4 pages!!
Comment: Can you please describe what version of Drupal you are using and what procedure you have followed for converting html templates to drupal theme templates?
Comment: we are using drupal 7 and for converting html to drupal we first renamed the index.html as page--front.tpl.php and we removed the css of the existing theme using hook_css_alter in template.php.Next we copied the css and js files from the created html folder and  in .info file we added all the css and js files ..after that in the page--front.tpl.php we added our css as:  the issue is header part has become responsive but other pages stil remain unaffected
Comment: Can anyone give us a possible solution to overcome this!!!
Answer: You can probably start with whatever theme you like, certainly some require more work then others if you're looking for a sensible set of base styles and a nice grid system.
However, I suspect, your main issue is the them you're starting with is missing the meta tag to set the zoom level on a device. If you're checking this on a computer's browser then it's something in the css. What does dev tools tell you? Something has to have a fixed width applied to it if it is overflowing your desktop browser window.
Comment: We added meta tags earlier as stated below:
   ....Even after using this the font sizes is getting reduced but in case of mobile devices the width is not getting adjusted.


Como otimizar o jogo batalha naval em JAVA?

Question: Não sei se isso é permitido aqui no site, então caso eu esteja quebrando alguma regra me avisem!
Comecei, recentemente, a aprender a linguagem JAVA. Fiz um jogo de batalha naval (humano x computador) usando tudo o que aprendi até agora e gostaria de ouvir opiniões de programadores mais experientes sobre o game, a fim de melhorar meus conhecimentos.
Alguns pontos como o que você teria feito de diferente? Como você otimizaria o código já existente? Cometi alguma redundância ou escrevi mais do que o necessário?
Como pensei a programação do jogo?
Criei duas arrays 5x5. Uma armazena o tabuleiro do jogo. Ela é iniciada com o valor padrão 0 para todos os elementos. Com um método, faço ser sorteado 3 desses elementos, que passarão a representar a posição dos barcos a serem afundados. À eles atribuo o valor 1. A outra array armazena as posições onde o jogador disparou, 0 simboliza uma área onde ainda não se atacou e 1 uma área onde se atacou.
Para exibir o tabuleiro, cruzo as duas arrays em uma verificação. Onde ainda não se atacou, consta como "~", onde se atacou e não há navio como "*" e onde se atacou e afundou um navio como "X". Criei um método para que a cada turno seja exibida uma dica informando se a quantidade de navios existentes na linha e na coluna do último disparo realizado.
Código:
BatalhaNaval.java
package batalhanaval;
import java.util.Scanner;

public class BatalhaNaval
{
    public static void main(String[] args)
    {
        Scanner entrada = new Scanner(System.in);
        Tabuleiro tab = new Tabuleiro();
        char option; //Opção do menu principal

        do
        {
            showMenu();
            option = entrada.next().charAt(0);
            System.out.println("\n\n");
            switch(option)
            {
                case '1': //Novo jogo
                {
                    initGame(entrada, tab);
                    break;
                }
                case '2':
                {
                    System.out.println("O seu objetivo no jogo é afundar os 3 navios inimigos que encontram-se no seu litoral.\n"
                            + "Para fazer um disparo, informe a posição(linha e coluna) do seu mapa na qual deseja lançar o míssel.\n"
                            + "O símbolo ~ indica uma área ainda não conhecida.\n"
                            + "O símbolo * indica uma área na qual você disparou e não havia nenhum navio.\n"
                            + "O símbolo X indica uma área onde você afundou um navio inimigo.\n"
                            + "A cada disparo realizado você receberá uma dica informando se há navios na linha e na coluna nas quais você realizou o disparo.");
                    break;
                }
                case '3': //Recorde
                {
                    if(tab.recorde == 1000)
                    {
                       System.out.println("<Recorde atual: nenhum>");
                    }
                    else
                    {
                       System.out.println("<Recorde atual: " + tab.recorde + " turnos>");
                    }
                    break;
                }
                case '4':
                {
                    System.out.println("Finalizando...");
                    break;
                }
                default:
                {
                    System.out.println("Opção inválida!");
                }
            }
            System.out.println("\n");
        }while(option != '4');

    }
    //Método que retorna true caso a String seja um número inteiro
    public static boolean isInt(String str)
    {
        try
        {
            Integer.parseInt(str.trim());
            return true;
        }
        catch (NumberFormatException ex)
        {
            return false;
        }
    }
    //Main menu
    public static void showMenu()
    {
        System.out.println("Bem vindo ao jogo <Batalha Naval>!!! (Criado por Talendar)\nEscolha uma opção:");
        System.out.println("1 - Novo jogo");
        System.out.println("2 - Tutorial");
        System.out.println("3 - Recorde");
        System.out.println("4 - Sair");
    }
    //Jogo
    public static void initGame(Scanner entrada, Tabuleiro tab)
    {
        String linha = ""; //As variáveis linha e coluna foram criadas como String para poderem ser submetidas a checagem do método isInt(str) localizado abaixo.
        String coluna = "";

        tab.initTab();
        tab.initShips();
        do
        {
            System.out.println("\n");
            //Exibe a dica a partir do segundo turno
            if(tab.turno > 1)
            {
                tab.dica(Integer.parseInt(linha), Integer.parseInt(coluna));
            }
            System.out.println();

            //Exibe o tabuleiro em seu estado atual
            tab.printTab();

            //Pede a linha
            System.out.print("Linha:");
            linha = entrada.next();
            while(!isInt(linha))
            {
                System.out.println("Apenas números inteiros de 1 a 5!\nLinha:");
                linha = entrada.next();
            }
            while(Integer.parseInt(linha) < 1 || Integer.parseInt(linha) > 5)
            {
                System.out.println("Apenas números inteiros de 1 a 5!\nLinha:");
                linha = entrada.next();
            }

            //Pede a coluna
            System.out.print("Coluna:");
            coluna = entrada.next();
            while(!isInt(coluna))
            {
                System.out.println("Apenas números inteiros de 1 a 5!\nColuna:");
                coluna = entrada.next();
            }
            while(Integer.parseInt(coluna) < 1 || Integer.parseInt(coluna) > 5)
            {
                System.out.println("Apenas números inteiros de 1 a 5!\nColuna:");
                coluna = entrada.next();
            }
            System.out.println("\n\n");

            //Tiro
            tab.tiro(Integer.parseInt(linha), Integer.parseInt(coluna));
            System.out.println();

        }while(tab.acertos != 3);
        System.out.println("\nVOCÊ DERROTOU O INIMIGO!!!! Turnos: " + tab.turno);
        if(tab.turno < tab.recorde)
        {
            tab.recorde = tab.turno;
            System.out.println("\nNOVO RECORDE (" + tab.recorde + ")!!!!");
        }
    }
}

Tabuleiro.java
/* Água não descoberta(~)
   Água vazia(*): 0
   Navio(X): 1
*/
package batalhanaval;
import java.util.Random;

public class Tabuleiro
{
    int turno = 1; //Turno em questão
    int acertos = 0; //Armazena o número de acertos
    int recorde = 1000; //Armazena o recorde
    int[][] tab = new int[5][5]; //Tabuleiro
    int[][] tiros = new int[5][5]; //Armazeana as posições dos tiros dados: 0 para área desconhecida e 1 para área onde se atirou.

    // Inicia o tabuleiro com o valor padrão 0
    public void initTab()
    {
        acertos = 0;
        turno = 1;
        for(int[] i: tab)
        {
            for(int j = 0; j < i.length; j++)
            {
                i[j] = 0;
            }
        }
    }
    //Sorteia os navios
    public void initShips()
    {
        Random rand = new Random();
        int i; //Linha
        int j; //Coluna

        for(int n = 0; n < 3; n++)
        {
            do
            {
                i = rand.nextInt(5);
                j = rand.nextInt(5);
            }while(tab[i][j] != 0);
            tab[i][j] = 1;
        }
    }
    //Mostra o tabuleiro de inteiros
    public void printTabInt()
    {
        System.out.print("     (1)  (2)  (3)  (4)  (5)\n\n");
        for(int i = 0; i < tab.length; i++)
        {
            System.out.print("("+ (i+1) + ")  ");
            for(int j = 0; j < tab[i].length; j++)
            {
                System.out.print(" "+tab[i][j]+"   ");
            }
            System.out.println("\n");
        }
    }
    //Mostra o tabuleiro de jogo
    public void printTab()
    {
        System.out.print("     (1)  (2)  (3)  (4)  (5)\n\n");
        for(int i = 0; i < tab.length; i++)
        {
            System.out.print("("+ (i+1) + ")  ");
            for(int j = 0; j < tab[i].length; j++)
            {
                if(tiros[i][j] == 1)
                {
                    if(tab[i][j] == 1)
                    {
                        System.out.print(" X   ");
                    }
                    else
                    {
                        System.out.print(" *   ");
                    }
                }
                else
                {
                    System.out.print(" ~   ");
                }
            }
            System.out.println("\n");
        }
    }
    //Tiro
    public void tiro(int linha, int coluna)
    {
        if(tiros[linha-1][coluna-1] == 0) //Checa se já foi dado tiro na posição fornecida
        {
            tiros[linha-1][coluna-1] = 1; //Muda o valor da posição fornecida para que conste como uma área atirada
            if(tab[linha-1][coluna-1] == 1) //Checa se há um navio na posição fornecida
            {
                System.out.println("Você afundou um navio inimigo!!!");
                acertos++; //Aumenta +1 em acertos
            }
            else
            {
                System.out.println("Você atingiu a água...");
            }
            turno++; //Avança o turno
        }
        else
        {
            System.out.println("Você já atirou nessa posição!");
        }
    }
    //Dica: informa o turno e se há alguma navio na linha e na coluna do último tiro disparado
    public void dica(int linha, int coluna)
    {
        System.out.println("Turno: " + turno);

        int countL = 0;
        for(int i: tab[linha-1])
        {
            if(i == 1)
            {
                countL++;
            }
        }
        System.out.println("Dica: há " + countL + " navio(s) na linha " + linha);

        int countC = 0;
        for(int[] i: tab)
        {
            if(i[coluna-1] == 1)
            {
                countC++;
            }
        }
        System.out.println("      há " + countC + " navio(s) na coluna " + coluna);
    }
}

Comment: Ou pode aguardar ver se alguém pode ajudar, já que a pergunta está totalmente dentro das regras e do escopo deste site. O texto poderia ser mais organizado para favorecer quem for tentar ajudar. Separar cada parte em um parágrafo já ajudaria, mas poderia se colocar no lugar de quem for ajudar em um código que ele nunca viu e tentar passar a informação de um jeito melhor.
Comment: Se você puder re-escrever a pergunta em inglês, sugiro mover ela para http://codereview.stackexchange.com, esse site foi feito com o objetivo de revisar códigos nas perguntas. Você também ainda pode fazer pergunta sobre algo específico em relação à performance no StackOverflow (pt, es, en, jp, etc)
Comment: Eu concordo com o @bigown: a sua pergunta faz parte do escopo do site. Só que ela está difícil de ser respondida de forma objetiva. Vc menciona "otimização" (o que, por princípio, eu entendo "desempenho"), mas o seu jogo é bem simples e não parece ter qualquer problema grave de desempenho. Sobre a forma como você implementou, ela está correta e te serve à sua necessidade *atual*.
Comment: Aí você pergunta se alguém teria feito algo diferente. Possivelmente. Mas uma pergunta que talvez seja mais apropriada seria: como tornar esse código mais fácil de ser evoluído? (para incluir embarcações com formatos diferentes de apenas uma célula, por exemplo). Aí a pergunta deixa de ser tanto opinativa, mas ainda fica ampla. Eu começaria por representar cada navio por uma classe e implementar nessa classe a detecção de "colisão" (se um tiro atingiu ou não). Pode ser um bom exercício pra vc, e quem sabe até gerar outras perguntas suas aqui no site. :)
Answer: Creio que você esteja pesquisando para ter mais conhecimentos sobre boas práticas de código, orientação a objetos, testes automatizados e assim por diante.
Sugiro que você mesmo tenha o senso crítico de auto-avaliar seu código a fim de procurar falhas. Bons programadores aprendem com o próprio erro.
Para tentar elevar seu conhecimento, vou sugerir alguns temas com links para você se aprofundar no assunto. Segue alguns:
TDD (Test Driven Design):
Desenvolvimento de software baseado em testes. Você evolui o seu código apenas para o teste passar. Isso facilita com que você construa um melhor design da sua arquitetura e objetos, garantindo simplicidade, baixo acoplamento e cobertura automática dos seus testes.
Orientação a Objeto
Garante que seu sistema possua classes com um único propósito e que se comunicam entre si, garantindo sua manutenibilidade, usabilidade e evolução do sistema.
Caso se interesse pelo assunto, criei 10 regras para garantir que seu código siga as boas práticas de orientação a objetos baseada no livro "The ThoughtWorks Anthology: Essays on Software".
https://github.com/matheusmessora/OOP-MANIFESTO

Vou citar alguns exemplos do seu código que infrinja algumas regras:
Regra 4: Apenas 1 ponto por linha
Melhora a legibilidade do código.
O trecho de código abaixo viola essa regra, dificultando sua leitura.
tab.dica(Integer.parseInt(linha), Integer.parseInt(coluna));

Uma melhor prática seria
Integer linha = Integer.parseInt(linha);
Integer coluna = Integer.parseInt(coluna);
tab.dica(linha, coluna);
Regra 9: Método deve possuir apenas 7 linhas de código.
Isso garante que seus métodos tenham alta coesão, ou seja, fazem apenas o que devem fazer, e nada mais.
Seu método printTab por exemplo infringe a regra.

Para finalizar, devo acrescentar que todo método deve ficar no infinitivo. Isso é uma boa prática adotada em muitas linguagens orientadas a objeto.
Neste caso, o método tab.dica deveria ser alterado para tab.exibirDica(...)
Comment: `Bons programadores aprendem com o próprio erro`, verdade, os maus não só insistem no erro, mas nem reconhecem quando estão cometendo. Maus programadores seguem regras, não entendem pra que elas servem, outro vão ainda mais longe e inventam regras completamente sem fundamento. TDD não tem nada a ver com a pergunta. E o que faz construir sistemas melhores é conhecimento real e experiência qualitativa. Sem isso pode usar a ferramenta que quiser que vai sair coisa errada. OOP não garante nada, muito menos o que foi afirmado. Saber fazer sistemas corretamente e aplicar esse conhecimento ajuda...
Comment: Note que lá não fala em OOP. Alguns dos erros mais graves não estão lá. Mas ainda tem regras tolas sem explicação. O problema é que muita gente lê essas listas, não sabem nada de nada e acreditam que elas são boas e seguem cegamente porque é o que elas têm à mão. Embora a intenção seja ajudar, muitas vezes acaba prejudicando.
Comment: ...alguma coisa, mas também não garante. OOP não é panaceia e na verdade como poucas pessoas sabem fazer certo, tem mais prejudicado do que ajudado. Existem outras ferramentas com objetivos semelhantes. Bons programadores as conhecem e aplicam a melhor para cada caso, não acham que uma só ferramenta resolve tudo. Na minha opinião a resposta mais prejudica que ajuda por colocar coisas que não tem relevância para a pergunta, tendenciosamente com base em informações sem fundamento e universalmente consideradas errôneas.
Comment: Me desculpe, mas essas 10 regras, além de, no geral, não ter nada a ver com OOP, são todas erradas, algumas por um pequeno detalhe, outras com erro grave, até porque está dizendo para fazer o oposto do que deve. Todas são ruins porque elas estabelecem o que fazer sem um contexto. Nenhuma faz sentido no uso geral, algumas fazem sentido em algo muito específico, tão específico que jamais poderia ser usada em uma texto que tenta dizer o que é bom ou não. Não vou ficar debatendo o assunto, meu objetivo é só alertar as pessoas que essa resposta prega uma vontade pessoal e não algo consolidado..
Comment: Aliás, a sua regra 4 é conflitante com a sua regra 9, porque ao se seguir a regra 4 se está justamente aumentando o número de linhas (ou de colunas, se vc optar por colocar *tudo* numa única linha)  - o que, pelo que afirma a regra 9, tende a diminuir a "coesão" (cujo significado que você emprega não está claro).
Comment: As "10 regras" são baseadas do "Object calisthenics" de Jeff Bay. São regras para serem praticadas para melhorar suas skills em programação, e sim, não devem ser usadas em todo projeto. Existem N+1 solução para a pergunta acima, o que eu quis propor aqui era abrir a mente do questionador para novos temas, a fim de elevar os conhecimentos dele.

http://www.javaworld.com/article/2081135/core-java/object-calisthenics-change-the-way-you-code.html
Comment: Sem entrar no mérito da qualidade da tal lista, eu discordo da aplicação da regra 4 no exemplo que você forneceu. Primeiramente, a linha do jeito que está é suficientemente clara pra quem conhece a linguagem. Em segundo lugar, se a questão é esforço (de digitar `Integer.parseInt` para cada parâmetro) porque o método espera um tipo diferente do utilizado, uma "solução" melhor (mais clara) seria implementar uma sobrecarga do método `dica` da classe `tab`. Ou usar o tipo de dado correto. Ou já convertê-lo no momento que ele é produzido. Definitivamente, a troca que você sugere é 6 por meia dúzia.


C++, random number w/ range of 1-6

Question: I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.
Comment: Possible duplicate of [How to generate a random number in C++?](https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c)
Comment: I think this question should be closed, read this: https://stackoverflow.com/a/13445752/5550963
Answer: This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
<code>#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(0));
    std::cout << (rand() % 6 + 1) <<std::endl;
    return 0;
}
</code>
Comment: The terribleness of `rand()` aside, this is almost certainly going to be biased.

C++, random number w/ range of 1-6


Android: layout with imageView re-sizing buttons wrongly

Question: I have a layout problem, I want an image to be in the middle of two buttons. So I created the two buttons and defined a weightSum of 1. I then set the weight of the two buttons to .40 and the image to .20 so that the image would be a small logo in the middle of the two buttons. The problem is the image is stretched out and the buttons are pushed aside.

<code><Button
    android:id="@+id/buttonClear"
    style="@style/ButtonText"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight=".40"
    android:background="@drawable/custombuttonred"
    android:text="@string/clear"
    android:textSize="50sp" />

<ImageView
    android:id="@+id/myimage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight=".20"
    android:src="@drawable/imageid" />

<Button
    android:id="@+id/buttonBackspace"
    style="@style/ButtonText"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight=".40"
    android:background="@drawable/custombuttonred"
    android:text="@string/backspace"
    android:textSize="20sp" />
</code>
Comment: is it in a linear layout? if yes, what is it's orientation? if vertical, you should not use fill_parent for layout_height
Comment: Can you list the enclosing View as well?
Answer: I had also faced the same issue. I used the button insted of ImageView and set background image to it.
Answer: This code: http://pastebin.com/3P9BWEcQ
Works well for me
Answer: I think you could use dp for resizing the image for both height & width.Say if you ar image is in original size of 400px width & 200 px height,just resize according to the screen size i.e if you are device in which you are testing currently could only hold half of the image size then android:layout_width="200dp" android:layout_height="100dp".If you follow resizing using dp image will get resized to both the smaller & larger device you are using.Make sure that when you have any larger devices screen than the one currently you are testing,just try to have the image as large as possible to get the best results.


What is a generally accepted definition of "curve" in mathematics?

Question: I am wondering if there is a generally accepted definition of the term curve in mathematics.  If one does exist, is there any requirement of continuity, beyond what is required by the piecewise differentiable property defined and applied to the definition of a curve in what follows?
Some authors call an entire hyperbola a curve, even though its two branches nowhere share a point. That is somewhat contrary to the naive concept of curve, but isn't too difficult to accept. On the other hand, the following definitions seem to leave a lot of room to produce things which satisfy the definition of curve, but we would never call curves in real life.
This is from Thomas's Calculus and Analytic Geometry, 2nd Edition, 1953.

The cardinal principle of analytic geometry is that an equation $F(x,y)=0$ describes a curve which is the locus of all and only those points $P(x,y)$ whose coordinates satisfy the given equation.

In that context, the meaning of the term curve is closer to what Gray, et al., are calling the trace of a curve in the following taken from Modern Differential Geometry of Curves and Surfaces with Mathematica,3rd Edition:

From Thomas's definition we could produce an equation that determines a set of points, none of which are connected.  I assume he was merely giving the historical definition, and not intending to be rigorous.
So, is the mathematical definition of curve really wide open, beyond piecewise differentiability?
Comment: I think "in mathematics" is too ambitious - different fields *definitely* disagree on what curve should be; asking a topologist will definitely get you a different answer than asking an algebraic geometer, and probably different still than asking someone who studies analysis or differential geometry.
Comment: Note that we can't even agree on whether zero is a [natural number](https://en.wikipedia.org/wiki/Natural_number). :)
Comment: @Blue It sucks using the naturals in any work because you have to annoyingly specify whether $0\in\mathbb N$ in your convention.
Comment: @Blue I'm not sure if you are familiar with the controversy I've caused in the past regarding the topic of natural numbers in this community.  But I am of the opinion that pointing at the first number in the most primstive set of numbers, and uttering the word "zero" is silly.  This is just some brainstorming scrawl for personal use : https://drive.google.com/file/d/15ctKgShNfJSCjoQhNnIVY-1n6cAsC_mT/view?usp=drivesdk
Comment: FYI: A site search for ["what is a curve?"](https://math.stackexchange.com/search?q=what+is+a+curve%3F) yields over 13000 results. Granted, almost-all of them are irrelevant to the question at hand, but it might be worth skimming part of the list.
Comment: There are different conventions, others call what the cited text names a "parametrized curve" a path and what the text calls "trace" is the curve, so that the curve is the geometric object, the set of points, and the path provides topological context. Then the curve is rectifiable, has a length etc. independent from any specific path used.
Answer: There is no unified definition. Curves in differential and algebraic geometry are defined very differently, via parametric and implicit equations, respectively. While the two representations can be related under some broad assumptions (via the implicit function theorem), both subjects push the envelope beyond such relatability. Mature fields are driven by technical reach, not intuition.
While connectedness and differentiability requirements are common in the differential context, they are not in the algebraic one. Studying connected components and algebraic singularities is a big part of the job. This is why hyperbola is one curve. Even within the classical differential geometry, different authors make different conventions about how differentiable a "curve" should be, from infinitely, to twice, to once continuously, each possibly piecewise (although continuity is usually assumed). There is also an intermediate area of analytic, holomorphic and pseudoholomorphic curves that combines methods from both approaches, and has definitional variations of its own.
Even just continuous curves, once deemed "pathological", like the Peano curve filling a square, or the nowhere differentiable Koch snowflake, now have a field of their own, a part of geometric measure theory. The study of such fractal curves has a very different flavor, employing distributions and measure theory, than the classical differential or algebraic geometry.
Comment: @StevenThomasHatton I'd say what drives this concept is not a common core but a common root. To "grasp" the intuitive "curve", first algebra and then calculus were used. When their respective representations were explored to the fullest, it turned out that the original loose concept naturally splits (at least) in two more precise ones. Later fractal curves were added to smooth and algebraic curves in a similar fashion. One can, perhaps, distill a common "essence" for each type, but I am not sure there is a useful umbrella definition  for all, just family resemblance from common ancestry.
Comment: It is unsurprising that different fields within mathematics would use different definitions.  Even within a specialty, there are often differing approaches.  Sometimes they turn out to be isomorphic.  And sometimes they use definitions that conflict with those by other competant researchers.  What now seems like a reasonable follow up is: what do the various definitions of "curve" have in common? I am familiar withe a generalized  Pythagorean theorem that works for for k-surfaces. Edwards Theorem V3.11.
Comment: Regarding the hyperbola example in your second paragraph, one should mention that in an algebraic geometry (using the *Zariski topology*), a hyperbols is not only a single curve, but it is *connected*. Sometimes though one still might want to treat two disjoint curves as one, e.g. when working with affine plane curves, so they are more uniformly defined as vanishing sets of one polynomial.
Answer: Yes. And actually, if we get to such things as "space-filling curves", differentiability need not be required at all. Hence, I'd think a good definition - covering both formalism and intuitive conceptalization - would be indeed just that open-ended. The trick is in how we imagine or picture it intuitively, versus how we might imagine a function in other contexts:

In formalism, a Euclidean curve $C$ is essentially nothing more than a drawing function: it is an arbitrary function $\gamma_C : [0, 1] \rightarrow \mathbb{R}^n$, taking a single continuous parameter into $n$-dimensional Euclidean space. The semantic intuition is that we can think of this function as describing how an infinitely fine pen, writing black ink, moves to draw the curve, with discontinuous jumps leaving no connecting traces. The path of the pen is obtained by varying the input, taken as a number ranging from $0$ to $1$ and which can and should be thought of as a sort of "percentage" (to make it an actual one, we could define instead the domain interval as $[0, 100]$ - but it doesn't matter) representing how much of the curve has been drawn so far (e.g. an input value of 0.50 means 50%, or half, of the drawing is done), and the value returned by the function - a set of coordinates - is the point to fill in next. During this process, the parameter is imagined to vary smoothly throughout the interval, such that a tiny point of ink is put down for every single real number progress point.

More generally, we can replace the codomain with a manifold $M$, in which case we can talk about curves in non-Euclidean spaces, such as curves drawn on the surface of a sphere like the Earth: for example, the path of an airplane, ship, or other vehicle travelling over that surface.
ADD: And even more generally - see the comment by @Don Thousand.
Comment: The codomain can just be a topological space.
Answer: This issue came up in a recent question. I will add some clarification in the context of Differential Geometry (and Differential Topology). Unsurprisingly, Wikipedia is also sloppy and inconsistent here.
There are several definitions of the word "curve" commonly used in Differential Geometry and Differential Topology. I will use the $C^\infty$-degree of smoothness for curves, since it is, again, most common.
Definition 1. A smooth curve in ${\mathbb R}^n$ is a smooth 1-dimensional submanifold $C$ of ${\mathbb R}^n$. In other words, $C$ is a subset of ${\mathbb R}^n$ such that for every $p\in C$ there exists a neighborhood $U$ of $p$ in ${\mathbb R}^n$ and a ($C^\infty$) diffeomorphism $f: U\to {\mathbb R}^n$ sending $U\cap C$ diffeomorphically to the 1st coordinate line $L$ in ${\mathbb R}^n$.
Here $L$ is given by:
$$
\{(x_1,0,...,0): x_1\in {\mathbb R}\}\subset {\mathbb R}^n.
$$
(Equivalently, one can require existence of a diffeomorphism $F: U\to V$, where $V$ is an open subset of ${\mathbb R}^n$, such that $F(U\cap C)=V\cap L$).
Definition 2. A smooth curve in ${\mathbb R}^n$ is a smooth 1-dimensional submanifold with boundary $C$ of ${\mathbb R}^n$. In other words, $C$ is a subset of ${\mathbb R}^n$ such that for every $p\in C$ there exists a neighborhood $U$ of $p$ in ${\mathbb R}^n$ and a diffeomorphism $F: U\to V$,  where $V$ is an open subset of ${\mathbb R}^n$, such that $F(U\cap C)=V\cap H$), where $H$ is the  closed positive half-line in a line $L$ as above:
$$
\{(x_1,0,...,0): x_1\in {\mathbb R}, x_1\ge 0\}\subset L\subset {\mathbb R}^n.
$$
If $F(p)=(0,...,0)$ then $p$ is called a boundary point of $C$.
Note that some authors require $C$ to be connected in both definitions.
One also frequently encounters the notion(s) of a parameterized curve. Again, there are competing definitions here as well:
Definition 3. A smooth parameterized curve in ${\mathbb R}^n$ is a smooth  map $c: I\to {\mathbb R}^n$, where $I$ is an interval in the real line. (Here an interval is allowed to be closed, open, half-open, infinite, etc).
Definition 4. A smooth regular parameterized curve in ${\mathbb R}^n$ is a smooth map $c: I\to {\mathbb R}^n$, where $I$ is an interval in the real line, such that $c'(t)\ne 0$ for all $t\in I$.
Here again an interval is allowed to be closed, open, half-open, infinite, etc and, depending on the context, the derivative is required (or not) to be nonvanishing at the end-points of $I$ (if it has any), where the derivative  is understood as a 1-sided derivative.
Remark. There are also several competing notions of smoothness map at an end-point of an interval. One definition (as above) works with 1-sided derivatives (as preferred by analysts), while another requires the existence of a smooth extension to a slightly larger open interval (as preferred by topologists). This discrepancy does not affect the definition.
Lastly, one may find a definition where a smooth curve is the image of a map $c$ as in Definitions 3 and 4.


PHP Amazon File upload Signature

Question: I tried a file upload to my amazon s3 refering this tutorial
http://www.anyexample.com/programming/php/uploading_files_to_amazon_s3_with_rest_api.xml
But I got the following error
HTTP/1.1 403 Forbidden
x-amz-request-id: 10F111F91A85CFC5
x-amz-id-2: 6pBJs+OKZOZdTF3zQw0MLM62zGAAsCFyeJsv/xzYB+wM7+7RnZU+k1rtcpTWC8VS
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Fri, 02 Dec 2011 09:35:21 GMT
Server: AmazonS3

2bf
<?xml version="1.0" encoding="UTF-8"?>
<Error>SignatureDoesNotMatch
<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
<StringToSignBytes>50 55 54 0a 0a 0a 46 72 69 2c 20 30 32 20 44 65 63 20 32 30 31 31 20 30 39 3a 33 37 3a 35 30 20 2b 30 30 30 30 0a 2f 74 61 6e 65 77</StringToSignBytes>
<RequestId>10F111F91A85CFC5</RequestId>
<HostId>6pBJs+OKZOZdTF3zQw0MLM62zGAAsCFyeJsv/xzYB+wM7+7RnZU+k1rtcpTWC8VS</HostId>
<SignatureProvided>6V2sLdHEJ9uWZO0G81q5QQzSa9Y=</SignatureProvided><StringToSign>PUT

Any Ideas
Thanks in advance
Comment: Is `The request signature we calculated does not match the signature you provided. Check your key and signing method.` not clear already?
Comment: do you have your own AWS Access Key ID and secret access key?
Comment: they following is the signing method... Can you please help ?

$dt = gmdate('r'); // GMT based timestamp

// preparing String to Sign    (see AWS S3 Developer Guide)
$string2sign = "PUT

{$dt}/{$aws_bucket}";

// preparing HTTP PUT query
$query = "PUT /{$aws_bucket} HTTP/1.1
Host: s3.amazonaws.com
Connection: keep-alive
Date: $dt
Authorization: AWS {$aws_key}:".amazon_hmac($string2sign)."\n\n";

$resp = sendREST($fp, $query);
if (strpos($resp, '') !== false) {

    die($resp);

}
Comment: yes I had my own Access Key ID and secret access key
Comment: @rajeesh I have no experience with this so I can't add anything useful, but maybe this helps:  https://forums.aws.amazon.com/thread.jspa?threadID=80386 if it doesn't, consider Googling for the error message first, it's more likely to yield a response
Answer: Without having your code to view it's hard to help but here is some example code that you might find helpful:
class myS3Helper{
public function getSignedImageLink($timeout = 1800, $my_aws_secretkey, $my_aws_key)
{

    $now = new Zend_Date(); //Gives us a time object that is set to NOW
    $now->setTimezone('UTC'); //Set to UTC a-la AWS requirements
    $now->addSecond($timeout); //set the time in the time object to a point in the future
    $expirationTime = $now->getTimestamp(); //returns unix timestamp representation of the time.

    $signature = urlencode(
            base64_encode(
                    hash_hmac(
                            'sha1', $this->_generateStringToSign($expirationTime),
                            $my_aws_secretkey,
                            true
                            )
                    )
            );

    //Yes - this is ugly but hopefully readable
    $url = 'https://';
    $url .= Zend_Service_Amazon_S3::S3_ENDPOINT; //e.g s3.amazonaws.com
    $url .= $this->_getImagePath(); //e.g /mybucket/myFirstCar.jpg
    $url .='?AWSAccessKeyId=' . $my_aws_key;
    $url .='&Signature=' . $signature; //signature as returned by below function
    $url .='&Expires=' . $expirationTime;

    return $url;

}

protected function _generateStringToSign($expires)
{

    $string = "GET\n"; //Methods
    $string .= "\n";
    $string .= "\n";
    $string .= "$expires\n"; //Expires
    $string .= $this->_getImagePath();

    return $string;
}

PHP Amazon File upload Signature


How to return all data from one column Android SQL

Question: I have an SQLite Database in my application. It has three columns. being _id, TEXT, and Location. If I want to return all the data from, say, the TEXT column should I use cursor.getColumnIndex(2)? I am obviously new to SQLite. And and all help is appreciated. Thanks everyone!
Comment: I would strongly suggest putting together some tutorials to familiarize yourself with sqlite such as this one, it really helped me awhile ago. http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Answer: Yes, friend, you are new.
First off, your database doesn't have three columns, but rather, your table does. Databases have tables, tables of columns (fields) and rows (records).
Secondly, TEXT is not a valid name for a column, as it's a datatype. Let's say you called the three columns id, theText, and location -- then if you selected all three columns to be returned, the second one would be accessible through:
cursor.getString(1); // that's the second column returned

or
cursor.getString(cursor.getColumnIndex( "theText" ) );

However, you can have sqlite do most of the work for you by selecting only the column you're interested in, so then you'd cursor.getString(0) as it's the only column returned.
For more pertinent explanations, please post your code in the question.
Answer: simply apply the query of getting all contacts and take an array of string type and then add the required record in that array as shown below
I hope this code help u

in DBHelper getting record of particular column :
public ArrayList<String> getAllCotactsEmail() {

    ArrayList<String> arrayList=new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    if (res != null)
    {
        while(res.isAfterLast() == false){
            arrayList.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
            Log.d("emailssinlisttt",arrayList.toString());

            res.moveToNext();
        }}
    return arrayList;

}

retrieve :
email=mydb.getAllCotactsEmail();

Log.d("emaillllll",email.toString());

Answer: You need to query your Database to get your data. This query will return a Cursor with the column you specified in the query.
To make query, you need to call query() method from ContentResolver. To get your ContentResolver, you can use getContentResolver() from a Context like Activity :
getContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
To understand all parameters, see : ContentResolver
In your case, you want only TEXT column so pass a String array with your TEXT column name for projection parameters.
You want all rows so your selection and selectionArgs parameters must be null.
If you don't care about order, pass null for sortOrder (rows will be sort by ID) :
Cursor c = getContentResolver.query(yourUri, new String[]{"TEXT"}, null, null, null)

This query will return a cursor, to extract your values from the cursor, make a loop like :
if(c.moveToFirst()) {
            do {
                final String text = c.getString(c.getColumnIndex("TEXT"));
            } while (c.moveToNext());
        }

Hope this will help you :)


How to implement spinner in angular2 and spinner hiding is possible in angular2?

Question: I have some delay on image loading time that time I want show a spinner and after image loading time that spinner should hide. What is the correct way to implement this in angular 2 platform.

This is the images loading,

Comment: There are several questions on SO discussing the use of spinners/loading indicators in Angular2 e.g. [here](http://stackoverflow.com/questions/38144655/angular-2-loader-on-each-http-request).  See if those can point you in the right direction
Answer: take a look at PrimeNG they have spinner and it's open source so you can just use it.
http://primefaces.org/primeng
https://github.com/primefaces/primeng
https://github.com/primefaces/primeng/tree/master/components/spinner
Comment: Did you try ngClass or ngStyle for this?
Comment: Can I implement any conditional usage for css class loading and hiding that loaded class


DocuSign Email Notifications - How to remove email address and name from the body of the email

Question: DocuSign notifications are being sent out with the DocuSign account owners name and email within the body of the email. Worked with DocuSign support and determined modification needs to be made to the email resource file (there is also a signing resource file) and this is not something DocuSign support can help with.
I am trying to remove/hide the Name and Email Address from the body of the email. I have attached a screenshot example.
Which line in the resource file (I can attach both email and signing resource files here if necessary) would need to be modified? Would it also be multiple lines that need to be modified?
Answer: We recommend that any changes done to the resource file should be performed by an HTML knowledgeable person, because this file contains settings for the entire account.
If you want to make the changes yourself you can look up the appropiate section by searching for the text "your documents have been completed".
We hope this helps
Adrian
DocuSign Support


Exchange 2013 Mailbox Step 10

Question: please i have this error message when installing exchange 2013 on windows server 2012 R2 on the step 10 of 14 Mailbox
the following error was generated when $error.clear()
start-Setupservice-ServiceName MSExchangeSubmission
"was run: "Service ' MSExchangeSubssimin ' failed to reach status Running on this server "
Comment: Can you give anymore information? A screenshot perhaps?
Answer: Which build of Exchange 2013 are you using?
The error means what it says - the service failed to start. There could be additional information in the Setup Logs.

Exchange 2013 Mailbox Step 10


Como transformar um "Projeto Unity" em um .EXE?

Question: Estou acompanhando os vídeos do Nils no YouTube.  Após a criação de um projeto no Unity, como faço um instalador/.EXE para ele? Para rodar em Android, Windows, e outros.
Comment: Oi @Nils. Você poderia editar a resposta de alguém, mas eu acho que faz mais sentido você dar uma resposta adicional própria. :)
Comment: Oi Pablo, editei sua pergunta pra ficar mais no formato do site ok? Aqui a gente não pergunta direto pra outro usuário, qualquer um pode responder. E, com a tag certa ([tag:unity-3d]), é bem provável que o Nils veja e responda. Agora é só esperar uma resposta, boa sorte!
Comment: Quanto mais respostas, melhor. Desde que uma não seja cópia da outra em todos seus detalhes, como às vezes acontece :) Mas se tem algo a mais para dizer, merece um resposta nem que seja só para complementar. Quem sabe ela fica tão boa que ela é que acabe sendo aceita como a melhor.
Comment: No caso `.exe` (ou `.msi`) seria no Windows para Desktop, Android seria o `.apk`. Eu nunca trabalhei com unity-3d, mas acredito que precise do `Android Studio`, iOS vai necessitar do `XCode` (somente Macs) e Windows do `Visual Studio`.
Comment: Eu consigo complementar a resposta de alguém?
O Guilherme Nascimento e o DolbyCpp já responderam uma parte. Mas seria bom mostrar como faz.
Primeiro tem que ir em File>>>BuildSettings (ctrl+shift+b - trocar o ctrl pelo command no mac).
Vai aparecer isso aqui http://i.imgur.com/JFrTKTD.png
Escolher a plataforma que deseja construir o jogo, no caso do android e ios é conforme Guilherme falou, no caso de exe não tem problema se estiver desenvolvendo direto em windows. Para mais detalhes consultar a informação no link que o DolbyCpp postou. (e mandar traduzir a página se o idioma for um problema).
Comment: Agora entendi bem. Obrigado pelo ***LINK*** @DolbyCpp ira ajudar bastante, Obrigado a todos por terem ajudado a tirar minha duvida! :)
Comment: Minha pergunta ja foi respondida mas eu estava dando uma estudada, e me veio uma duvida, não vi a opção de "Exportar" para (Java).jar, provavelmente porque o programa não tem essa função, mas caso eu queira "exportar" para .jar oque eu devo fazer ?!
Answer: Exportar teu projeto do Unity para as plataformas disponíveis
Conteúdo

Premissas
Configurar o Player
Para Exportar
Standalone - Windows, Mac & Linux
Android.
iOS.

Atualizado para Unity 5.0.0.

Premissas
Para exportar o teu programa/jogo feito em Unity você precisa primeiro definir a plataforma alvo, pois dependendo da plataforma vai precisar de uns arquivos adicionas, ou contas de desenvolvedor para poder rodar ele.
Além disso você precisará configurar o "Player" - que na verdade é um menu com as configurações do teu jogo.
TL;DR(vídeo no youtube) - http://youtu.be/gK93-LGPp-c

Configurar o Player
Vá em Edit > Project Sttings > Player , conforme a seguinte figura.

No Inspector aparecerá alguns detalhes para você configurar, o importante é definir o que é padrão para todos.

Configurações padrões:

Default Company - Nome da tua empresa [importante]
Product Name    - Nome do teu jogo    [importante]
Default Icon    - Ícone do jogo       [importante]
Default Cursor  - Como vai ficar o mouse no jogo
Cursor Hotspot  - Parte do cursor que "funciona" - ex: você pode fazer uma mão e escolher que só o dedinho funcione.

As outras vão depender para onde você quer exportar.

Para exportar
Vá em File > Buid Settings ou Ctrl+Shift+B (cmd+shif+b no mac)

Certifique-se que todas as cenas do teu jogo estão em Scenes in Build
Windows, Mac & Linux - StandAlone
O Unity exporta por padrão para estes formatos, sem precisar de nada adicional.
Você só precisa escolher:

**Target Plataform **  - Qual o sistema operacional alvo, Windows, Linux ou Mac
Architecture       - Arquitetura do processador
O resto é opcional e depende do que você quer fazer.

Mais detalhes http://docs.unity3d.com/Manual/class-PlayerSettingsStandalone.html

Android
Primeiro você precisa ter o Android SDK instalado no teu computador. Se você não sabe o que é isso, está no lugar errado e não deveria estar fazendo jogos para ele(ha-ha). Brincadeiras a parte, acesse o site oficial de desenvolvedor do android: http://developer.android.com/sdk/
Procure pela opção outros downloads ("Other Download Options" da ultima vez que acessei).
E baixe a versão para teu sistema operacional que corresponde a SDK Tools Only
Após instalado, abra o Unity. Clique em Edit > Preferences.... Escolha External Tools, e em Android SDK Location escolha onde você instalou ele.

Agora vá no Build Settings e escolha o Android como opção de plataforma.

Obs: Quando você mandar compilar e não aparecer a barra de progresso é sinal que alguma coisa aconteceu de forma errada.

Mais detalhes http://docs.unity3d.com/Manual/android-GettingStarted.html

iOS
Um do mais chatos de exportar.
Você precisará ter uma conta de desenvolvedor Apple, cumprir os requerimentos para instalar o iOS SDK (geralmente instalar o iTunes e atualizar o sistema). Não use versão beta, sempre vá na recente mais estável.
Siga o passo a passo do portal de desenvolvimento da apple para configurar tudo que ele te pedir - adicionar pessoas, dispositivos, certificados, instalar outras coisas... até a resposta para esse modo é tão chata de escrever.
Dependendo do que for fazer vai dar muito mais ou só muito trabalho, como adicionar compras no aplicativo, chamadas de bibliotecas, e por ai vai.
Lembrando que os projetos são gerados em xcode, e depois você precisa tunar algumas configurações como as travas de fps dos dispositivos com iOS.

Mais informações http://docs.unity3d.com/Manual/iphone-GettingStarted.html
Video para testar o teu jogo (funciona para android também) https://youtu.be/BXHd-67Q98w

BlackBerry
Windows Phone 8.1
Web Player
WebGL (Preview)
Consoles
TODO : Preciso juntar os links e materiais para cada caso pois vai levar um tempinho, mas o que tem até agora já responde a dúvida inicial.
Comment: Uoo! Mas que ótima a explicação, a principio só vai ira "servir" quando eu conseguir finalizar minha ideia/projeto. mas de qualquer forma já irei finalizar entendendo esta parte ...
Estudar muito (...) :]. Gracias! @Nils
Answer: A extensão .exe é reconhecida apenas pelas versões do Windows. Outros sistemas operacionais trabalham com outras extensões(Android com .apk, e assim por diante).
Você precisa compilar seu projeto para cada plataforma onde deseja roda-lo.
A própria documentação da Unity fala a respeito disto: Platform Specific(Vá expandindo os menus).
Boa sorte.
Comment: Grato irmão, valeu pela Força!
Comment: @Nils - Minha pergunta ja foi respondida mas eu estava dando uma estudada, e me veio uma duvida, não vi a opção de "Exportar" para (Java).jar, provavelmente porque o programa não tem essa função, mas caso eu queira "exportar" para .jar oque eu devo fazer ?!


Multiclass classification with Random Forest in Apache Spark

Question: The Apache Spark's documentation (1.4.0) promises that Random Forest (the same promise is for decision trees) can be extended to multiclass classification setting. However, I can't find any way to reach this using RandomForestModel API:
randomForestModel.predict

Could you please provide a right way how to do that, if it's really possible in 1.4.0 version?
Answer: All right, I've found it in an experimental package (ml): org.apache.spark.ml.classification.RandomForestClassificationModel
and transform should be used instead of predict:
RandomForestClassificationModel.transform


Solve a system of quadratic and trigonometrc equations

Question: I have a condition
$$3R^2-d^2+2dR\cos\alpha = 0$$
along with the following equations
$$d = \sqrt{(X_1-X_2)^2+(Y_1-Y_2)^2}$$
$$\alpha = \arccos{\frac {Y_2-Y_1}{d}}+\psi$$
$$Y_2=Y_1-(X_1 - X_2)\tan\psi $$
The values $ X_1, Y_1, \psi, R$ are known.
The resolution of the first condition should lead to a second order equation for $X_2$. The solution obtained for $X_2$ is of interest.
Tried solving it with little success, someone help me out.
Comment: This is the Output by Mathematica, i hope this will help you: $$\left(\left(0=d-\sqrt{d^2}\land \psi =\alpha -\frac{\pi }{2}\land \text{X2}=\frac{-\sqrt{d^2
   \left(\cot ^2(\alpha )+1\right)}+\text{X1} \cot ^2(\alpha )+\text{X1}}{\cot ^2(\alpha
   )+1}\right)\lor \left(0=d-\sqrt{d^2}\land \psi =\alpha -\frac{\pi }{2}\land
   \text{X2}=\frac{\sqrt{d^2 \left(\cot ^2(\alpha )+1\right)}+\text{X1} \cot ^2(\alpha
   )+\text{X1}}{\cot ^2(\alpha )+1}\right)\right)\land \text{Y1}=\text{X1} \tan (\psi
   )-\text{X2} \tan (\psi )+\text{Y2}$$
Comment: You want to solve this System of equations for $X_2,Y_2,d$?
Comment: Yes, since $Y_2, d$ can be expressed in terms of $X_2$, obtaining the solution for $X_2$ is the goal.
Comment: @Dr.SonnhardGraubner I did not really understand the solution, also there were a few mistakes in the question posted, I have done the corrections now, Can you please check again? I have posted the question again with more details [link](https://math.stackexchange.com/questions/3412382/solution-for-a-system-of-quadratic-and-trigonometric-equations)
Answer: Let $x=X_2-X_1$ and $y=Y_2-Y_1$. From the givens,
$$ y = x \tan\psi, \>\>\>\>\> d= x\frac{\tan \psi}{\cos(\alpha-\psi)}$$
Plug above into $d = \sqrt{x^2+y^2}$  to get
$$\cos(\alpha-\psi)=\sin\psi$$
which has the solution $\alpha=\frac \pi2$, or $\alpha = 2\psi -\frac\pi2$. In turn, $\cos\alpha=0$, or $\cos\alpha=\sin2\psi$.
For $\cos\alpha=\sin2\psi$, we have
$$3R^2-d^2+2dR\sin2\psi = 0$$
which leads to
$$d= R\left(\sin2\psi+\sqrt{\sin^22\psi+3}\right)$$
As a result,
$$x = d \frac{\cos(\alpha-\psi)}{\tan\psi}= d \cos\psi= R\cos\psi\left(\sin2\psi+\sqrt{\sin^22\psi+3}\right)$$
The other solution, corresponding to $\cos\alpha=0$,  is $d = \sqrt3 R$, which yields
$$x= \sqrt3 R\cos\psi$$
Comment: I have posted the question again with more details, can you please check. There were mistakes in the question i posted here. [Link for the new question](https://math.stackexchange.com/questions/3412382/solution-for-a-system-of-quadratic-and-trigonometric-equations)


HTML - Navigation menu over header

Question: I am building currently my web-page on Github (Githug Page), and I am having some troubles with the top-nav menu. As you can see, when you scroll down, the menu disappears, and when you scroll up, it appears again. Nevertheless, I would like to make the behaviour much more simpler, and that is, to make it fixed with respect the header. In other words, I just want the menu to appear on top of the page, like another element more. I do not want the menu to follow the scrolling. Looks simple but I do not end up getting the result.
This is my current main.js.

(function($) {

 var $window = $(window),
  $body = $('body');

 // Breakpoints.
  breakpoints({
   xlarge:   [ '1141px',  '1680px' ],
   large:    [ '981px',   '1140px' ],
   medium:   [ '737px',   '980px'  ],
   small:    [ '481px',   '736px'  ],
   xsmall:   [ '321px',   '480px'  ],
   xxsmall:  [ null,      '320px'  ]
  });

 // Play initial animations on page load.
  $window.on('load', function() {
   window.setTimeout(function() {
    $body.removeClass('is-preload');
   }, 100);
  });

 // Scrolly.
  $('.scrolly').scrolly();

})(jQuery);

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("header_nav").style.top = "0";
  } else {
    document.getElementById("header_nav").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

The index.html file, where you can see, the important sections are header and header_nav.

<!DOCTYPE HTML>

  <title>Eduardo Alvarado</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
  <link rel="stylesheet" href="assets/css/main.css" />
  <link rel="stylesheet" href="assets/css/noscript.css" />

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Home

Research

Game-dev

Photography

Hi, I'm Eduardo Alvarado.

A passionate software engineer who develops intelligent

     cars during the day and loves to design

     game-focus art and applications in his spare-time.

Want to contact me? Send me a message at firstname.lastname@example.com.

Discover

Background

I am a first year PhD Researcher at Daimler AG in Stuttgart, Germany. My research is centered on robust perception for human activity recognition. Prior joininig Daimler, I graduated with a master's degree in Embedded Systems Engineering, with a major in Artificial Intelligence and Autonomous Intelligent Systems from Albert-Ludwigs-Universität Freiburg, and with a bachelor's degree in Electronics and Automation Engineering from Universidad Carlos III in Madrid.

I have dedicated my academic career to the field of robotics, with special interest in AI-based Perception and Behavior Planning applied to intelligent-mobility. I wrote my master's thesis at Robert Bosch GmbH on DL sensor-fusion architectures for Object Detection and Tracking, under the supervision from Prof. Dr. Joschka Boedecker and Prof. Dr. Abnihav Valada. I also worked as development-intern at ZF Friedrichshafen on the design of ROS SW-tools for self-driving vehicles. Additionally, I have been working as research assistant for Autonomous Intelligent Systems at the university, on the development of SLAM algorithms and Autonomous Driving simulations.

I dedicate my day to day to my other great passion too, game-related development and 2D/3D design. Since I was a child, I have always loved bringing to reality dream worlds, characters and landscapes only possible in one's imagination. Little by little, I try to learn more about design, gameplay and visual programming.

My work

Research and Academic Service

Publications, preprints, SW/HW proyects and news.

More

Game Development

Game applications, 2D/3D design and visual programming.

More

Photography

A small portfolio of my favorite trips and places.

More

CV

Email

GitHub

Google Scholar

© Untitled

Design: HTML5 UP

And finally, the respective part of the css.

/* Header */

 #header {
  padding: 9em 0 9em 0 ;
  background-color: #4686a0;
  color: rgba(255, 255, 255, 0.75);
  background-attachment: fixed,       fixed,       fixed;
  background-image: url("images/overlay2.png"), url("images/overlay3.svg"), linear-gradient(45deg, #9dc66b 5%, #4fa49a 30%, #4361c2);
  background-position: top left,      center center,     center center;
  background-size: auto,       cover,       cover;
  overflow: hidden;
  position: relative;
  text-align: center;
 }

  #header a {
   border-bottom-color: rgba(255, 255, 255, 0.5);
  }

   #header a:hover {
    color: #ffffff;
   }

  #header h1, #header h2, #header h3, #header h4, #header h5, #header h6, #header strong, #header b {
   color: #ffffff;
  }

  #header header p {
   color: #ffffff;
  }

  #header header.major:after {
   background: #ffffff;
  }

  #header input[type="submit"],
  #header input[type="reset"],
  #header input[type="button"],
  #header button,
  #header .button {
   box-shadow: inset 0 0 0 1px #ffffff;
   color: #ffffff !important;
  }

   #header input[type="submit"]:hover,
   #header input[type="reset"]:hover,
   #header input[type="button"]:hover,
   #header button:hover,
   #header .button:hover {
    background-color: rgba(255, 255, 255, 0.125);
   }

   #header input[type="submit"]:active,
   #header input[type="reset"]:active,
   #header input[type="button"]:active,
   #header button:active,
   #header .button:active {
    background-color: rgba(255, 255, 255, 0.25);
   }

   #header input[type="submit"].primary,
   #header input[type="reset"].primary,
   #header input[type="button"].primary,
   #header button.primary,
   #header .button.primary {
    background-color: #ffffff;
    box-shadow: inset 0 0 0 1px #ffffff !important;
    color: #4686a0 !important;
   }

    #header input[type="submit"].primary:hover,
    #header input[type="reset"].primary:hover,
    #header input[type="button"].primary:hover,
    #header button.primary:hover,
    #header .button.primary:hover {
     background-color: rgba(255, 255, 255, 0.125) !important;
     color: #ffffff !important;
    }

    #header input[type="submit"].primary:active,
    #header input[type="reset"].primary:active,
    #header input[type="button"].primary:active,
    #header button.primary:active,
    #header .button.primary:active {
     background-color: rgba(255, 255, 255, 0.25) !important;
    }

  #header ul.major-icons li .icon {
   border-color: #ffffff;
  }

  #header .icon.major {
   color: #ffffff;
  }

  #header h1 {
   margin: 0;
  }

  #header p {
   margin: 1em 0 0 0;
  }

  #header .actions {
   -moz-justify-content: center;
   -webkit-justify-content: center;
   -ms-justify-content: center;
   justify-content: center;
   margin-top: 2.5em;
   margin-left: 0;
   position: relative;
  }

   #header .actions li:first-child {
    padding-left: 0;
   }

   #header .actions:after {
    background: #ffffff;
    content: '';
    height: 100vh;
    left: 50%;
    position: absolute;
    top: 100%;
    width: 1px;
   }

  #header .inner {
   -moz-transition: -moz-transform 1.5s ease, opacity 2s ease;
   -webkit-transition: -webkit-transform 1.5s ease, opacity 2s ease;
   -ms-transition: -ms-transform 1.5s ease, opacity 2s ease;
   transition: transform 1.5s ease, opacity 2s ease;
   -moz-transition-delay: 0.25s;
   -webkit-transition-delay: 0.25s;
   -ms-transition-delay: 0.25s;
   transition-delay: 0.25s;
   -moz-transform: scale(1);
   -webkit-transform: scale(1);
   -ms-transform: scale(1);
   transform: scale(1);
   opacity: 1;
   position: relative;
   z-index: 1;
  }

   #header .inner .actions {
    -moz-transition: -moz-transform 1.25s ease;
    -webkit-transition: -webkit-transform 1.25s ease;
    -ms-transition: -ms-transform 1.25s ease;
    transition: transform 1.25s ease;
    -moz-transition-delay: 1s;
    -webkit-transition-delay: 1s;
    -ms-transition-delay: 1s;
    transition-delay: 1s;
    -moz-transform: translateY(0);
    -webkit-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0);
    opacity: 1;
   }

  #header:after {
   -moz-transition: opacity 1s ease;
   -webkit-transition: opacity 1s ease;
   -ms-transition: opacity 1s ease;
   transition: opacity 1s ease;
   background-image: linear-gradient(45deg, #4fa49a, #4361c2);
   content: '';
   height: 100%;
   left: 0;
   opacity: 0;
   position: absolute;
   top: 0;
   width: 100%;
  }

 body.is-preload #header .inner {
  -moz-transform: scale(1.05);
  -webkit-transform: scale(1.05);
  -ms-transform: scale(1.05);
  transform: scale(1.05);
  opacity: 0;
 }

  body.is-preload #header .inner .actions {
   -moz-transform: translateY(30em);
   -webkit-transform: translateY(30em);
   -ms-transform: translateY(30em);
   transform: translateY(30em);
   opacity: 0;
  }

 body.is-preload #header:after {
  opacity: 1;
 }

/* Header_nav */

 #page-wrapper {
  padding-top: 3.5em;
 }

 #header_nav {
  background: rgba(0, 0, 0, 0);
  box-shadow: 0 0 0.25em 0 rgba(0, 0, 0, 0);
  cursor: default;
  height: 3.5em;
  left: 0;
  line-height: 3.5em;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 100;
 }

  #header_nav h1 {
   height: inherit;
   left: 1.25em;
   line-height: inherit;
   margin: 0;
   position: absolute;
   top: 0;
  }

  #header_nav nav {
   position: absolute;
   right: 1em;
   top: 0;
  }

   #header_nav nav ul {
    margin: 0;
   }

    #header_nav nav ul li {
     display: inline-block;
     margin-left: 1em;
    }

     #header_nav nav ul li a, #header_nav nav ul li span {
      border: 0;
      color: inherit;
      display: inline-block;
      height: inherit;
      line-height: inherit;
      outline: 0;
     }

      #header_nav nav ul li a.button, #header_nav nav ul li span.button {
       height: 2em;
       line-height: 2em;
       padding: 0 1.25em;
      }

      #header_nav nav ul li a:not(.button):before, #header_nav nav ul li span:not(.button):before {
       margin-right: 0.5em;
      }

     #header_nav nav ul li.active > a, #header_nav nav ul li.active > span {
      color: #e44c65;
     }

     #header_nav nav ul li > ul {
      display: none;
     }

 body.landing #page-wrapper {
  padding-top: 0;
 }

 body.landing #header_nav {
  background: transparent;
  box-shadow: none;
  position: absolute;
 }

To summarize, I would like the menu to be only on the top of the page, over the header, nothing more. I would really appreciate your help. I have tried several things but I still not very experimented in web-design, I am sorry.
Thank you very much in advance.
Answer: In the styling for #header_nav, set position to absolute instead of fixed. Then remove the following from main.js:
/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("header_nav").style.top = "0";
  } else {
    document.getElementById("header_nav").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

This way, the menu will render over the header but not stay at the top of the page when the user scrolls down.
Edit: If you want the menu to render above the header, not on top of it, remove the position line completely.

HTML - Navigation menu over header


Structure of groups of order $pq$, where $p,q$ are distinct primes.

Question: I don't know about the Sylow Theorems.
But I have been wondering about a proof of the fact that a group or order $pq$ where $p$ and $q$ are distinct primes must be cyclic. I can't quite work out the details, but here is the general idea. I would like help with filling in details. I assume that it is already known that $G$ has subgroup(s) of order $p$ and subgroup(s) of order $q$.
If $G$ is a group of order $pq$ ($p\neq q$), then I know that $G$ has a subgroup $H$ of order $p$ and a subgroup $K$ of order $q$. Then $H\simeq \mathbb{Z}_p$ and $K\simeq \mathbb{Z}_q$.
But then $H\oplus K \simeq \mathbb{Z}_{pq}$, so I would think that $H\oplus K \simeq G$. I guess one could do an internal direct product instead of an external direct product, but I don't know that $H$ and $K$ are normal subgroups.
I am asking for help completing this argument.
Edit: I see from the comments below that I might need to assume that the smaller prime does not divide the larger prime minus $1$. Or maybe it is enough to assume that the primes are greater than or equal to $3$ (Still distinct).
Comment: $S_3$ has order $6=2^*3$ (in general you need to add the condition that the smaller prime does not divide one less than the larger).
Comment: @JohnDoe: Generally, a group $G$ of order $pq$ (not necessarily distinct) is either abelian or $Z(G)=1$. In our case you have to believe (Sylow Theorems) that $H$ and $K$ are normal in $G$. (I'm sorry for not mentioning it in my previous comment.) Now, notice that $aba^{-1}b^{-1}=(aba^{-1})b^{-1} \in K$, cause $K \trianglelefteq G$ and $aba^{-1}b^{-1}=a(ba^{-1}b^{-1}) \in H$, cause $H \trianglelefteq G$. So $aba^{-1}b^{-1} \in H\cap K=1$, which means that $ab=ba$ and you are done.
Comment: (Assuming $p$ does not divide $q-1$) Let $H=$ and $K=$. Then show that $G=HK$ and that G is abelian. Then take the map $H \times K \rightarrow G$ with $(a^{m},b^{n}) \mapsto a^{m}b^{n}$ and show that it is an isomorphism. Then conclude $G \cong H \times K \cong Z_{p} \times Z_{q} \cong Z_{pq}$.
Comment: Yep, I was going to bring up the dihedral groups.
Comment: @lulu : I think $q < p$ should indeed be distinct primes with $q$ not dividing $p-1$.
Comment: @JoelCohen That won't do it...you need that $p$ doesn't divide $q-1$ (assuming $p<q$):  http://math.stackexchange.com/questions/63219/nonabelian-semidirect-products-of-order-pq
Comment: @lulu : Yep, edited my comment to reflect it :)
Comment: What goes wrong when $p$ divides $q-1$ (with $p<q$) is that $H$ need not be normal, so $G$ need not be a direct product of $H$ and $K$. I know you said you don't know the Sylow theorems, but this is the most direct way to see the problem, so that gives you some motivation to learn them :-) If $N_p$ denotes the number of subgroups of order $p$, then $N_p$ must divide $q$ and must be congruent to $1$ mod $p$. If $p$ divides $q-1$ then $np = q-1$ for some $n$, hence $np+1 = q$, so we can't rule out $N_p = q$. But $H$ is not normal unless $N_p = 1$.
Comment: @BillMoustakas: Ok, that makes sense. I see why $G = HK$, but I don't see why $G$ is Abelian. Can you help me with that?
Answer: For a general group of order $p$ and $q$, there are very few possibilities (though you need Sylow theorems to know this). The fact is, for $p>q$ and $G$ a group of order $pq$, we must have
$$G\cong C_p\rtimes C_q$$
where the semi-direct product is defined in terms of some homomorphism $$\Phi:C_q\to\mathrm{Aut}(C_p)\cong C_{p-1}.$$
If $q$ does not divide $p-1$, this homomorphism must be trivial and you get $G\cong C_p\times C_q\cong C_{pq}$.
When $\Phi$ is nontrivial, we can write $\Phi(c_q^k)=\phi_k$. Then, the product structure on $C_p\rtimes C_q$ is given by
$$(c_p^a,c_q^b)(c_p^r,c_q^s)=(c_p^a\phi_b(c_p)^r,c_q^{b+s}).$$
It is a nice exercise to check that this is a group structure, and $C_p$ is normal. It is also useful to describe the isomorphism $S_3\to C_3\rtimes C_2$ explicitly.
EDIT: As you are requesting more detail, here you go:
Let $G$ be a group of order $pq$ with $p>q$ primes. Using Cauchy's theorem there are (cyclic) subgroups $P=\langle x\mid x^p=1\rangle$ and $Q=\langle y\mid y^q=1\rangle$ of orders $p$ and $q$, respectively. It follows from the Sylow theorems that $P\lhd G$ is normal (Since all Sylow $p$-subgroups are conjugate in $G$ and the number $n_p$ of Sylow $p$ subgroups must divide $q$ and satisfies $n_p\equiv 1$ (mod $p$)).
With this taken as given, it is straightforward to prove that $G\cong P\rtimes Q$, where the semidirect product is defined in terms of a homomorphism $\phi:Q\to\mathrm{Aut}(P)$.

We first note that since $|P\cap Q|$ divides both $p$ and $q$ we must have $|P\cap Q|=1$. It follows that $$|PQ|=\frac{|P||Q|}{|P\cap Q|}=pq=|G|$$
Hence, $PQ=G$.

Now, since $Q=\langle y\rangle$ normalizes $P=\langle x\rangle$, the map $\phi_k:P\to P$ given by $\phi_k(x)=y^kxy^{-k}$ is well defined. Moreover, it is clearly an automorphism with inverse $\phi_{-k}$. Finally, since $\phi_{k}\phi_j=\phi_{k+j}$, the map $y^k\mapsto\phi_k$ defines a homomorphism
$$\phi:Q\to \mathrm{Aut}(P).$$

As above, we define $P\rtimes Q$ to be $P\times Q$ as a set, with multiplication
$$(x^i,y^j)(x^k,y^l)=(x^i\phi_j(x^k),y^{j+k}).$$
Of course, one needs to verify that this is indeed a group. The identity is $(1,1)$, $(x^k,y^l)^{-1}=(\phi_{-l}(x^{-k}),y^{-l})$. Associativity is tedious but true.

Define a map $\psi: P\rtimes Q\to G$ by $\psi(x^i,y^j)=x^iy^j$. The map $\psi$ is surjective since $PQ=G$, and it is injective because $|P\rtimes Q|=pq=|G|$. To see that it is a homomorphism we compute
\begin{align*}
\psi((x^i,y^j)(x^k,y^l))&=\psi(x^i\phi_j(x^k),y^{j+l})\\
&=x^i\phi_j(x^k)y^{j+l}\\
&=x^i(y^jx^ky^{-j})y^{j+l}\\
&=x^iy^jx^ky^l=\psi(x^i,y^j)\psi(x^k,y^l).
\end{align*}
Hence, $\psi$ is an isomorphism as promised.

Now, either the homomorphism $\phi:Q\to\mathrm{Aut}(P)$ is trivial or it is not. If it is trivial, then $$G\cong P\rtimes Q=P\times Q\cong C_p\times C_q\cong C_{pq}.$$
If the homomorphism is nontrivial, then $G$ has the following presentation:
$$G = \langle x,y\mid x^p=1=y^q, yx=x^ny\rangle$$
where $n\in\mathbb{Z}$ satisfies $n\not\equiv1 \bmod p$), but $n^q\equiv 1 \bmod p$). (To see this note that $yxy^{-1}=x^n$ for some $n\not\equiv_p 1$, but $x=y^qxy^{-q}=x^{n^q}$.)

This works for any pair of primes with $q|(p-1)$, not just $p=3$. An example: $p=11$, $q=5$. Take $n=3$ so we have
$$G=\langle x,y\mid x^{11}=1,y^5=1,yx=x^3y\rangle.$$
This group has order $55$ and you can compute
\begin{align*}
yxy^{-1}&=x^3\\
yx^3y^{-1}&=(yxy^{-1})^3=x^9\\
yx^{9}y^{-1}&=x^{27}=x^5\\
yx^5y^{-1}&=x^{15}=x^4\\
yx^4y^{-1}&=x^{12}=x
\end{align*}
Comment: This answer seems like it would be perfect material for a second course in Abstract Algebra.
Comment: At which point can we conclude that $G$ is a semidirect product of $P$ and $Q$? After step 1, we already have that $P \cap Q = \{e\}$ and $G=PQ$, then along with the observation that $P$ is normal in $G$, is this enough to conclude $G$ is a semidirect product of $P$ and $Q$? Also, the subsequent steps explicitly show how to multiply elements of $P \rtimes Q$, is this also **all** possible ways to multiply them? Thank you!
Comment: @eatfood the isomorphism $G\cong P\rtimes Q$ is established in step 4 using steps 1, 2, and 3. The multiplication in $G$ is given (and since $G$ is an arbitrary of order $pq$ this includes all possible multiplications) and induces a homomorphism $P\to \mathrm{Aut}(Q)$. **All** such homomorphisms are described in step 5.
Answer: Let $\lvert G \rvert = pq$ for primes $p, q$ such that $q < p$ and $q \not \mid p-1$.
Let $n_p$ and $n_q$ be the number of Sylow $p$-subgroups and Sylow $q$-subgroups, respectively.
By the Third Sylow Theorem, $n_p \mid q$ and $n_p \equiv 1 \pmod p$ which implies $n_p = 1$ since $q < p$.
Similarly, $n_q \mid p$ and $n_q \equiv 1 \pmod q$ implies $n_q = 1$ since $p \not\equiv 1 \pmod q$.
Let $P$ be the unique Sylow $p$-subgroup and $Q$ be the unique Sylow $q$-subgroup.
Since $p$ and $q$ are prime, $P$ and $Q$ are cyclic: $P \cong \mathbb Z / p \mathbb Z$ and $Q \cong \mathbb Z / q \mathbb Z$.
Restatement of 1. from David Hill's answer: $P \cap Q \le P, Q$ so by Lagrange's theorem we have  $|P\cap Q|$ divides both $p$ and $q$, and we must have $|P\cap Q|=1$. It follows that $$|PQ|=\frac{|P||Q|}{|P\cap Q|}=pq=|G|$$
Hence, $PQ=G$. Since $P$ and $Q$ are unique, by consequence of the Third Sylow Theorem, $P,Q \lhd G$. Then the internal and external direct product are isomorphic, so $G \cong P \times Q$.
An analogue to the Chinese Remainder Theorem for groups shows that if $\operatorname{gcd}(m,n)=1$ then  $\mathbb Z / m \mathbb Z \times \mathbb Z / n \mathbb Z \cong \mathbb Z / mn \mathbb Z$. (prove with First Isomorphism Theorem and the standard Chinese Remainder Theorem) So by this theorem, $G \cong P \times Q \cong \mathbb Z / pq \mathbb Z$ and hence cyclic.
Answer: Consider $S_3$, the group of symmetries of the triangle. It's not cyclic and has order $6=2\cdot 3$.
Comment: Such a group can be non-cyclic only if $p=2$


Disable mouse right click event for GridView on WinRT C# app

Question: i have a GridView in my WinRT app, the problem is that one of the standard functionality of the gridViwes is when you click the right button (MOUSE), the item clicked is selected,
this will focus on this item , and loos focus from the previous one,
i wont this to happen, and i need to disable the right click mouse
- i think that this is the solution ,,,
- but if you think that desabling Right mouse click event, is a wrong avtion ,,
please give me other suggestions !
Answer: I think this is not the best solution for this, and I really don't know WinRT's GridView but I'm a Silverlight developer so I think you can subscribe to MouseRightButtunUp/Down events of the cells and handle them with e.Handled = true; in the code-behind.
For WinRT(Edit):
    private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
     if (ptr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
     {
        Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(Target);
        if (ptrPt.Properties.IsLeftButtonPressed)
        {
        e.Handled = true;
        }
     }
    }

Hope this one helps!
Comment: the MouseRightButtonUP/DOWN does not exist in WINRT :/
Comment: Yes you are right. Because it made for tablets too! It has a pointerpressed event instead. I'm editing my post according to this.


How to create array name from function parameter

Question: I want to create an array from a function. How would I go about doing this so that the array name is passed within the parameter.
function arrayCreate(name){
     name = [];
    }

So if I used arrayCreate("Hello") I would have Hello = [] as an array. The obvious problem is I'm passing a string so how would I overcome this.
To explain a bit more about my problem I have a function which updates a chart as seen below:
      self.updateChart = function(name){

        if (typeof chartData == 'undefined') {
          chartData = [];
        }
        chartData.push({
          date: game.tickCount,
          visits: self.price,
        });
        priceLabour.validateData();
        return chartData;
        }

Now the "chartData = []" and "priceLabour" I would like for it to be dynamic and change based on the "name" parameter.
Comment: even if you get it, what do you do with the named array?
Comment: I want to display different charts which require different named arrays
Comment: and how do you hand over the data?
Comment: I have an Object called Market.list which to create a graph I use Market.list[4].updateChart();. Obviously it's fine for one market but I want to re-use the code
Comment: It doesn't look like it should matter what the array is named since it's only being referenced inside this function. Why do you need to specify a name?
Comment: Because for amChart it takes in a dataProvider called chartData. I want to use the same chart but I can't use chartData array again
Comment: Can you provide a code example of where else you need to use the chartData array? I'm still not seeing why you need to pass in a name.
Comment: I'm using this library https://www.amcharts.com/demos/line-chart-with-scroll-and-zoom/ if you click on the source code you can see "chartData"
Comment: where do you call `arrayCreate`?
Answer: You can't just create variables by a string. You can create, assign, and read properties on objects using a string:
var obj = {};
obj[name] = [];
obj[name].push(...);

Comment: So there's no way I can change the edited code I just added?
Comment: @epayne not that i can tell. seems to be a leaky global however.
Comment: I declared chartData = []; outside the function
Answer: You can create a dynamically named array as a property of an object. Not entirely sure what your needs are but here's an example based on your provided code.
  var data = {};

  self.updateChart = function(name){
    // Store a shallow clone of the chartData array in the data obj
    data[name] = chartData.slice(0);

    if (typeof data[name] == 'undefined') {
      data[name] = [];
    }
    data[name].push({
      date: game.tickCount,
      visits: self.price,
    });
    priceLabour.validateData();
    return data[name];
  };

After calling updateChart you should be able to use data["myString"] elsewhere to refer to your array.


Prove $|y''(x)| \leq 40$ for all $x \in [1,3]$.

Question: $$y' = 2 - \sin(xy), \qquad\quad 1 \leq x \leq 3, \qquad\quad y(1) = -\frac{1}{2}$$
Attempt:=
$$|y''(x)| = |-\cos(xy)(y + xy')| \leq |y + xy'|$$
Not sure what to do next.
Answer: First of all, the IVP
$$\begin{cases}y' = 2- \sin(xy), \quad x \in [1,3] \\ y(1) = -1/2 \end{cases}$$
does not have a closed form solution. This means that we should find another way around.
Note that $y'(x) = 2 - \sin(xy)$. But we know that $-1 \leq \sin(x) \leq 1 \implies -1 \leq \sin(xy) \leq 1$.
This means that $y'(x) > 0 \forall x \in [1,3]$. That means that $y(x)$ is strictly increasing.
Now, use a numerical method for the IVP to approximate $y(3)$ since you have $y(1)$ and use that to find a bound for $|y''(x)| = |-(xy'(x)+y(x))\cos(xy)|$.
Note : I added the usage of a Numerical Method since I saw your "numerical-methods" tag.
Comment: Is $|y''(x)| = |-\cos(xy)(y + xy')|$ correct?
Comment: @user572780 Yes, I apologize, had a typo.
Answer: As already mentioned, using the fact that $-1  \leq \sin \leq 1$ you have
$$1 \leq y' \leq 3$$
so integrating between $1$ and $x$ we obtain
$$x-\frac{3}{2} \leq y(x) \leq 3x-\frac{7}{2}$$
and in particular
$$-\frac{1}{2} \leq y(x) \leq \frac{11}{2}.$$
And you can easily obtain
$$| y +x y'| \leq  \max(\frac{1}{2},\frac{11}{2}+3*3) = \frac{29}{2} <40$$
Comment: How did you get $x-\frac{3}{2}$ and $3x-\frac{7}{2}$?
Comment: You have for all $s \in [1,3]$, $1 \leq y'(s) \leq 3$. So integrating for $s$ between $1$ and $x$ you obtain $$\int_1^x 1 ds \leq \int_1^x y'(s) ds \leq \int_1^x 3 ds$$ i.e $$ x-1 \leq y(x)-( -\frac{1}{2}) \leq 3x -3$$ which leads to the desired inequality.


MSAL - use two different clientid from different directory

Question: I have an application that will be used by two different entities and each entity have their own Azure Active Directory.
Initially, the code I am using is:
var msalConfig = {
        auth: {
            clientId: '<client-id-1>'
            authority: "https://login.microsoftonline.com/<tenant-id>"
        },
        cache: {
            cacheLocation: "localStorage",
            storeAuthStateInCookie: true
        }
    };

Now what I want to happen is, can I put two different client ID, and tenant ID?
I could use multiple tenant in the first AAD, but I want to limit it to only two tenants. What should be my approach here?
Comment: I've written an article on these kind of apps, it might give you some pointers: https://joonasw.net/view/best-practices-for-n-tenant-azure-ad-applications
Comment: @juunas, it seems like it but I am not using .Net. If only there's also a documentation with MSAL.js for this concern
Answer: Question: I could use multiple tenant in the first AAD, but I want to limit it to only two tenants. What should be my approach here?
Answer: if you develop a multiple-tenant AD application, you can validate "id_token" with its issuer after your users log in. For example :
 var msalConfig = {
        auth: {
            clientId: 'b0114608-677e-4eca-ae22-60c32e1782d9', //This is your client ID
            authority: "https://login.microsoftonline.com/common" //This is your tenant info
        },
        cache: {
            cacheLocation: "localStorage",
            storeAuthStateInCookie: true
        }
    };
 var graphConfig = {
        graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
    };

    // create a request object for login or token request calls
    // In scenarios with incremental consent, the request object can be further customized
    var requestObj = {
        scopes: ["user.read"]
    };

    var myMSALObj = new Msal.UserAgentApplication(msalConfig);

    // Register Callbacks for redirect flow
    // myMSALObj.handleRedirectCallbacks(acquireTokenRedirectCallBack, acquireTokenErrorRedirectCallBack);
    myMSALObj.handleRedirectCallback(authRedirectCallBack);

    // difine issuers
    var issuers = new Array();
    issuers[0]="https://login.microsoftonline.com/{TenantId}/v2.0";
    issuers[1]="https://login.microsoftonline.com/{TenantId}/v2.0";

    function signIn() {
        myMSALObj.loginPopup(requestObj).then(idToken => {

            var issuer =String(idToken.idToken["issuer"])
            console.log(issuer)
            if(issuers.indexOf(issuer) != -1){
                //login successfully then your users can do otherthing

            }else{

                // your users use a wrong account
            }

        }).catch(function (error) {
            //Please check the console for errors
            console.log(error);
        });
    }

For more details, please refer to the document
Answer: You could try using the Factory pattern and create a method that will instantiate the clientApplication for the proper client. For example:
const msalConfigFoo = {
        auth: {
            clientId: '<client-id-1>'
            authority: "https://login.microsoftonline.com/<tenant-id>"
        },
        cache: {
            cacheLocation: "localStorage",
            storeAuthStateInCookie: true
        }
    };

var msalConfigBar = {
        auth: {
            clientId: '<client-id-2>'
            authority: "https://login.microsoftonline.com/<tenant-id>"
        },
        cache: {
            cacheLocation: "localStorage",
            storeAuthStateInCookie: true
        }
    };

function getClientApplication(clientType) {
   if (clientType == "foo") {
      return new Msal.UserAgentApplication(msalConfigFoo);
   } else {
      return new Msal.UserAgentApplication(msalConfigBar);
   }
}


Integral with residue theorem, zero or does not exist?

Question: Wolfram Alpha says that this integral does not converge
$$\int^{\pi/2}_{-\pi/2}\frac{\mathrm{d}x}{a+b\sin(x)},$$
$a,b \in \mathbb{R}^+$ with also the condition $b \geq a$.
Is it true? Making a fast calculation using the residue theorem I have found that it is equal to zero.
I have used the fact that $$\sin(x) = \frac{e^{ix}-e^{-ix}}{2i}$$ and the substitution $z = e^{ix}$.
Comment: I think it converges if $a > b$. Otherwise, there is a simple pole at $x = \arcsin(- a/b)$. Maybe you want to compute the principal value?
Comment: Mmm, I noticed that the value of the integral is equal to half the value on $-\pi, \pi$. Using the substitution I proposed the poles belongs to the unit circle. If we integrate inside the circle we get zero so shouldn't the integration on the "limit circle" (i.e the unit circle) be zero?
Comment: The point is that even if you integrate inside the circle you can't neglect a pole that's right on the contour.
Comment: @jennifer so what to do in such a case?
Comment: See http://math.stackexchange.com/questions/721475/general-method-of-integration-when-poles-on-contour or http://math.stackexchange.com/search?q=pole+on+contour
Answer: If $b \ge a > 0$ there is a singularity at $x = \arcsin(-a/b)$, and the integral diverges.  However, if $b > a > 0$ it will have a Cauchy principal value.
Comment: Can you please compute that value?
Answer: Robert Israel provided the good explanations.
Concerning the antiderivative, using the tangent half-angle substitution, you should arrive to $$I=\int \frac{dx}{a+b\sin(x)}=\int\frac{dt}{at^2+2bt+a}$$ If $b \neq a$, then $$I=\frac{2 \tan ^{-1}\left(\frac{a \tan
   \left(\frac{x}{2}\right)+b}{\sqrt{a^2-b^2}}\right)}{\sqrt{a^2-b^2}}$$ from which (if $a>b$)$$J=\int^{\pi/2}_{-\pi/2}\frac{dx}{a+b\sin(x)}=\frac{2 \left(\tan ^{-1}\left(\frac{a-b}{\sqrt{a^2-b^2}}\right)+\tan
   ^{-1}\left(\frac{a+b}{\sqrt{a^2-b^2}}\right)\right)}{\sqrt{a^2-b^2}}$$ Now, using $$\tan^{-1}(p)+\tan^{-1}(q)=\tan ^{-1}\left(\frac{p+q}{1-p\, q}\right)$$ should give (since, here, $p\,q=1$) $$J=\frac \pi{\sqrt{a^2-b^2}} $$


Adding an hour feature to data

Question: I need to add an hour feature to my data.
Assigning "dummy variables" (which is what I usually do) does not work in this case, apparently (wouldn't elaborate - but believe me this is so).
At first, I simply assigned the hour itself (13:00 - 13, 14:00 - 14, etc...)
But then I realized this means 23:00=23 is radically different in value from 00:00=0, which is clearly undesirable since they are quite close in reality.
I read in google and found there's the following transformation:
sin(2*pi / 24 * hour) which would result in hour 23:00 and hour 00:00 both giving close values.
However, I have several issues with the new method:

hours 5 and 7 (for instance) are indistinguishable to the algorithm as they have the same value (0.965)
Another problem is that, for instance, the difference in value between hour 6 (1.0) and 7 (0.965) is different from the different of 7 (0.965) to 8 (0.877) - which, of course, does not reflect reality (at least not in my case).

Is there any other, better solution to this problem than I raise above?
Comment: Why is closeness in time an issue in modelling hours for your model?
Answer: A linear time effect can be used to model certain phenomena, like the accumulation of muscle relaxants as participants endure longer periods of forced wakefulness, or growth trends of alligators. In general, though, it is a bad idea to use linear time for the reasons you mention, since when those assumptions fail, they can fail catastrophically. However, those assumptions can be checked by using a residual plot which you should do.
The "google" source is a start but likely not a good suggestion unless you can better describe the problem. it is just modeling something that "goes up" at hours 6 and 18 and "goes down" at hours 0 and 12. Whether or not that's appropriate is your call and yours alone. You have described some limitations which I can address directly in a proposed solution below, but rather than discarding ideas which are or are not applicable to your problem, try describing it.
You can use a complex representation of cyclic time using convolutions or equivalently splines. This uses multiple features, but you can subselect sparse representations with any feature selection method.
A continuous linear representation of time involves creating a triangle wave representation of time. Using 6 hour intervals, a time data frame would map to the following 4 features:

Which, demonstrating with regression creates the following:
<code>set.seed(123)
library(splines)
rep <- bs(0:23, degree = 1, knots=c(1:3*6))
rep[1:6, 4] <- rev(rep[19:24, 4])
y <- rnorm(24, sin(0:23 * pi / 12), 0.4)
fit <- lm(y ~ 0 + rep)
plot(y)
lines(predict(fit))
</code>

It should be said this is basically a poor man's fast-fourier transform. If you fit a regression model, you can use FFT to handle cyclic auto-regressive or time-depend errors by using a frequency decomposition to estimate what fluctuations in errors owe to unknown periodic effects. This is discussed in some detail in Diggle's Book Time Series: A biostatistical introduction, which might be a good reference in general.
Answer: Not sure what exactly your goal is here, maybe then there may be a better solution. However, if you only want to disentangle the hours 5 and 7 (among others) the simplest solution is to create two features:

sin(2*pi / 24 * hour)
cos(2*pi / 24 * hour)

Which basically translates each our to its position on the clock circle. Depending on the application (e.g. if you are doing some kind of clustering), this may just work. For other applications, this may fail horribly, but it is impossible to tell with this little information.

Adding an hour feature to data


I am trying to execute it but it throws error of 'SQLSTATE[IMSSP]: This function is not implemented by this driver.'

Question: I have tried calling the function but it gives me errors always.
My code is below
$name = 'Devrishi Pandey';
$return_message = prepared_insert($pdo, 'my_table', ['name' => $name]);
function prepared_insert($pdo, $table, $data) {
    $keys = array_keys($data);
    $fields = implode(",", $keys);
    $placeholders = str_repeat('?,', count($keys) - 1) . '?';
    try{
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $pdo->prepare($sql);
        $pdo->execute($data);
        return $pdo->lastInsertId();
    } catch(PDOException $e){
        return $sql . "
" . $e->getMessage();
    }
}

Comment: Can you echo out your `$sql` to see what it contains?
Answer: The execute function is for a PDOStatement, not connection. You need to assign the prepared statement to a variable then execute on that.
$name = 'Devrishi Pandey';
$return_message = prepared_insert($pdo, 'my_table', ['name' => $name]);
function prepared_insert($pdo, $table, $data) {
    $keys = array_keys($data);
    $fields = implode(",", $keys);
    $placeholders = str_repeat('?,', count($keys) - 1) . '?';
    try{
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($data);
        return $pdo->lastInsertId();
    } catch(PDOException $e){
        return $sql . "
" . $e->getMessage();
    }
}