Aonde salvar dados no Angular aonde possam ser acessados de qualquer lugar e, ao alterá-los, atualizar componente

Question: Bom pessoal, minha questão pode ser bem idiota mesmo, mas é porque estou estudando sobre o Angular e como utiliza-lo.
Gostaria de saber aonde posso salvar dados que, ao alterá-lo, posso recuperar em qualquer lugar do sistema e também, atualizar o componente.
Por exemplo
Tenho uma pagina que é a home-page, dentro dela tenho o menu e a opção de selecionar a empresa aonde o usuário está logado.
Quando essa empresa for alterada no meu dropdown button, gostaria que o dados no meu  atualizassem.
Para tentar explicar melhor o que gostaria, vou postar o seguinte código da minha "home.html"
Aqui, na minha pagina home.html, eu seleciono um estabelecimento:
    <button mat-button [matMenuTriggerFor]="menuEstab">
        store
        {{estabelecimento.nomeFantasia}}
    </button>
    <mat-menu #menuEstab="matMenu">
        <ng-container *ngFor="let estab of estabelecimentos">
            <button mat-menu-item (click)="changeEstab(estab)">
                business
                {{estab.nomeFantasia}}
            </button>
        </ng-container>
    </mat-menu>

Hoje, ao selecionar qual o estabelecimento que quero utilizar para o usuário que está logado, eu salvo no sessionStorage:
  public changeEstab(estab: Estabelecimento) {
    this.estabelecimento = estab;
    sessionStorage.setItem(environment.currentEstab, JSON.stringify(estab));
  }

Porém, meu componente que está no centro da página, não sabe que o estabelecimento foi alterado, mas eu preciso saber.
<mat-sidenav-content>
    <router-outlet></router-outlet>
</mat-sidenav-content>

Não sei se consegui me explicar direito, mas, qual a melhor maneira de fazer isso?
Obrigado.
Comment: Realmente não ficou muito claro sua questão man.
Comment: Pois é... o que eu quero é salvar os dados do usuário logado em um lugar e poder recuperar eles em qualquer outro componente, e, quando esses dados alterarem, que meu componente saiba que eu preciso atualizar para executar novas pesquisas.
Comment: Ou seja, o que você está querendo é um banco de dados.
Comment: @LeAndrade não... Eu quero que a minha aplicação tenha acesso aquela única instância, único objeto, como se fosse um Singleton. Algumas páginas dependem do conteúdo deste singleton e, quando ele alterar, essas páginas precisam ser atualizadas. Quando ele é alterado: Na minha mat-toolbar que é exibida em toda a aplicação há a possibilidade de alterar o emitente atual, ao alterar, as página que se encontra visível, deve atualizar com o estabelecimento selecionado.
Answer: Bom pessoal, estou estudando por conta e acho que pulei algumas etapas antes de começar a implementar o software.
Para resolver o meu problema passei a utilizar NgRx.
Essa abordagem é nova para mim, porém, depois de estudá-la bastante, implementei e resolveu o meu problema.
Obrigado a todos.


String para Double - Ajuda!

Question: Estou tentando somar uma coluna de um JTable. Alguma sugestão de como fazer?
public void actionPerformed(ActionEvent arg0) {
                try {
                    double itens = 0;
                    double soma = 0;

                    for (int i = 0; i < jtbRacao.getColumnCount(); i++) {
                        itens = Double.valueOf((String) jtbRacao.getValueAt(i, 3));
                        soma += itens;
                    }
                    lblPB.setText(String.valueOf(soma));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Erro ao calcular Total Produtos: " + e.getMessage());
                }
            }

Stack trace
Wed Jul 19 16:33:17 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:20 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:20 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:23 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:23 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "3,58"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at java.lang.Double.valueOf(Unknown Source)
    at VIEW.TelaRacao$7.actionPerformed(TelaRacao.java:313)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Comment: Não mascare o erro com esse catch, deixa a exceção estourar e cole a pilha de erros aqui.
Comment: Douglas, descobri...na verdade eram dois erros: o que vc indicou sobre a troca da vírgula pelo ponto e o outro era o getColumnCount q na verdade o correto é getRowCount...deu certo!
Comment: Troca a vírgula da string por ponto.
Comment: Erro ao Calcular Total Produtos: 2 >= 2
Comment: Esqueci de avisar que já havia tentado com inteiro e retornou esse erro.
Comment: tenta fazer: `itens = Double.parseDouble( ((String) jtbRacao.getValueAt(i,3)).replace(",", ".") );`
Comment: Douglas, não deu certo! Creio que não seja um problema relacionado a vírgula, pois tentei calcular mudando a variável para inteiro e também não deu.
Comment: Quando pego a célula especifica me parece que ela retorna um Object. Pode ter alguma relação?
Comment: Pelo erro, pra mim parece culpa da vírgula mesmo. Faz `System.out.println(jtbRacao.getValueAt(i, 3));` e nos diga a saída, pra sabermos o que está sendo retornado aí.
Comment: 3,58 vou postar a imagem da coluna que estou pegando os valores...
Comment: "3,58" não vai converter para Double, mas "3.58" deveria. Pelo que entendi, vc está dizendo que nem "3.58" está convertendo? Execute isso: `System.out.println("Valor convertido: "+Double.parseDouble("3.58"));` Se até esta linha lançar uma Exception, então eu não faço ideia de como resolver seu problema.
Comment: Exception in thread "AWT-EventQueue-0" 3.58
5.07
java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
 at java.util.Vector.elementAt(Unknown Source)
 at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
 at javax.swing.JTable.getValueAt(Unknown Source)
 at VIEW.TelaRacao$7.actionPerformed(TelaRacao.java:313)
Comment: Alterei os valores da coluna para "3.58" e "5.07" e calculei...veja a resultado aí acima.
Comment: Ótimo, se a resposta de alguém abaixo resolve seu problema, marque ela como aceita; caso contrário, crie uma resposta e marque ela como aceita. :)
Answer: Alguns pontos que vi aqui:

Na tela, a coluna deve estar mostrando casas decimais com "," ao invés de ".", que é o esperado pelo método Double.parseDouble(). Use a classe java.text.NumberFormat para converter e formatar valores de e para strings localizadas.
No laço for, você está indo de 0 até o número de colunas, deve ir na verdade até o número de linhas.
Para somar valores e outras operações que necessitam de precisão, não é bom usar nem float nem double, por serem pontos flutuantes. É mais interessante usar a classe java.math.BigDecimal.

Observando isso, ficaria assim:
public void actionPerformed(ActionEvent arg0) {
    try {
        BigDecimal soma = BigDecimal.ZERO;
        // pega o formato de número para o "locale" atual
        NumberFormat nf = NumberFormat.getNumberInstance();

        // varre todas as LINHAS da tabela, coluna 3
        for (int i = 0; i < jtbRacao.getRowCount(); i++) {
            String coluna = jtbRacao.getValueAt(i, 3).toString();
            // converte de string para number
            Number valor = nf.parse(coluna);
            // soma com o total atual. BigDecimal sempre retorna uma instância nova, então precisa atualizar a variável
            soma = soma.add(new BigDecimal(valor.toString()));
        }
        // formata a soma para exibir no label
        lblPB.setText(nf.format(soma));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Erro ao calcular Total Produtos: " + e.getMessage());
        // não esqueça de escrever a exceção no log...
        e.printStackTrace();
    }
}

Answer: Aparentemente o seu problema deve ser na conversão de valor String para o Double,
tenta fazer um replace de virgula para ponto.
Ex:
String valor = "9,99"
valor = valor.replace(",", ".");
Double valorDouble = Double.parseDouble(valor);

Comment: Felipe, tentei sua sugestão mas infelizmente não deu certo...

String para Double - Ajuda!


Failed to restart Apache server

Question: I'm trying to restart Apache through Plesk. When I click "Restart", i'm getting the following message.

Error: Unable to make action: Unable to manage service by
  apache_control_adapter: Service /etc/init.d/httpd failed to start
  ('--start', 'web')

I also tried(thanks to paulsm4 from stackoverflow to do it through the terminal. I typed

sudo /etc/init.d/httpd start

and the error i got is:

Starting httpd: (98)Address already in use: make_sock: could not bind
  to address [::]:80 (98)Address already in use: make_sock: could not
  bind to address 0.0.0.0:80 no listening sockets available, shutting
  down Unable to open logs [FAILED]

Thank you in advance!
Answer: httpd seems to be still running in a bad state...
try:
<code># kill -9 $(pidof httpd)
# /etc/init.d/httpd start
</code>
You should also verify that logs exists and have good permissions.
Comment: Got a blank line on "".
And on the second line I got "Starting httpd: [  OK  ]".

can you where can i verify that logs exist?
Comment: if the output of `service httpd status` is *running*, that's ok. I don't use RH or derivated, but debian, so i think (i can be wrong) that logs are in /var/log/httpd/{access,error}.log
Comment: When i edit/access the php.ini file and the log files as you said, I see that they are empty.
Comment: Also when i login to the server and type "ls", I get
"install.log
install.log.syslog
kmod-microsoft-hyper-v-rhel63.3.4-1.20120727.i686.rpm
kmod-microsoft-hyper-v-rhel63.3.4-1.20120727.x86_64.rpm
microsoft-hyper-v-debuginfo-rhel63.3.4-1.20120727.i686.rpm
....
microsoft-hyper-v-rhel63.3.4-1.20120727.src.rpm
microsoft-hyper-v-rhel63.3.4-1.20120727.x86_64.rpm
parallels
plesk10-install.log
plesk-installer.log
ZendGuardLoader-php-5.3-linux-glibc23-x86_64
ZendGuardLoader-php-5.3-linux-glibc23-x86_64.tar.gz"

So I guess something's wrong there.
Comment: ls command list your actual working directory. That means your user directory contains  a lot of redhat packages(rpm), that's not clean but this is not a problem. Logs can be anywhere, depending on your plesk config. Is the webapp ok now?
Comment: Apache is still down. I'm kinda lost! Don't know what to do.
Comment: what is the output of `pgrep -l -u apache` and `pidof httpd`
Comment: Both return nothing. Just going to the next line.
Comment: ok and `sudo fuser 80/tcp`
Comment: It returns
"80/tcp:               7168"
Comment: ok now `ps 7168`
Comment: PID TTY      STAT   TIME COMMAND

(I guess it's empty)
Comment: wow... can you type `sudo fuser 80/tcp` again
Comment: Sure.
Still getting nothing. Just skips to the next line.
Comment: so try to start `service httpd start`
Comment: Still the same message:
"Starting httpd: (98)Address already in use: make_sock: could not bind to address [::]:80
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
[FAILED]"

Failed to restart Apache server


Devise: NoMethod Error & user_signed_in

Question: I'm trying to use user_signed_in? to add a login area to my rails 3 application using devise 1.1.3 and I get a NoMethodErrorin Rules#index
<% if user_signed_in? -%>

  <%= current_user.email %> |
  <%= link_to 'My info', edit_user_registration_path %> |
  <%= link_to 'Sign out', destroy_user_session_path %>

<% end -%>

I'm not sure what's wrong exactly, but clearly the devise method isn't being used. I'm also fairly (read: really) new to rails and haven't used devise before.
Comment: If, you remove `user_signed_in?` and login, and get to the page displaying your mentioned view, is the `<%= current_user.email %>` displayed or not ?
Comment: It isn't. I get this:
undefined local variable or method `current_user' for #<#:0xab962d4>
Answer: What is the name of the model you generated Devise for?
If you called it something else instead of User, you might want to check out http://groups.google.com/group/plataformatec-devise/msg/67f1eb5a571b6136
Answer: I had the exactly the same issue.
    undefined local variable or method 'edit_user_registration_path'
However, I have devise :database_authenticatable, but not :registerable.  After I added the :registerable everything works!
Answer: You seem to be missing the call to devise :database_authenticatable in your User model.
Also, a good way to get started with devise is to look at the excellent RailsCasts by Ryan Bates :  Introducing Devise.
Answer: It also may happen that your trying to call that route from another engine, so in that case you have to specify the context for that route, like main_app.edit_user_registration_path.

Devise: NoMethod Error & user_signed_in


Data binding to the output of a method

Question: I'm trying to display the output of a method in a WPF TextBox. I'm just trying a simple attempt, to print a single string 3 in a TextBox.
I'm trying to do it the following way, using an ObjectDataProvider:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:system="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

        <ObjectDataProvider x:Key="dataprovider" ObjectType="{x:Type system:String}" MethodName="GetValue">

        </ObjectDataProvider>
    </Window.Resources>
    <Grid>

        <TextBox Text="{Binding Source={StaticResource dataprovider}, Mode=OneWay}" HorizontalAlignment="Left" Height="23" Margin="201,168,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

And here's my code behind:
namespace WpfApplication1
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public string GetValue()
        {
            return "3";
        }
    }
}

I'm getting no output. the TextBox is just blank. Where am I going wrong?
Answer: Instead of ObjectDataProvider create a property like this:
public string GetMethod
{
     get
     {
         return GetValue();
     }
}

And:
public MainWindow()
{
     InitializeComponent();
     DataContext = this;
}

Then in the XAML remove ObjectDataProvider and just:
<TextBox Text="{Binding GetMethod, Mode=OneWay}" HorizontalAlignment="Left"
         Height="23" Margin="201,168,0,0" TextWrapping="Wrap"
         VerticalAlignment="Top" Width="120"/>

Data binding to the output of a method


Will these frogs ever meet?

Question: Two frogs are on an eternal stairway. Will they ever be able to meet?
Anton is on step 14 and jumps 4 steps.
Billy is on step 16 and jumps 6 steps.
The way I look at this is that as long as they're not on the same step, the one on the lowest jumps next, so:

Their difference (Anton-Billy) is -2
Anton jumps to step 18, difference = 2
Billy jumps to step 22, difference = -4
Anton jumps to step 22 - THEY MEET

If Anton had been on step 15 instead:

Their difference is -1
Anton jumps to step 19, difference is 3
Billy jumps to step 22, difference is -3
Anton jumps to step 23, difference is -1
Since the difference has repeated, they will never meet

However, I am certain there's a much better way to find out if and where they will ever meet in a single equation.
Answer: In the very general case, suppose Anton starts on step $a_0$ and jumps by $a$ steps each time. Similarly, suppose Billy starts on step $b_0$ and jumps by $b$ each time. Let $n$ denote the number of jumps made by Anton, and $m$ the number of jumps made by Billy.
Then, we are trying to ask if the equation
$$a_0 + an = b_0 + bm$$
has a solution, for variables $n, m$ and constants $a_0,a,b_0,b$. Rewrite this equality as
$$an - bm = b_0 - a_0$$
This is a linear Diophantine equation in two variables. It is well-known that this has solutions if and only if $\gcd(a, b)$ divides $b_0 - a_0$ (see e.g. this math.se post), and thus the frogs can meet if and only if the difference in their starting positions is divisible by the greatest common divisor of their step distances.

For your specific instance, we have $a=4$ and $b=6$, whereby $\gcd(a,b)=2$. Thus, Anton and Billy meet only if the difference between their starting steps is even.
Comment: Yes, you can solve the Diophantine equation using that link (it isn't difficult math). You get an infinite number of solutions, and can pick any solution that you like.
Comment: Thanks. That was a good explanation.

Knowing now that they will meet, is there a quick way to determine where they meet, or is that explained in the link you included?
Comment: Thank you. Much appreciated.
Comment: Having some issues getting my brain wrapped around this. Would you be willing to give an example of how to use that to get to the first step (10) where Anton and Billy would meet if they started at a0 (2) and b0 (4)?
Thanks again!
Comment: FYI, a quick way to see that in the Anton starts on 15 example that they never meet, simply note that Anton will always be on an odd step, and Billy will always be on an even one. This is a consequence of nneonneo's last statement, but is more easily seen.
Answer: Stated formally the question is as follows:
Are there any non-negative integer numbers M,N such that:
14 + 4N = 16 + 6M ?
This is same as
2N = 1 + 3M
This means 2N has to give remainder 1 when divided by 3.
This only happens when N has the form: N = 3L + 2, where L is integer >= 0.
You can find this out directly by trying (for N) all remainders modulo 3.
Since 2 and 3 are co-prime, you get only 1 solution here, only 1 remainder modulo 3 which works.
Now the last equation becomes:
2.3.L + 4 = 1 + 3M
6.L + 3 = 3M
2L + 1 = M
Now, when we summarize what we got so far,
we see that the frogs meet for all numbers N, M
such that: N = 3L + 2, M = 2L + 1 (where L = 0, 1, 2, 3, 4, ...).
Comment: Still not sure I understand your explanation, but thanks for helping.
Answer: Stated formally the question is as follows:
Are there any natural numbers M,N such that:
14N + 4 = 16M + 6 ?
This is same as
7N = 1 + 8M
This means 7N has to give remainder 1 when divided by 8.
This only happens when N has the form: N = 8L + 7, where L is integer >= 0.
You can find this out directly by trying all remainders.
Now the last equation becomes:
7.8.L + 49 = 1 + 8M
56.L + 48 = 8M
7L + 6 = M
Now, when we summarize what we got so far,
we see that the frogs meet for all numbers N, M
such that: N = 8L + 7, M = 7L + 6 (where L = 0, 1, 2, 3, 4, ...).
Comment: I think you made a mistake. Wouldn't it be:

14N - 16M = 2

7N - 8M = 1
Comment: @OleDrewsJensen Yes, I was just chasing it too :) I just found it. Thanks.
Comment: I see you edited it, so ignore my last, but not sure I understand the edited version... :-) Let me study it for a minute.
Comment: My whole calculation is messed up. I was solving a different problem: A is on step 4 and jumps 14 steps, B is on step 6 and jumps 16 steps. Should I edit it for the real problem? The real is much simpler.
Comment: So the only way I can solve this, is by trying all remainders?

Thanks.
Comment: I added another answer. I will keep this one here for a while as you may want to solve that other problem too :)
Comment: Well, OK, not really by trying all remainders blindly. If you know some theory you will know there's only 1 remainder which works there (because 7 and 8 are relatively prime). You just have to find that 1 remainder which works. And for that, I think you really have to try all remainders. I don't try them all, I see it almost immediately.
Comment: What would the simpler version you're mentioning be? Thanks.
Comment: No simpler version. Not sure what you mean. Trying all remainders at that step is required, but as we have modulo 8 which is small (and not say 800) that's not a problem. The real solution to your problem is in my 2nd answer.
Comment: You said in a previous comment "Should I edit it for the real problem? The real is much simpler."
Comment: The solution to your real problem is in my other answer. As you see, the calculation there is simpler (because instead of 7 and 8, we have 2 and 3).
Answer: There is! Let $n$ and $m$ be integers corresponding to the jumps of the frogs. Let $x$ and $y$ be the initial positions. Now if we are seeing if we can make two frogs equal, we are checking to see if we can write $x+ni=y+m=j$ for integers $i, j$, so we are asking if $x-y=(mi-nj)$. The term on the right is a multiple of the greatest common denominator of $n$ and $m$, so that $x-y=kgcd(n, m)$, so that conidition is that $gcd(n, m)|(x-y)$.
Comment: Not sure about ni and mi, as i is different from n and m.

x had to "jump" 4 twice, and y had to "jump" only once, before they both met at 22.
Comment: Since the jumps may or may not be the same, I assume we'll have to look at the jumps as i and j (as you actually mentioned in your reply). So it would look something like:

x-y = m^j-n^i

Not sure where to go with that, but thanks again for your post.
Comment: You are right! I misunderstood your question. Not it is less elementary, but the solution has been edited
Comment: Thanks, that makes more sense, and looks similar to the link about linear Diophantine equation in another answer above. My only problem is that I have not (yet) been able to understand how to get the first step where they meet.
Answer: It is trivial to prove that they always meet if they start in the same step. If they don't :
Let :
$x$ = step at which the frog which starts lower starts
$m$ = nº of steps the frog wich starts lower jumps each time
$y$ = step at which the other frog starts
$n$ = nº of steps the other frog jumps each time
$Z$ = $(y-x)$ modulo $n$
$D$ = maximal common divisor of $m$, $n$ and $Z$
The frogs meet if and only if $\frac{m}D$ and $\frac{n}D$ are coprimes.
Proof:
The question is asking if there exist two non-negative integers $i$ and $j$ such that this equation (1) is satisfied :
$$x+mi = y+nj$$
This is equivalent to (2) :
$$mi = (y-x) + nj$$
Let's define Z as (y-x) modulo n:
Equation (2) is equivalent to (3):
$$mi = Z + nj$$
It is trivial to prove the equivalence if $(y-x)<n$ since $(A\pmod{B}=A)$ when $A=n$ we may rewrite (2) as (4):
$$mi=(Z+nk)+nj=Z+n(k+j)$$
With k being an integer such that $(Z+nk)=(y-x)$. And now we are looking for integers $i$ and $(k+j)$ which satisfy the equation, which is no different than looking for integers $i$ and $j$. Thus we have proved that (2) is equivalent to (3) in all cases.
Let $D$ be the maximal common divisor of $m$, $n$ and $Z$. Equation (3) is equivalent to (5):
$$\frac{m}Di=\frac{Z}D+\frac{n}Dj$$
If $\frac{m}D$ and $\frac{n}D$ are not coprime :
 In such case there is a divisor $E$ greater than 1 for both $\frac{m}D$ and $\frac{n}D$. But E is not a divisor of $\frac{Z}D$, otherwise D could not be the mcd of $m$, $Z$ and $n$. This means that $\frac{m}Di$ and $\frac{n}Dj$ will be multiples  of E for all values of $i$ and $j$. Rewriting (5) as (6) we have :
$$\frac{m}Di-\frac{n}Dj=\frac{Z}D$$
Implying that a multiple of $E$ is equal to a non-multiple of $E$, which is not possible. Thus if $\frac{m}D$ and $\frac{n}D$ are not coprime the equation can't be satisfied (the frogs will never meet)
If $\frac{m}D$ and $\frac{n}D$ are  coprime :
Let's rewrite (5) as (7):
$$Ai=C-Bj$$
Since $A$ and $B$ are coprime, from Bézout's identity we know that there exist integers $p$ and $q$ such that (8):
$$Ap + Bq = 1$$
(8) is equivalent to (9) :
$$Ap = 1 - Bq$$
(9) is equivalent to (10) :
$$ACp = C - BCq$$
Thus we have proved that (7) can be satisfied with $i=Cp$ and $j=Cq$ when $\frac{m}D$ and $\frac{n}D$ are  coprime
Comment: Thanks for that answer. My head hurts now. :-)

I am not looking for a proof, only a way to check if they will meet, which I have found from previous answers.

I am now looking for the first (smallest number) step where they will meet, but as far as I can see (I still haven't grasped all the answers yet), the methods posted finds multiple steps where they meet, and I'll have to "dig around" to find the first (smallest).
Comment: What is the minimun number of steps required to make the frogs meet should be handled in a different question.
Answer: jump to ten. This answer would have been more concise but for the character count.
Comment: Thanks :-) I did know that. :-)
Was hoping for something that would find the first (lowest) step on much larger numbers too.

Will these frogs ever meet?


Convergence of improper integral: $x^2\cos(e^x)$

Question: I am pretty sure the following converges, but I'm having trouble proving it.
$$\int_0^\infty x^2\cos(e^x)dx$$
I tried breaking up the integral into pieces, where each piece corresponds to a period of $\cos(e^x)$, but I'm stuck.
Any hints?
Edit: Later I'd like to extend the argument to other exponents, e.g. $\int_0^\infty x^{1000} \cos(e^x)$. I know that not every exponent works, but I think that exponents > -1 work.
Comment: For convergence you rely on the interval between two successive zeros shrinking much faster than the peak is rising. It should not be hard to formalise that into a rigorous argument.
Comment: That's definitely the picture that's been in my head, but I can't figure out a way to make that into a nice rigorous argument.
Answer: Let $x= \ln y.$ Your question is then the same as asking if
$$ \int_1^\infty (\ln y)^2 \cos y \frac{dy}{y}$$
converges. Because $(\ln y)^2/y$ is eventually decreasing, Dirichlet's test shows the answer is yes.
Comment: This is great thanks! I'll read up on Dirichlet's test.
Comment: Seems like this approach works as long as the exponent, call it $b$, is greater than or equal to zero ($b=2$ in the given problem). If $b<0$, then $\ln(y)^b/y$ is unbounded at 1. I believe that the integral converges for all $b>-1$, so this proof doesn't extend to that case. Of course, that isn't the problem I asked, just leaving this as a note (to myself and maybe others).
Answer: A start: Rewrite the integrand as $x^2e^{-x}e^x\cos(e^x)$, and integrate by parts, with $u=x^2e^{-x}$ and $dv=e^x\cos(e^x)\,dx$. Then $du=(-x^2e^{-x}+2xe^{-x})\,dx$ and we can take $v=\sin(e^x)$.
Comment: @animal_magic: Just saw your edit. Essentially the same argument will work for $x^{1000}\cos(e^x)$, because in the long run the $e^{-x}$ crushes any polynomial. For negative powers of $x$, the behaviour becomes simpler "at" $\infty$, but there is potential trouble at $0$. However, for $x^{-p}$ where $p\lt 1$, it is OK near $0$ by comparison.
Comment: Ended up going in a circle with the integration by parts, but maybe that's just an error on my part.
Comment: I can write more detail if you wish. However, I can guess what you are trying to do, and would rather you finished the argument. After the first integration by parts, there is an integral remaining. **Do not attempt** to evaluate it, just show it exists. This should be relatively easy. For $\sin(e^x)$ stays between $-1$ and $1$, and the rest of the stuff decreases rapidly because of the $e^{-x}$, so the (improper) integral converges. To repeat, I am ready with more detail if you keep having difficulty.
Comment: Oh I see, I was trying to evaluate it. I'll take another look.


Projective plane - equation in $\Bbb R^5$

Question: I've just read that the projective plane $\Bbb RP^2$ is a surface equivalent to the set of $(x,y,u,v,w) \in \Bbb R^5$ such that
$$u^2=xy,v^2=x(1-x-y),w^2=y(1-x-y)$$
How is it true? I don't see how to get this result, even looking at questions like these : Give an explicit embedding from $\mathbb{R}P_2$ to $\mathbb{R}^4$, Injective map from real projective plane to $\Bbb{R}^4$, embedding projective plane in 4-space?.
Thank you!
Comment: I tried to "prove" the equations were correct using "obvious" choices of maps from $S^2$ to $\mathbb{R}^5$ (similarly to how was one in the questions you linked).  After failing several times, I decided to find a reason I was failing, hence my answer.
Comment: Where did you read about this?
Comment: I saw it on slides (for explaining Poincaré's conjecture). The first page gives the link http://milnor.math.ucl.ac.be/plwiki/Olympiades2007/ but it seems to be dead now.
Comment: More precisely, I would like to know: where do these equations come from? If we look at [this](http://math.stackexchange.com/questions/886616/injective-map-from-real-projective-plane-to-bbbr4) question, the equations are "proved" to be "correct"… But what about the ones here? The problem is that I don't know exactly what is meant by "equivalent".
Answer: I'm not sure what is meant by "equivalent", but it is not as smooth manifolds.  More specifically, the set $$X=\{(x,y,u,v,w): u^2 = xy, v^2 = x(1-x-y), w^2 = y(1-x-y)\}$$ is not a smoothly embedded submanifold of $\mathbb{R}^5$.
To see this, consider the point $p = \left(0,\frac{1}{2},0,0,\frac{1}{2}\right)\in X$.  I claim that $T_p X$ contains the three vectors $(0,1,0,0,0)$, $(0,0,1,1,0)$ and $(0,0,1,-1,0)$.  Thus, if $T_p X$ is a vector space, it's a least 3-dimensional.  On the other hand, we will find a path $\alpha(t)$ in $X$ connecting $p$ to another point $q\in X$ where the tangent space is $2$-dimensional.  Thus, on a single connected component of $X$ we find it's $2$ dimensional and at least $3$ dimensional, a contradiction.
So, let's argue that $T_p X$ contains those three vectors.
To do that, let $\gamma(t) = (0,t,0,0,\sqrt{t-t^2})$.  Then one can easily verify that $\gamma\left(\frac{1}{2}\right) = p$, $\gamma(t)\in X$ for all $t$ it's defined, and $\gamma'\left(\frac{1}{2}\right) = (0,1,0,0,0)$.
For the other two, consider $\alpha_{\pm}(t) = \left( 2t^2, \frac{1}{2}, t, \pm t\sqrt{1-4t^2}, \sqrt{\frac{1}{4}-t^2}\right)$.  Then $\alpha_{\pm}(0) = p$, and $\alpha_{\pm}(t)\in X$ whenever it's defined, and $\alpha'(0) = (0,0,1,\pm 1,0)$.
Finally, for either choice of $\alpha$, note that for small non-zero $t$, all components are non-zero.  So $\alpha$ is a path in $X$ connecings $p$ to a point where are coordinantes are non-zero.
Now, one can compute the jacobian:  One gets $\begin{bmatrix}-y & -x & 2u & 0 & 0\\ 2x + y-1 & x & 0 & 2v & 0 \\ y & 2y+x-1 & 0 & 0 & 2w\end{bmatrix}$.  In particular, if $u$, $v$, and $w$ are all non-zero, this matrix has full rank.  Thus, at such points, the tangent space of $X$ is $2$-dimensional.
Comment: @Alphonse:I don't know the MSE rules on bounties, but if there is some way you can save some of your reputation points by not awarding me, please do so.  In my own opinion, I have not satisfactorily answered your original question.
Comment: I suspect that $X$ isn't even a topological manifold at $p$, so I think $X$ isn't homeomorphic to $\mathbb{R}P^2$ (or any other manifold), but I'm not sure how to prove it.
Comment: Thank you for your answer! I agree that the word "equivalent" they used is vague. But is there a way to "see" $\Bbb{RP}^2$ in $\Bbb R^5$ (maybe only as topological _space_) using these equations? I mean where do these equations come from?
Comment: I think that the reputations points will be lost… Even if your answer is very interesting (thank you for your effort!), I agree with you: I think that I won't award you the bounty.


How to check if a state object is of type ICollection

Question: I use the nhibernate interceptor to compare values of the old state and the current state of the entity properties but some of the properties are of type ICollection so could anyone guide me about how to check if an object is of type ICollection
this is my code
    public void OnPostUpdate(NHibernate.Event.PostUpdateEvent @event)
    {
        var entityToAudit = @event.Entity as IAuditable;
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuditLog.txt");
        using (StreamWriter sw = File.AppendText(path))
        {
            for (int i = 0; i < @event.OldState.Length; i++)
            {
                string propertyName = @event.Persister.PropertyNames[i];
                if (@event.OldState[i] != null)
                {
                    if (!@event.OldState[i].Equals(@event.State[i]))
                    {
                        sw.WriteLine("the value of "+ propertyName + " has been changed from " + @event.OldState[i] + " to " + @event.State[i]);
                    }
                }
                else
                {
                    if (@event.State[i] != null)
                    {
                        sw.WriteLine("the value of "+ propertyName + " has been changed from being empty to " + @event.State[i]);
                    }
                }
            }
        }
    }

Comment: Collections have their own kind of "previous"-state tracking anyway. There is (usually) only one instance of a collection, so you cannot compare it that easily. By the way, I wouldn't have a good feeling when writing to a file in an OnPostUpdate trigger. Apart from very bad performance, imagine the very nasty dead-locks you might get with circular file locks and database locks.
Answer: You have more than one options to do this, use is or use as with null checking:
if (obj is ICollection){
    //your logic
}

Or, if you need the object as ICollection later on, I recommend to use as:
var icoll = obj as ICollection
if (icoll != null){
    //use icoll
    //icoll.Something();
}

Answer: you can check the type using a simple is
like this:
var obj = getObject();
if(obj is TypeYouWant)
    doSomething();

Good Luck


Redirecting from nested methods in Ruby on Rails

Question: Here is a code similar to one I have. What I need to do is to redirect from a nested method to other page and stop execution all actions it was called from. In this this case it's method2. It should redirect to '/home/index' and I need to prevent redirecting to '/home/index123'
    class MyController::ApplicationController

    def index
     #some work
      method1
     #some work  that must be done if there is no redirect
     #some work   that must be done if there is no redirect
      redirect_to '/home/index123'
    end

    private

    def method1
     #some work
     method2
     #some work that must be done if there is no redirect
     #some work  that must be done if there is no redirect
    end

    def method2
     #some work
     #I need to redirect to other page just from here!
     redirect_to '/home/index'
    end

end

Your ideas?
Answer: Make your redirection a variable.  Set this variable as the return value of your method.
For instance:
 def method2
   #some work
   #I need to redirect to other page just from here!
   '/home/index'
 end

def index
     #some work
      to_action = method1
      redirect_to to_action
    end

Comment: I have 2 private methods and it would be not good because I would have to check this variable in each method and in index.
Comment: didn't understand your concern
Comment: I updated index and method1. Look at them. The bottom line is, that I want to redirect right away, right here I would call it.
Comment: why would you want to repeat the redirect logic in three methods if you can do it in just one, as in my solution.  all you need to do is set redirects in one of your private methods and if that's nil set the to_action variable in your index action to the default url.  this solution is clean, avoids duplication of code, makes it easier to read.
Comment: You forgot that index has "#some work  that must be done if there is no redirect". So if there is a way to redirect this work must not be done.
Comment: that's what i said.  check if your private methods return anything, if not set the variable to the redirect url.  then you can use just one "redirect_to" statement to redirect to the appropriate url


R - Using for loop to conditionally change values in a dataframe

Question: All of the variables are on the same scale in the data.frame 1-5.
Example of data.frame
rpi_invert

A   B   C   D
5   2   4   1
3   5   5   2
1   1   3   4

For all values that equal 5 I would like to change it to 1.
for 4 change to 2.
for 2 change to 4.
for 1 change to 5.
Example of data.frame after values have been changed.
rpi_invert

A   B   C   D
1   4   2   5
3   1   1   4
5   5   3   2

What I have tired.
for(b in colnames(rpi_invert)){
  rpi_invert[[b]][rpi_invert[[b]] == 5] <- 1
  rpi_invert[[b]][rpi_invert[[b]] == 4] <- 2
  rpi_invert[[b]][rpi_invert[[b]] == 2] <- 4
  rpi_invert[[b]][rpi_invert[[b]] == 1] <- 5
}

This will only change the values in the first row and not the second column.
for(b in colnames(rpi_invert)){
rpi_invert <- ifelse(rpi_invert[[b]] == 5,1,
                     ifelse(rpi_invert[[b]] == 4,2,
                            ifelse(rpi_invert[[b]] == 2,4,
                                   ifelse(rpi_invert[[b]] == 1,5,rpi_invert[[b]]))))
}

But this gives me the error:
Error in rpi_invert[[b]] : subscript out of bounds

If I try to the same methods for an individual column instead of looping through the data.frame then both methods work so I am not sure what is the problem.
I am sure what I am trying to do can be done more efficiently without a for loop probably with some type of apply function but I am not sure how.
Any help will be appreciated please let me know if further information is needed.
Answer: You can try (if your data.frame is df):
3-(df-3)
#  A B C D
#1 1 4 2 5
#2 3 1 1 4
#3 5 5 3 2

or, same but written a bit differently: 6-df
Comment: That's really clever.
Comment: ahh that makes sense. Thank you for your answer and explanation.
Comment: @Cath That worked great! Your way is much more efficient. If possible do you understand why my for loops failed to do what I wanted them to do? If not I am sure I can do further research to better understand for loops.
Comment: @Dre, in your first for loop, you change the values `5` and `4` into `1` and `2` with the first 2 lines but then, you change `1`s and `2`s back into `5`s and `4`s with the last 2 lines so it cannot work. In  your second for loop, there are several problems, there are far too many embedded `ifelse`s but what causes the error is that you reassign your complete df at each "loop turn" instead of just column `rpi_invert[[b]]`


Probability theory books for self-study

Question: Are there any good books that explain important concepts of probability theory like probability distribution functions and cumulative distribution functions?
Please, avoid referring books like "Mathematical Statistics and Data Analysis" by John Rice which start with simple permutation concepts and then, suddenly (in 2nd chapter) take a leap assuming knowledge in real-analysis, multiple and surface integrals and begin describing CDFs and PDFs and illustrating them in 3-dimensional figures. One is left scratching head as to how everything is connected.
I am looking for self-study books and any book in the same category as "Calculus for the Practical Man" would be of great help.
Comment: Thanks for that response. If you are looking for something *like* Rice's text, but "better", my personal favorite is Mood, Graybill, and Boes, *Introduction to the theory of statistics*, 3rd ed., 1974. It has long been out of print and so can be expensive to get a hold of. It's also a bit more advanced book, even then some of it's more modern competitors like Casella & Berger. At any rate, I find the writing very clear; it moves at the right pace, generally, and has great examples and exercises. Using an elementary probability book like Ross's would probably be good as a supplement.
Comment: My point of asking is that you can learn a good amount of elementary probability theory with only a decent grasp of calculus. You can learn a decent amount of (classical) applied statistics without calculus as long as you are willing to accept many formulas without a tremendous amount of motivation. It's, unfortunately, pretty difficult to get *too* deep into statistical *theory* (as I understand that term) without the elementary probability theory and a greater familiarity with calculus.
Comment: What level of sophistication are you looking for? You mention Rice and *Calculus for the Practical Man*. You also mention "very simple" permutation concepts, so you must be comfortable with some math. When you say *statistical theory*, what do you mean? The examples you mention are more in the vein of elementary *probability* theory.
Comment: Thanks Cardinal. I understand that I cannot go much far in statistical theory without good knowledge in Calculus and I am not looking for a non-mathematical text here. The problem I find with Rice's book is that it takes a sudden leap and I am left wondering what should I have known or know to understand this material. On the other hand "Practical Man" slowly builds concepts from elementary blocks and occasionally reiterates them. The latter series has made visible to me the  relationships in Mathematics and I am left me wondering why I feared Calculus for so long.
Comment: If you are also interested in online lectures try https://www.coursera.org/course/probability or more "mathy": https://www.youtube.com/watch?v=KbB0FjPg0mw
Answer: I recommend Head First Statistics. The 'Head First' Series is of superior didactic quality and fun to read. It has a lot of exercises, and was one of the few books were I liked doing the exercises.
http://www.amazon.com/Head-First-Statistics-Dawn-Griffiths/dp/0596527586
Comment: Any book in this series causes so much distraction that for me it is no-go, no matter if it is math, programming or playing guitar. But, OP MMV.
Answer: I was looking for the same a week ago. I found from another post on stackexchange about this book Intuitive biostatistics: A Nonmathematical Guide to Statistical Thinking by Harvey Motulsky. I think the second part of the title is pretty lame. But generally I have/had no problems in understanding the math, but found none of them explaining concepts clear enough for me. I just ordered this book based on the reviews, so I can't give an opinion about it myself yet. There were good reviews on amazon and on stackexchange (although many preferred the 1st edition to 2nd). If you're looking for something totally different, this might interest you.
Comment: Highly recommended by me, too.
Answer: Schaeffer's book from Duxbury press seems ok.  Sheldon Ross' books are always awesome.  Note, these are both books on Probability, not stats, which is what you asked.
Answer: I'd strongly recommend Bulmer's Principles of Statistics as a leaping-off point.  It's a touch dated, but it's short, clear and available in a cheap Dover edition - around $10 from Amazon.  For a more modern and to the point statistical book I'd suggest Wasserman's "All of Statistics".  I got it a few months back and it's been a good survey of everything - I've not read the first few chapters in detail but it seems ok on a skim. I like some of the practical advice which would be useful in a self study context - e.g. "Unbiasdness used to receive much attention but these days is considered less important".
But this is assuming you want a practical statistics text which covers some probabilty rather than a probability theory text. For probability theory, I'd suggest reading a lot on measure theory and hit something on Lebegue integration first - but this doesn't sound like where you're at.
Comment: I used Wassermann's book to supplement the official one that every other instructor in a ten-section "Intro to Stats for Engineers" class was obliged to use, and liked it way better than the required textbook. It swoops through statistics at an amazing pace by omitting all the proofs, in the hope that a mathematically savvy student will either see through it, or consult more rigorous books.
Answer: https://www.crcpress.com/Introduction-to-Probability/Blitzstein-Hwang/p/book/9781466575578 - Introduction to Probability
I had no experience in probability before; this is a good book that explains the basic probability distributions with motivating context. Begins with discrete random variables and moves to continuous, which is good for the beginner. Builds your foundation up so you can tackle more advanced topics in the future.
Answer: Yes, I agree that the John Rice book is not good for self-study. It jumps around topics of varying difficulty, although it is obvious the author is a very experienced practitioner. For my level, it does more confusion than enlightenment.
I would highly recommend:

Dimitri Bertsekas
Sheldon Ross
Ron C. Mittelhammer
Richard Larsen

You can contact me if you want copies.

Probability theory books for self-study


Meteor autoform "afFieldValueIs" with a boolean checkbox only triggers once

Question: I have a checkbox that needs to show/hide another input box. I'm doing the following:
Schema:
isFlexibleTime:
   type: Boolean
   label: 'Is the start time flexible?'
flexibleTimeDetails:
   type: String
   label: 'Flexible time details'
   optional: true

Template:
+afQuickField(name='isFlexibleTime')

if afFieldValueIs name='isFlexibleTime' value=true
    +afQuickField(name='flexibleTimeDetails')

The helper will trigger one time and show the other field but it won't trigger again. Any help into what is wrong would be much appreciated.
Answer: EDIT
Actually on further inspection it seems there is currently a bug with the checkbox event as of AutoForm 5.1.2 https://github.com/aldeed/meteor-autoform/issues/861
The issue has been open a little while, so you can use a quick workaround like:
In your template event:
'click [name=isFlexibleTime]': function() {
    Session.set('isFlexibleTime', AutoForm.getFieldValue('isFlexibleTime','ID_OF_YOUR_AUTOFORM'));
}

Template helper:
isChecked: function() {
            return Session.get('isFlexibleTime');
}

then:
{{#if isChecked}}
         {{> afQuickField name="flexibleTimeDetails"}}
{{/if}}

I'm not sure if that's your actual syntax but following the example from: http://autoform.meteor.com/fieldvalues it should look like this:
 {{> afQuickField name="isFlexibleTime"}}
 {{#if afFieldValueIs name="isFlexibleTime" value="true"}}
      {{> afQuickField name="flexibleTimeDetails"}}
 {{/if}}

Comment: Thanks a ton @Jon. That is great to know. I will just monitor that PR and pull the fix once it is merged.


How to wire 1 humbucker to a 6 position rotary switch without tone and volume pots?

Question: Any help would be useful diagrams?
Comment: Well, what do you want that 6-pos switch to do?
Comment: Both in phase, both out of phase, one on, other on seem to be the 4 options.
Comment: to just be able to switch between all possible wiring of the pickup, like splitting it parrell etc. all possible ways with the rotary.
Comment: Sounds great to me, any diagrams?
Comment: There actually are six options: serial in phase, serial out of phase, parallel in phase, parallel out of phase, coil A alone, coil B alone. But it's probably not possible to get access to all of these. At any rate we'll need to know what this switch is you're talking about – there are plently of different models.
Comment: https://www.amazon.com/Allparts-EP-0920-000-6-position-Rotary-Switch/dp/B002HFKVYQ/ref=sr_1_1?ie=UTF8&qid=1519928880&sr=8-1&keywords=6+position+rotary+switch+guitar
Answer: With a full 4-pole switch, it's easy to figure out a routing – just assign each of the wires coming out of the PU a pole.
Then for each setting of the knob, you can freely decide where the signal should go. You'll definitely want the standard serial wiring (i.e. opposite coil polarities in series, so the opposite magnets will bring the signals in phase)

and probably also the brighter-sounding parallel variant with the same phase

Extend to other wirings as you see fit. Single-coil splitouts are the obvious third choice, followed by out-of phase arrangements. All of these are frankly much less useful though in practice – an out-of-phase humbucker sounds extremely weak/thin, which is particularly bad since, like a SC tap out, it doesn't actually humbuck anymore. So, a more practical alternative migh be to offer a whole bunch of variations on the serial circuit, with different capacitors to short out the high frequencies from one of the coils.

All of these woult be mostly hum-free, but in the crucial midrange the capacitor-shortened coil won't contribute much so it'll actually sound more like a single coil.


Given $f : A \rightarrow B \::\:\forall\: a_1, a_2 \in A,\:a_1 \leq a_2 \implies f(a_1) \leq f(a_2)$.

Question: Suppose that $A$ and $B$ are nonempty subsets of $\mathbb{R}$, and that $f : A \rightarrow B$ is a function satisfying $\forall\: a_1, a_2 \in A,\:a_1 \leq a_2 \implies f(a_1) \leq f(a_2)$.
(Such a function is said to be weakly increasing.) Furthermore, suppose that $f$ is surjective
(i) Prove that if $M$ is a largest element of $A$, then $f(M)$ is a largest element of $B$.
(ii) Why is the assumption that $f$ is surjective necessary? Give an example of nonempty subsets $A$ and $B$
of $\mathbb{R}$, a weakly increasing function $f : A \rightarrow B$, and a largest element $M$ of $A$ such that $f(M)$ is not a
largest element of $B$.
Comment: I've taken the liberty of making some formatting adjustments to your post, fixing the tags, and trying to make the title more helpful. I'm not certain what "a largest element" means. Do you mean "the greatest element," possibly? Also, your questions will be more likely to gain attention if you include your thoughts and efforts, to help us gauge your experience level.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.*
From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/). Welcome to Math.SE!
Answer: Counter-example in (ii):
Let $A=\{0\}$ and $B=\{0,1\}$. Define $f:A\rightarrow B$ by $f(0)=0$. Clearly, $A,B$ are non-empty subsets of $\mathbb{R}$ and $f$ is "weaking increasing". Moreover $0$ is the largest element of $A$. However, $f(0)=0$ is not the largest element of $B$.
//////////////////////////////////
To prove (i). Let $y\in B$. Since $f$ is surjective, there exists $x\in A$ such that $f(x)=y$. Now $x\leq M$, so $y=f(x)\leq f(M)$. This shows that $f(M)$ is the largest element in $B$.


Como fazer comparação de arrays?

Question: Estou com dificuldades de fazer esta questão:
Faça um programa que receba dez idades, pesos e alturas e que calcule e mostre:

A quantidade de pessoas com peso superior a 90 quilos e altura inferior a 1,50;
A percentagem de pessoas com idade entre 10 e 30 anos entre as pessoas que medem mais de 1,90;

Eu criei três input's para receber as informações (idade, peso e altura). No PHP elas são inseridas em um array através do explode, mas não consigo relacionar os arrays de peso e altura para responder ao primeiro ponto nem relacionar os arrays de idade e altura para responder o segundo ponto.
Código que tenho até agora:
<form action="" method="post">

    Idade
    <input type="text" name="idade">

    Peso
    <input type="text" name="peso">

    Altura
    <input type="text" name="altura">

    <input type="submit" name="enviar">
</form>

<?php

if(isset($_POST['enviar'])){

$cont = 0;
$soma = 0;
$media = 0;

$idades = explode(",", $_POST['idade']);
$pesos = explode(",", $_POST['peso']);
$alturas = explode(",", $_POST['altura']);

?>

Comment: Você já viu como ficam os arrays? Experimente ver que vai perceber como ficam associadas as informações.
Comment: Com `array_filter` você consegue remover do array elementos que não satisfazem certa condição.
Answer: Uma dica é você e trabalhar com os índices do array, pois pelo que entendi cada posição do array vai ser uma pessoa (posição 1 == pessoa 1) , por exemplo
for($i=0;$i<=10;$i++)
{
  if ($peso[i] > 90) && ($altura[i] < 1,50)
  {
   $count++;//se a pessoa tiver mais que 90kg **E** tiver menos que 1,50 de altura incrimento +1 no meu contador
  }
}

Comment: `$count = $count++;` é redundante, apenas `$count++;` é o suficiente
Comment: De fato , vou fazer esse alteração.
Obrigado pelo aviso.

Como fazer comparação de arrays?


How to get a resource integer ID from a string containing ID (like: R.string.*, R.drawable.*, etc.)?

Question: Recently I had an issue very similar to the one described i.e. here: Convert String containing an ID into an Integer-ID.
In short, I had resource identifiers formatted as: R.drawable.picture and wanted to transform them to integer values so that they could be stored in an array and accessed by methods building layouts of my application.
However, following the clues given by Users didn't help to solve my problem, I always ended up with improperly formatted data.
Answer: Looking for a solution, I came to the one described below.
Details:

strings containing resource IDs were kept in a database,
full addresses of resources were used to describe them (so, for example: R.drawable.chopin instead of simple chopin - sometimes you may forget what is actually hidden behind a resource: is it a picture or a string it points to? Keeping full identifiers doesn't let you forget about types of these),
resource IDs were fetched by a method as strings (also kept in the database as text values) and then parsed into integer identifiers.

Firstly, the context had to be defined:
public DBAdapter(Context context) {
   this.context = context;
   dbHelper = new dbHelper();
}

As I had the context, I could have parsed the strings:
int composerPicture = context.getResources().
        getIdentifier(composerPictureId.substring(11), "drawable",
        context.getPackageName());

and:
int composerName = context.getResources().
        getIdentifier(composerNameAddress.substring(9), "string",
        context.getPackageName());

Pay attention to the quantity of characters we cut off using substring() method. When the ID starts with R.drawable., we have 11 characters and this value has to be cut off. If there is R.string., then we cut off only 9 characters. This way we end up with a pure name of our resource (drawable or string, in this case). The methods assign ID and we have an integer. After that, we can store it in an ArrayList<Integer> or wherever else.
Comment: You could have simply used Reflection ;)


Remove Duplicate Items in Dictionary

Question: I'm trying to remove duplicate items in a list through a dictionary:
def RemoveDuplicates(list):
    d = dict()

    for i in xrange(0, len(list)):
        dict[list[i]] = 1       <------- error here

    return d.keys()

But it is raising me the following error:
TypeError: 'type' object does not support item assignment

What is the problem?
Comment: Variable names like `dict` and `list` are a Very Bad Idea.  Never call a variable `dict`, `list`, `tuple`, `int`, `float` or anything of the kind.  It makes it very hard to discern what you're talking about.  And it may make your program not work because your local variable name has replaced a built-in name.
Answer: You should have written:
d[list[i]] = 1

But why not do this?
def RemoveDuplicates(l):
    return list(set(l))

Also, don't use built-in function names as variable names. It can lead to confusing bugs.
Answer: In addition to what others have said, it is unpythonic to do this:
for i in xrange(0, len(lst)):
    do stuff with lst[i]

when you can do this instead:
for item in lst:
    do stuff with item

Answer: dict is the type, you mean d[list[i]] = 1.
Addition:  This points out the actual error in your code.  But the answers provided by others provide better way to achieve what you are aiming at.
Answer: def remove_duplicates(myList):
    return list (set(myList))

From looking at your code it seems that you are not bothered about the ordering of elements and concerned only about the uniqueness. In such a case, a set() could be a better data structure.
The problem in your code is just to use a function argument name which is not the name of the built-in type list and later on the type dict in the expression dict[list[i]].
Answer: Note that using list(set(seq)) will likely change the ordering of the remaining items.  If retaining their order is important, you need to make a copy of the list:
items = set()
copy = []
for item in seq:
    if not item in items:
        copy.add(item)
        items.append(item)
seq = copy

Remove Duplicate Items in Dictionary


Characteristic Polynomial Computation

Question: Let $A_{0}=k[x,y]$, $\mathfrak{m}=(x,y)$. Let $A=(A_{0})_{\mathfrak{m}}$. We wish to compute the characteristic polynomial, $\chi_{\mathfrak{q}}$, of the $\mathfrak{m}$-primary ideals (i) $(x,y)$, (ii) $(x,y^2)$, (iii) $(x,y)^2$ and finally check that the degrees of each polynomial are equal.
I am only really familiar with char. poly. in linear algebraic terms, i.e., Jordan canonical form computations. I read through Atiyah-Macdonald, but I did not find it terribly helpful in direct computation. How might I do this problem? Any help would be appreciated!
Answer: Well, it seems that $\chi_{\mathfrak q}(n)=l(A/\mathfrak q^n)$ for $n\gg0$.
In general, it is not an easy task to compute these lengths! That's why the theory reduces the finding of the degree from the general case to the most simple one when $\mathfrak q=\mathfrak m$. (However I won't exclude the possibility to perform such computation in your particular cases.) In your case this is easy to find since you know that $\mathfrak m^n/\mathfrak m^{n+1}$ is a $A/\mathfrak m\cong k$-vector space having a basis with $n+1$ elements, so $\chi_{\mathfrak m}(n)=n(n+1)/2$ is a polynomial of degree $2$ for $n\gg 0$. (But, of course, you know this from Krull-Chevalley-Samuel theorem which says that the degree of the characteristic polynomial equals the Krull dimension of $A$.)
Comment: Ah, we can also see that the Hilbert polynomials for the three ideals are equivalent. Namely, let $\mathfrak{m}=(x,y)$, $\mathfrak{g}=(x,y^2)$, $\mathfrak{h}=(x,y)^2$. Then we have $l(\mathfrak{g_{1}})=1$, $l(\mathfrak{g_{n}})=l(\mathfrak{m_{n}})$ for $n \geq 2$ and $l(\mathfrak{h_{1}})=0$, $l(\mathfrak{h_{2}})=2$, $l(\mathfrak{h_{n}})=l(\mathfrak{m_{n}})$ for $n \geq 3$. Then our ideals have the same Hilbert polynomial, i.e., $H(n)=n+1$ and the degrees of our char. polys. should be equal.

Characteristic Polynomial Computation


Rails Assets Pipeline load JavaScript from controllers and methods

Question: I want to stay DRY in my code so I want to auto-load my javascripts file when it matches a controller or/and a method and the .js exists. I added this to my layout
= javascript_include_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.js")
= javascript_include_tag "#{params[:controller]}/#{params[:action]}" if ::Rails.application.assets.find_asset("#{params[:controller]}/#{params[:action]}.js")

So now when I add javascripts/my_controller/my_method.js it automatically loads it, which's nice.
Sadly I must add another line to precompile the asset otherwise an error is thrown (which says I must precompile my .js file) and I didn't find any way around this.
Rails.application.config.assets.precompile += %w( orders/checkout.js )

Does anyone has a solution to avoid tu add manually elements in this configuration ?
NOTE : I already tried to use require_tree . which was just loading all the files on every page and was not working in my case.
Answer: You can use a wildcard to allow all JS files included in your views to be precompiled:
config.assets.precompile << '*.js'
Comment: You just made my day ;)


A função de embaralhamento tem armadilhas não facilmente percebidas?

Question: A função shuffle recebe como entrada uma array e a embaralha.

//
function shuffle(a) {
 // atribui a variável n a quantidades de elementos da array a.
 n = a.length;
 // Percorre a array a da posição 0 até a ultima posição.
 for (var i = 0; i < n; i++) {
 //Sorteia uma posição aleatória entre i e n−1 e atribui para a variável swap
 swap = i + Math.floor(Math.random() * (n - i - 1));
 // Troca os valores das posições i e swap da array a.
 var aux = a[i];
 a[i] = a[swap];
 a[swap] = aux;
 }
}
var array = [5, 3, 1, 4, 2];
if (shuffle(array)) console.log(array);

Existem potenciais armadilhas (pitfalls) na função acima? Se SIM qual é ou quais são? Comente a resposta.
Mandei executar e não deu resultado.
Comment: Qual é a sua dúvida em resposta ao exercício?
Comment: tentei executar e não consegui e não entendi o funcionamento da função
Comment: O seu if está impedindo de mostrar a saída. Tire o if e execute a função direto. Aí sim tente entender como funciona e quais podem ser as potenciais armadilhas.
Comment: @AlbertoVerzemiassiBorguesani A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: De forma geral não, em específico não podemos dizer porque não sabemos o que deseja, se ela resolve o que precisa.  Este algoritmo tem até nome, chama-se Fisher-Yates, e é o mais usado para embaralhar dados. Como ser visto em outra resposta (uma mais completa que leva à análise de alternativas).
A única coisa ruim na função é que ela não declara as variáveis localmente com var ou let (uma dela sim, então o código é estranho por estar inconsistente), não declarando assim a variável fica global e aí sim terá armadilhas complicadas de resolver. Se executar só isso não tem problema, se tiver outras partes de código essas variáveis podem se confundir com outras, pode até não dar problema aí mas criará problema nas outras partes, dependendo de como forem escritas.
A função em si está correta, a chamada dela está bem errada e não faz sentido. O if não tem função alguma aí e estám andando imprimir um objeto e não os elmentos do array que parece que é o que deseja.

function shuffle(a) {
    let n = a.length;
    for (let i = 0; i < n; i++) {
        let swap = i + Math.floor(Math.random() * (n - i - 1));
        let aux = a[i];
        a[i] = a[swap];
        a[swap] = aux;
    }
}

let array = [5, 3, 1, 4, 2];
shuffle(array);
for (let i = 0; i < array.length; i++) console.log(array[i]);

Coloquei no GitHub para referência futura.


Que comando posso utilizar para excluir um item de um repeater em c# asp.net

Question: Estou tentando realizar a exclusão de um item de um repeater, este item é uma pessoa "cadastrada". Porque não há um banco de dados envolvido
tenho conhecimento do Repeater1.Controls.Remove, porém este não exclui.
As informações como: nome, e-mail, cpf estão "registradas" em uma list.
Que outro comando posso utilizar??
Obs: não posso fazer uso de JavaScripit nesta página
Answer: Você pode colocar um if no repeater. Acredito que isso deva lhe ajudar.
Por exemplo o código aqui tem um if do currentItem.

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>

            <% if ( (CurrentItemCount % 2) == 0 ) { %?>

            <% } %>

                    Some data

            <% if ( (CurrentItemCount % 2) == 0 ) { %?>

            <% } %>
        </ItemTemplate>
    </asp:Repeater>

Pra vc buscar informações do item da lista vc pode usar a chamada direto para variavel.
Assim:
<asp:repeater runat="server">
<itemtemplate>
    <%# if ((bool) DataBinder.Eval(Container.DataItem, "IsEmpty")) { %>
       ALO
    <%#}%>
</itemtemplate>
</asp:repeater>

Mais info: https://forums.asp.net/t/1766065.aspx?if+statement+in+repeater+control
Comment: Muito obrigado!!
Comment: =) só dá o ok nas flechas alí. valews


How to make legend's line wider in a react-vis XYPlot

Question: The DiscreteColorLegends of an XYPlot are a little narrow for me:

Specially when I want to make them other than solid:

I browsed the documentation, and even the source code; I think that the length is determined in line 59 of this file: https://github.com/uber/react-vis/blob/master/packages/react-vis/src/legends/discrete-color-legend-item.js :
d="M 0, 1 L 14, 1"

Can I change it in my own local source code?
Answer: I found a 'semi' solution. I'm not proud of it, but maybe can help others. I did two things:

After compiling (with clojure -A:fig:min), I changed the string cited above using sed (28 doubled the size of the legend):

sed -i 's/"M 0, 1 L 14, 1"/"M 0, 1 L 28, 1"/' dev-main.js

Then, in the file legends.css, I changed this:

.rv-discrete-color-legend-item__title {
  margin-left: 10px;
}

into this:
.rv-discrete-color-legend-item__title {
  margin-left: 20px;
}

Now, al least, it looks better:


How to define the set of all ordered pairs whose first element coincides with $a'$?

Question: Let $A$ and $B$ be arbitrary sets with arbitrary elements $a\in A$ and $b\in B$. Then, define the Cartesian product $C=A\times B$, with arbitrary element $c=(a,b)\in A\times B$. Further, take some $a'\in A$.
My goal is to define the set of all ordered pairs whose first element coincides with $a'$: namely, the set $\{(a,b)\in A\times B:a=a'\}$. However, I have two problems.

First, I am not sure whether the set-builder expression $\{(a,b)\in A\times B:a=a'\}$ is the correct expression to denote the set of all ordered pairs whose first element coincides with $a'$.

Second, I need to start the definition with $\{c\in C:\dots\}$ rather than with $\{(a,b)\in A\times B:\dots\}$. I have thought of using the set-builder expression $\{c\in C:c_A=a'\}$, but I am not sure whether it is legit to use $c_A$ to denote the first element of the pair $c\in C$.

Thank you all for your help.
Comment: If $a'$ is fixed and pre-specified, then $\{(a,b)\in A\times B\mid a=a'\}$ makes perfect sense. So do $\{(a',b)\mid b\in B\}$, and $\{a'\}\times B$.
Answer: Most people would be happy with your expression $\{(a,b) \in A \times B\  \colon \ a=a'\}$ in most contexts.  When you want something more formal, perhaps in some contexts in axiomatic set theory, you could write something like
$$\{c \in C\  \colon \ \exists b \in B, (a', b) = c\}.$$
Comment: I don't see why $\{c \in C\  \colon \ \exists b \in B, (a', b) = c\}$ is more formal than $\{(a,b) \in A \times B\  \colon \ a=a'\}$. It looks like a step backwards to me. And $\{(a'b):b\in B\}$ is even better.
Comment: @Héctor, the first of those.  The quantifiers $\forall x$ and $\exists x$ are typically defined for variables $x$, not for general expressions.
Comment: @TonyK: $\{c \in C\ \colon \ \exists b \in B, (a', b) = c\}$ is more formal because, when $\{x \in A \ \colon \ P(x)\}$ is defined formally, it's typically defined just for atomic symbols $x$ assignable to variables.  If you're doing axiomatic set theory, that might matter to you.  If you're not, it probably won't.
Comment: Thank you for your comment. Suppose instead that $C=A\times B\times D$, with arbitrary element $c=(a,b,d)\in A\times B\times D$; and I wanted the set $\{(a,b,d)\in A\times B\times D:a=a'\}$. Would your expression be
\begin{gather}
\{c\in C:\exists b\in B,\exists d\in D,(a',b,d)=c\}
\end{gather}
or
\begin{gather}
\{c\in C:\exists (b,d)\in B\times D,(a',b,d)=c\}
\end{gather}
instead?

How to define the set of all ordered pairs whose first element coincides with $a’$?


How to understand the Response Time Graph of jmeter results?

Question: Please explain how this graph will respond the results:
Answer: In your graph:
X/horizontal is the time of the execution as 16:05:50
Y/Vertical is the response time of each request in miliseconds
Each color is a different Sampler, as PNM Profile View in yellow
For example PNM Profile View sampler sent return answer in 16:07:40 after ~30 seconds
Comment: Thanks for the reply @user7294900 . But i want to know how all sampler will respond. for example User Dashboard after Login in red at the top of the graph.
Comment: It had the biggest response time up to 90 seconds at the start of the test. This reflect what actually occurred in your test
Comment: Thanks a lot. @user7294900   it really helps me alot to understand. That means this interface takes max number of time to load.


try to install MySQL-python on Mac but keeping get errors

Question: I use python 2.7 on Mac 10.13
I already have MySQL on my Mac, but when I wanna install MySQL-python, keep getting error.
I tried pip:

sudo pip install mysql-python

but got:
<code> Collecting mysql-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 1.9MB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/tmp/pip-build-AhyoBa/mysql-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 53, in get_config
        libraries = [ dequote(i[2:]) for i in libs if i.startswith(compiler_flag("l")) ]
      File "setup_posix.py", line 8, in dequote
        if s[0] in "\"'" and s[0] == s[-1]:
    IndexError: string index out of range

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-AhyoBa/mysql-python/
</code>
Then I tried to move the file directly to 'site-package',and ran:
<code>python /Users/dandizhao/Downloads/MySQL-python-1.2.5/setup.py install
</code>
but still got:
<code> Traceback (most recent call last):
  File "/Users/dandizhao/Downloads/MySQL-python-1.2.5/setup.py", line 17, in <module>
    metadata, options = get_config()
  File "/Users/dandizhao/Downloads/MySQL-python-1.2.5/setup_posix.py", line 32, in get_config
    metadata, options = get_metadata_and_options()
  File "/Users/dandizhao/Downloads/MySQL-python-1.2.5/setup_common.py", line 12, in get_metadata_and_options
    metadata = dict(config.items('metadata'))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 642, in items
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'metadata'
</code>
Really exhausted...I tried many methods I can find, but none of them works...
Answer: I went on this link here and it seems like this is a very common issue with MySQL and MacOS.
Give these commands a try in your terminal

<code>$ brew uninstall mysql
$ brew install mysql-connector-c
$ brew unlink mysql-connector-c
$ brew install mysql
$ pip install mysql-python
</code>


jQuery Dropdown menu not displaying menu

Question: I'm trying to implement a Bootstrap dropdown menu with this code:

        Dropdown

Action

Another action

Something else here

Separated link

Looking at the Bootstrap docs, this is about the bare minimum needed for a dropdown menu, there is no other explanation provided in the docs. I have referenced Bootstrap and jQuery. I do not understand how this is supposed to work - and it doesn't in this current sample.
Well obviously it needs something to tell it to show the menu, but I haven't been able to find a straight answer on what reference and file does what for the Bootstrap dropdown menu.
Question: So does this thing use jQuery to work or what? I don't understand why or how it works even after I found a simple working demo here from this SO question stackoverflow.com/questions/14023115/dropdown-menu-not-showing-in-bootstrap.
I got it to work in this JSfiddle after importing Bootstrap.css and Bootstrap.min.js and Jquery 2. So it needs both Bootstrap.min.js AND Jquery to work? Huh? I'm just completely lost here. Thanks.
EDIT: Okay, found out that bootstrap.js needs to be loaded after jquery to work. But I still do not understand how the menu works. Does Bootstrap.js need Jquery?
Comment: You need to call it in javascript:
`$('.dropdown-toggle').dropdown()`
Comment: @niklas, Do I need to call it if I am just trying to click it to get it to drop down?
Comment: check their docs - http://getbootstrap.com/javascript/#dropdowns
you should call your dropdown, sry, I corrected the selector above, it should be attached to button
Comment: @niklaz, The doc says by Data Attribute (clicking due to the ``?) or by JS. If dropdown is to be triggered by the user's mouse click, should `.dropdown()` be called by an attached click handler to the dropdown button?
Answer: All js plugins in bootstrap uses jquery

Plugin dependencies
Some plugins and CSS components depend on other plugins. If you
  include plugins individually, make sure to check for these
  dependencies in the docs. Also note that all plugins depend on jQuery
  (this means jQuery must be included before the plugin files).

source: http://getbootstrap.com/javascript/
Comment: Okay, I missed that on the site, thanks.

When I look at event handlers for the dropdown link , they all reference the jquery.js file. I don't understand how bootstrap.js ever comes into play if it is never triggered.
Comment: bootstrap triggers the jquery plugins in the background.
Answer: The following post should help you.
Why doesn't this bootstrap dropdown example work?
You are gonna need both jquery and bootstrap referenced in the correct order and with html 5 doctype.


How do I interpolate a variable into a string?

Question: I have a username, "jerry" that I want to check if it's in my airtable's Username column:
username = 'jerry'
rows = at.get_all(formula="FIND('jerry', {Username})=1") # I want to replace the `jerry` there with the `username` var

How can I do this?
Answer: Python 3.6+ offers string interpolation with f-strings, which should be the preferred way of doing this.
So something like this should work:
username = 'jerry'
rows = at.get_all(formula=f"FIND('{username}', {{Username}})=1")

Notice the double curly braces to escape them in the string.
Comment: Be aware, though, that this assumes that `username` itself does not contain unescaped single quotes.
Answer: The easiest way in modern Python is to do:
foo = 12
bar = 'hello'
print(f"Giving {foo} {bar}'s")

Note the f in front of the string literal, making it a "f-string" where substitution will take place.
Answer: I believe if you put a .str in before the parentheses the variable is in could do something maybe.
---.str('words')
hope this helps.


Subtração direto na query de uma view?

Question: Tenho a view dbo.ViewExportItensNotasFiscais, tenho o campo NFValIcmsSubs, onde é necessário subtrair o valor do campo NFValFCP e manter o nome da coluna como NFValIcmsSubs
Como eu poderia fazer uma subtração direto da Query de uma View?
Answer: Utilizando Alias no SQL.
SELECT (NFValIcmsSubs - NFValFCP) as NFValIcmsSubs FROM TABELA

Answer: Especificamente para o seu caso a resposta do amigo Everson é a que atende a sua pergunta.
Porém o cliente MySQL pode efetuar também algumas operações com algum nível adicional de complexidade.
Exemplos:
SELECT (NFValIcmsSubs - NFValFCP)*2 as NFValIcmsSubs FROM TABELA

SELECT (NFValIcmsSubs - NFValFCP)*(FValIcmsSubs + NFValFCP) as NFValIcmsSubs FROM TABELA

Tal como nas operações de cálculo aritmético básicas, o MySQL também tem precedências entre operadores.
Assim, os operadores de multiplicação e de divisão são considerados antes dos operadores de adição e subtração.
Se dois operadores tiverem a mesma prioridade, a expressão é lida da esquerda para a direita.
Use os parênteses para forçar a priorização e para melhorar a legibilidade da expressão.

Subtração direto na query de uma view?


how to import nested JSON data into JavaScript

Question: I have a JSON file called ui-components.json that holds config data for user interface components used in a mobile app.  Here is a sample of data in the file:
{
  "picker": {
    "color": {
      "choices": ["brown", "black", "red", "green"],
      "defaultChoice": "red"
    },
    "size": {
      "choices": ["small", "medium", "large"],
      "defaultChoice": "medium"
    },
    "direction": {
      "choices": ["north", "south", "east", "west"],
      "defaultChoice": "west"
    }
  },
  "number": {
    "size": {
      "choices": ["1", "2", "3", "4", "5"],
      "defaultChoice": "5"
    },
  }
}

Currently, this data is being imported selectively, like so -
import { picker } from '../../config/ui-components';

While this works, a lot more data is being imported than necessary (more than shown in the sample above).  The file that's importing the config data only needs color so I tried the variations below but the editor indicated errors and sure enough, when an attempt was made to run the app, it threw errors.
// variations attempted
import { picker.color } from '../../config/ui-components';
import { picker.color as color } from '../../config/ui-components';
import { picker['color'] } from '../../config/ui-components';
import { picker['color'] as color } from '../../config/ui-components';

Is it possible to do this?  If so, what is the correct syntax?  If not, why not?
Comment: Sorry, I saw that you were working with a JSON object and my mind immediately went to destructuring assignment. The `import` syntax you're using is intended for importing named exports...I had no idea you could make it work on a file with no exports at all. Just out of curiosity, what environment are you doing this in? webpack? node? browser?
Comment: [MDN Nested object and array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring)
Comment: @knot22 When you use `import` with a JSON file, you embed the whole JSON file into the project.
Comment: Does `ui-components` have an export statement at the bottom?
Comment: @otw it does not.  `ui-components` is a .json file.  I am under the impression that export statements are only for .js files.
Comment: @David784 How does the `import` step fit into the approach of the link you provided?  Would the entire `picker` object still need to be imported?  ...I was hoping to avoid that.
Comment: You can't import parts of a JSON file separately. You could use `fetch` instead of `import`, that way you can at least discard the unused data after filtering out the part that you need.
Comment: @Kokodoko Why will it allow importation of `picker` from the .json file but not an element nested within `picker`?  If it allowed importing the top level elements, I wonder why it won't import nested elements.
Comment: @David784 I'm working with Vue Native which is a wrapper for React Native APIs.  It uses node modules and a bundler called Metro.
Comment: Even if that did work, syntactically, it would still have to load the entire module.
Answer: You can't import part of the json data but if the environment you use supports commonjs syntax  you can do something like this
let{
    picker:{
      color:colors
    }
  }=require("../../config/ui-components") //if the Json file extension is .json

  console.log(colors)

Comment: No the `:colors` is not necessary at all in fact you can access the variables like this `let{picker:{ color,size,...}}==require("....)` however if your object is deeply nested or complex, allocating variables will make the structure of the obj in your JS file cleaner and easy to read/ you can easily locate parts of your object that you need
Comment: If the `color` from the JSON file is to be put into a variable called `color` within the JavaScript it looks like `color: color` works and also just `color` (no semicolon or word after it).  Is the `: colors` part necessary only if the JS variable name is to be different from the JSON element name?
Comment: Everytime I see a tip like this, the code itself is unsurprising. This is immediately readable  and obvious as to how it works, yet somehow I couldn't see it before coming here. Works in create-react-app. Great tip, thanks.
Answer: So I am not aware of an environment where you can import JSON directly like that, so you might be using some tooling that is processing the files. Not sure if it would support anything like that but you can also just do this:
import { picker } from '../../config/ui-components';

const pickerColor = picker.color;

It's unlikely you'd get any performance advantage by doing it any earlier in the import, unless your tooling supports shaking JSON which I've never heard of.


My IBM X346 Series server is showing 5 HDD as DDD & only one HDD as Online....i have lot of files in HDD

Question: There were all red in HDD Lights .. when we reinsert the raid controller show only one HDD online  other 5 HDD showing DDD in Bios features///
Answer: You haven't actually posted a question. But I'll go out on a limb and suggest that the correct answer to your unasked question is "restore from backups." If you don't have recoverable backups, you should do a few things:

Contact IBM support to see if anything can be done
If not, contact a data recovery service to get a quote. Then, determine if the value of the data is more than the price of recovery.
Implement a recoverable (ie tested frequently) backup process. No one cares about backups, but you've just learned that people do indeed care about restores.


How would one go faster in Karting when they already hold the record?

Question: I do go karting as an hobby and I currently hold the track record at my local circuit. The average driver completes it in 37 to 38 seconds and my record is 33.13 seconds. The karts do a maximum of 40mph and I do an average of 34mph.
As I am obviously doing most things right, are there any advanced tips that a fast driver may not know? I am right on the limit and it is not possible to know that I have set the maximum possible time or not. My aim is to get a 32.9x or faster.
Since this is an arrive and drive, I do not have much competition when racing with other racers. I am more interested in tips to help me go faster in clean air when it is only myself on the track.
Answer: You may already be doing this anyway but the only real thing I can think of would be to ensure the kart is warmed up properly including the tyres, so try to do a few laps rather than just one or two.  Warm tyres give more grip so you can corner more quickly.  The other thing you can do is lose weight!
All you can do to know if a faster time is possible would be to try to take each corner slightly quicker until you begin to lose grip and slide or crash.  Sliding a kart is usually sub-optimal depending on the kart and the corner involved.
Once you know the exact limit for each corner and you are on that limit for every corner in the same lap you can assume that you have set pretty much the optimal time.  Of course if the track is outside the wind may play a small part in things, ie a tailwind down the main straight will be helpful, depending on the track characteristics etc.
Comment: Looks like that I probably need to find when the kart skids then. Some corners I do sometimes but not always. The warming of tyres are ok since I am out on track for ten minutes at a time. Also I think the weather plays a big part of setting fast times too. In the summer, I am about 0.5-1 second slower and in the autumn/winter that is the time I set the records


In a triangle, find the minimum and maximum of $\cos(A-B)\cos(B-C)\cos(C-A)$

Question: In a triangle, with $A, B, C$ are three angles, find the minimum and maximum of $$\cos(A-B)\cos(B-C)\cos(C-A)$$
Comment: multiplication of all cosinuses has absolute value less than one. So what you want to prove is completely wrong.
Comment: I'm guessing $A$, $B$, and $C$ are the three angles of the triangle. Right?
Comment: Think about $A = \pi/6, B = \pi/3, C = \pi/2$, the result is strictly less than 1.
Comment: Sorry, I just want to prove it greater than $\frac18$
Comment: You can rewrite one of those angles as $\pi$ minus the other two, then it becomes a minimization problem of two variables.  I would suggest [Lagrange Multiplier](https://en.wikipedia.org/wiki/Lagrange_multiplier) as a "brute force" way to solve it.
Comment: If $A = \epsilon$, $B = \dfrac{\pi}{3}-\epsilon$, and $C = \dfrac{2\pi}{3}$ where $\epsilon > 0$ is tiny, then $\cos(A-B)\cos(B-C)\cos(C-A)$ is slightly larger than $-\dfrac{1}{8}$. So proving that $\cos(A-B)\cos(B-C)\cos(C-A)$ is greater than $\dfrac{1}{8}$ isn't possible.
Answer: They are multiplication of cosinus of three angles which have sum of zero.
So:
$$\min(\cos(A-B)\cos(B-C)\cos(C-A))$$
Is the same as
$$\min(\cos(x)\cos(y)\cos(-x-y))$$
or in another form
$$\min(\cos(x)\cos(y)\cos(x+y))$$
Due to symmetric position of $x$ and $y$, the candidates for minimum must be at the boundaries ($\cos . =\pm1$) or where $x=y$
We can check them.
For when $x=y$:
$$A=\cos(x)\cos(y)\cos(x+y)=\cos^2(x)\cos(2x)$$
$$\frac{dA}{dx}=-\sin(2x)-\sin(4x)=0$$
$$\sin(2x)=-2\sin(2x)\cos(2x)$$
$$\sin(2x)(1+2\cos(2x))=0$$
if $\sin(2x)=0$ then $A=0$
if $\cos(2x)=\frac{-1}{2}$ then $A=\frac{-1}{8}$
So, the absolute mimimum is $\frac{-1}{8}$
Update
$\cos(2x)=\frac{-1}{2}$ means that
$$x=k \pi \pm \frac{\pi}{3}$$
if we set $x$ as $(A-B)$ and $y$ as $(B-C)$ then since $x=y$ then:
$$A-B=B-C=k \pi \pm \frac{\pi}{3}$$
And there is always a degree of a freedom.
If you add any equal value to all A, B, and C the result of the multiplication remains the same. So A, B and C can be any number as far as they satisfy the equation above.
Just an example can be $B=0$, $A=\frac{\pi}{3}$ and $C=\frac{-\pi}{3}$
$$cos(\frac{\pi}{3})\times \cos(\frac{\pi}{3}) \times \cos(\frac{-2\pi}{3})=\frac{-1}{8}$$
Fix
For angles in a triangle, we need to add additional condition:
$$A+B+C=\pi$$
After, I did all my bests, I found these angles cannot be placed in any triangle. It means in a trangle, due to the following contrains:
$$0<A<\pi$$
$$0<B<\pi$$
$$0<C<\pi$$
we would have $A>\frac{-1}{8}$ instead of $A\ge\frac{-1}{8}$. So we can approach very close to $\frac{-1}{8}$ but we can never achieve it in a real triangle.
According to suggestion of JimmyK4542:
$$A=\varepsilon, B=\frac{\pi}{3}, C=\frac{2\pi}{3}-\varepsilon$$
Where $\varepsilon$ is very close to zero causes the multiplication reach very close to $\frac{-1}{8}$ but $\varepsilon$ never touches zero in a real triangle. It just approaches it.
Maximum
The maximum is when all $\cos(.)$ are at their maximum which means all angles are equivalent.
Symmetry

Also, this answer still relies on the fact that the minimum of
    cosxcosycos(x+y) "must be at the boundaries (cos.=±1) or where x=y",
    which needs to be justified. The fact that cosxcosycos(x+y) is
   symmetric with respect to x and y isn't enough to justify this
JimmyK4542

I agree. It looks like an open discussion: link
Comment: For what angles $A,B,C$ is the absolute minimum $-\dfrac{1}{8}$ obtained?
Comment: The problem specified that $A,B,C$ be angles in a triangle. This means that $A,B,C > 0$ (strictly greater than) and $A+B+C = \pi$. Also, just because the function $\cos x \cos y \cos(x+y)$ is symmetric with respect to $x$ and $y$ does not mean that the minimum must be at the boundaries of the region or where $x = y$.
Comment: ^The maximum is trivially $1$, obtained when $A = B = C = \pi/3$
Comment: Fixed it. Thanks to Jimmy
Comment: Also, this answer still relies on the fact that the minimum of $\cos x \cos y \cos(x+y)$ "must be at the boundaries ($cos.=±1$) or where $x=y$", which needs to be justified. The fact that $\cos x \cos y \cos(x+y)$ is symmetric with respect to $x$ and $y$ isn't enough to justify this.
Comment: @JimmyK4542, I agree.
Answer: Let $A-B=x$ etc. $\implies x+y+z=0$
and $S=\cos x\cos y\cos z\iff2S=2\cos x\cos y\cos z=\cos x[\cos(y+z)+\cos(y-z)]$
$\implies2S=\cos x[\cos(-x)+\cos(y-z)]\iff \cos^2x+\cos x\cos(y-z)-2S=0$
which is a Quadratic Equation in $\cos x$
So, the discriminant $\cos^2(y-z)-4\cdot1(-2S)\ge0$
$\iff8S\ge-\cos^2(y-z)=\sin^2(y-z)-1\ge-1\implies S\ge?$
The equality occurs if $\sin^2(y-z)=0\iff\sin(y-z)=0$
Comment: @LzuTao, "Fix" in other answer should clarify your doubt


$x\mapsto \cos\left(\pi \| x\|\right)u+\sin(\pi \Vert x\Vert)\frac{x}{\Vert x\Vert}$ is surjective

Question:
I would like to prove that the map $f:B^n\to S^n$ given by $x\mapsto \cos(\pi \Vert x\Vert)u+\sin(\pi \Vert x\Vert)\frac{x}{\Vert x\Vert}$ is surjective? Where $u=(0,\cdots,1)$ and $B^n=\{x\in \Bbb{R}^n: \Vert x\Vert\le 1\}$ and $S^{n-1}=\{x\in \Bbb{R}^n: \Vert x\Vert= 1\}$.

Of course I look at $B^n=\{(x_1,\cdots,x_n,0):\sum x_i^2\le 1\}\subset \Bbb{R}^{n+1}$
The context is to prove that $B^n/S^{n-1}$ is homeomorphic to $B^n$.
After thinking a lot, I tried the following function. Everything is "fine", it's continuous and $f(S^{n-1})=\{-u\}$, so I get the result using some theorems.
But I forgot to prove that $f$ is actually surjective; not sure how can I do that.
Comment: @VikrantDesai I edited.
Comment: What is $B^n$ and $S^n$ ?
Answer: Guidance without explicit solution: Pick a point $z = (z_1, \ldots, z_{n+1}) \in \Bbb S^n \subset R^{n+1}$. Note that $-1 \le z_{n+1} \le 1$. Observe that you need $cos(\pi \| x \| ) = z_{n+1}$. That tells you what $\|x\|$ must be. (Why?)
Now look at $(z_1, \ldots, z_n)$; that points in the direction of $x$. Why? What's the angle between $u$ and $x$?
So scale $(z_1, \ldots, z_n)$ until it has the right norm, and you've found an appropriate $x$. What if $(z_1, \ldots, z_n)$ has norm 0 and cannot be scaled? Hmm. That's a special case you'll need to consider and understand.
(Note: you have to check that the norm is no more than $1$, and that the resulting $x$ really does map to $z$.)


Remove node_view rendered node's title link

Question: I am using the code below to add a form to my node. This renders a page with the node and form on it. Apparently, the node is rendered with its title as a link. I would like to have the node's title without a link. So I tried to change $node->content, but there seems to be no value that determines that the node title is a link. how do I change this with code?
$form = array();
$node = node_load(24)
$form['offer_form'] = array(
  '#value' => drupal_get_form('dt_offer_entry_form', $node),
  '#weight' => 10
);
$node->content = $form;
return node_view($node);

Comment: that title/link behavior is normally dealt with inside of your theme's `node.tpl.php` template.  Often it is based upon whether it is a full page view vs a teaser view.  Going in and creating a specific one just for this content type, eg, `node--TYPE.tpl.php` (D7) or `node-TYPE.tpl.php` (D6), might be the quickest way to deal with this.
Comment: You could also look at calling `node_view()` with different `$view_mode` (D7) or `$teaser`/`$page` (D6) arguments to coerce different behavior if your theme supports it.  http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_view/7 for more info
Comment: This worked for me:
    $node_view = node_view($node, FALSE, TRUE);
    return 'Voorstel indienen' . $node_view;
Answer: Quoting from this comment, this code worked for the OP.
$node_view = node_view($node, FALSE, TRUE);
return '
Voorstel indienen
' . $node_view;


Does a Context Condition Path need to exist?

Question: I have a context that has a condition Path of FooBar/*
I added a block (Reaction) view for that context.
When I go to /FooBar/Mens_Bible_Studies, the view shows, but I also get "Page not found"?
<code>Page not found

    Mens Bible Studies

    Overview of Mens Bible Studies. Delete if you don't want an overview
        Curabitur tortor - Meets every Wednesday, 6:30 am.

The requested page "/FooBar/Mens_Bible_Studies" could not be found.
</code>
What am I missing?
Rich
Update based upon the first two responses.
Thanks Boriana and rooby for answering! Here is a little more about what I am doing. At this point I am really not sure why I didn't use a page view. I am leaning to using contexts instead of panels. I want a responsive site and the theme handles that for me so I don't want to force a layout with panels. I want to select my block view based upon the "FooBar" root path.
I have a fairly large number of content types tagged with different taxonomy terms. I have a compound view that does all the work. It just looks at the last leaf of the URL (/FooBar/bla1/bla2/blanN... there is a variable depth) and uses that as the taxonomy term and builds a recursive output that descends the taxonomy tree in a way that I can CSS style each level differently. Content tagged as sub-category heading displays differently than content tagged with terminal terms (the lowest level in the branch of the taxonomy hierarchy they are in). I have heading content and then child content under that in the term hierarchy.
I thought I could just have the reaction point to the view and have it output. I will try both approaches you both suggested to see what works best. I believe I have to go with rooby's suggestion since I don't think I can have menu entries point to non-existent content. After I posted, I was thinking of just creating a panel page with empty variants that reacted to all the URLs I needed to create. Each of these would point to the same block view.
So Ideally, the new module I would need create (I never created a module before) would take a list of my hierarchical URLs, create phantom pages for them and create menu entries for them. My context would provide the content.
Or, perhaps I should just commandeer the taxonomy term views with what I want since the URLs that I want match the taxonomy term hierarchy.
Comment: So, you want the view without a page actually existing there in the first place?  Then why not make the view into a page view versus making it into a block that shows up *on* a page.  If you don't already have a page, just make a page view with that URL.  Or am I misunderstanding the issue?
Answer: Yes, the context module does not create pages, it allows you to position blocks on existing pages.
If you want a page that is not a node or a view you can use the empty page module or the panels module.
If you want a bunch of pages that are dynamic like FooBar/* where there are lots of sub pages, you could also create a custom module to create the pages, by using hook_menu() and returning an empty string for you page content.