Is this recursive GCD function correct?

Question: Everything compiles and runs perfectly for my program. I had to write a recursive GCD function. I used two functions however, gcdRecursive and gcd. Can I condense this code into a single function so I do not need the gcd function within my code below? Or is my code correct as it is and the two functions are both needed.
void gcdRecursive(int *x, int *y, int i){
  if (i >= 1) {
    if (*x % i == 0 && *y % i == 0) {
        printf("The GCD of %d and %d is %d", *x, *y, i);
    }
    else {
        gcdRecursive(x, y, i - 1);
    }
  }
}
void gcd(int *x, int *y){
  getValuesForGCD(x, y);
  gcdRecursive(x, y, *x);
}

Comment: You `gcd` function is a wrapper dedicated to interacting with the input environment: all the work happens in `gcdRecursive`. It is already unneeded for computing greatest common divisors. Programs generally need some kind of IO arrangements to be useful, of course, but that is separate of whatever computation you are doing.
Comment: Please stop doing spam edits just to bump your question.
Answer: Yes it is correct but it is by far sub-optimal.
EDIT: try to use this:
if (x > y)
  gcd(x,y) = gcd(y, x);
if (y % x == 0)
  gcd(x, y) = x;
else
  gcd(x, y) = gcd(x, y%x)

Comment: @QweRty You might try looking up the subject in [Wikipedia](http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm) before refusing advice…
Comment: You can compute gcd recursively in way less operations(computational-wise)
Comment: See my edit for an alternative solution
Comment: That will not work. It needs a third parameter as shown in my code above. Your code is sufficient but not workable code for my current code...
Answer: A more compact form could be
int getGcd(int num1, int num2)
{
    int remainder;

    if(num2 != 0)
        remainder = (num1 % num2);
    return ((num2 == 0) ? num1: getGcd(num2, remainder));
}

Is this recursive GCD function correct?


Are the intervals in the pentatonic scale all considered steps?

Question: When studying non-chord tones all the definitions use steps in the diatonic sense, but what about non-chord tones in pentatonic melodies? Are melodies written in pentatonic scales considered "steps"? Or are some of them still leaps?
Comment: It might be helpful to break "leaps" into two categories, "skips," which are thirds, and "leaps," which is anything bigger than a third.  A little context would help though - for what purpose are you calling them steps?
Comment: It depends on your definition of 'step'.
Comment: I write melodies using pentatonic scales and am learning about figuration in my harmony textbook which defines various non chord tones and I need to know how these relate to pentatonic melodies. Skips are not really a thing when learning about non chord tones. They are usually either labelled as "by step" or "by leap" when discussing how tones are resolved or approached
Comment: @nuggethead - where does the notion of skips and leaps come from - your own, or others' ideas?
Comment: @tim now you mention it, I don't know!
Answer: It's defined by context. If one is talking about the scale itself, then one tends to refer (colloquially) to the "steps" in the scale. However, if talking about the intervallic content, then one is likely to describe the larger-than-a-whole-step intervals as "skips".
The ideas of chord- and non-chord tones is one that doesn't really apply to pentatonic scales, at least not in the same way it does to diatonic scales. Neither the "building chords in thirds" nor the "every other scale tone" applies cleanly to pentatonic scales, so one can essentially adapt the concepts as is convenient to the scenario at hand.
In the pentatonic case, it's probably most convenient to think of notes in the scale and notes not in the scale, and make this synonymous with chord tones and non-chord tones. That will give a consistent definition regardless how one chooses to define/build chords within the scale.
For the purpose of ornamentation, then, it becomes a question of whether the ornaments stay within the scale (in which case some might involve the "skip"), or whether ornamentation can use notes outside the scale.
Comment: "If one is talking about the scale itself, then one refers to the "steps" in the scale": you could really go either way on this question.  There's certainly no standardized analytical framework for pentatonic scales that I'm aware of where an octave is said to comprise five steps, but this sentence tends to imply that there is.  It would certainly be confusing to combine such a framework with the diatonic-based terminology used to describe intervals in every other context.
Comment: @phoog I've edited to soften the language. Did not mean to imply there was a formal language for this.
Comment: Wiki (and others) seems to think it's more than 'colloquial'.
Comment: @Tim Link? Now that there's some disagreement, I guess it's time to cite some sources. So it would save me some time to know where you were looking.
Comment: @Aaron - Wiki's a start.
Comment: @Tim On what topic? Is there a specific entry for pentatonic chords? A link to what you've been reading would save me time.
Comment: Wiki, simply ref. steps/skips.
Answer: Steps are the intervals between two notes of, generally considered, diatonic scales. Thus they're either major 2nds or minor 2nds. Also referred to as conjunct motion, semitones being half steps, tones being whole steps. For example, in key C, D>E is a whole step, while E>F is a half step.
Any wider intervals than those are skips or leaps, also referred to as disjunct motion. Such as in the C pentatonic scale between E and G (m3). So, in the pentatonic scales (both major and minor) there are steps and skips.
Whatever scale is in consideration, those will be the intervals, so it doesn't really matter which scales are in discussion. All full major scales will only contain steps, while pents (and others, like harmonic minor) will contain both steps and skips. The fact that notes are non chord tones isn't a consideration. In a melody with consecutive notes of a semitone or a tone maximum, those are steps; anything larger are skips.
Comment: We'd have to decide on a specific definition of a step with regard to harmonic minor, though.  Is F to G# truly a skip as an augmented second?
Comment: @nuggethead - thought for the day! As it's still a second of some sort, rather than a third as found in harmonic minor, I'd argue that it's more likely a step. Maybe that's the criterion. I feel a question coming on...
Comment: "So, in the pentatonic scales (both major and minor) there are steps and skips." Says who?
Comment: @armani - on the premise that steps are semitones and tones, and skips are m3 and wider, why shouldn't that apply?
Comment: So it is the mathematical intervals that decide when something is a step or a skip not the distance from one tone of a scale to another? Is that what you are saying?
Comment: @armani - that's what my research so far has uncovered. Maybe call it the *intervals* themselves that designate. There's a difference between  the names of, say, aug2 and m3, although the sound is the same.
Comment: Hmm I don't know if I am ready to take your word for it just yet :)
Answer: Some of the 'steps' in a pentatonic scale, being wider than a 'whole step' (yes, the terminology overlaps, doesn't it!) do feel more like a 'leap'.
I suspect you're trying to apply 17th century rules of voice leading in a major/minor context to pentatonic music. This may not be very useful.
Comment: is there some other new syllabus on music theory that teaches voice leading that I am not aware of?
Comment: The 'rules' are about writing smooth 4-voice arrangements.  This wasn't always the aim, even in Bach's time!  Angular melodies, dramatic leaps are good too!  Know the principles of smooth voice-leading, do other stuff too!
Answer: It all depends. The concept of a step is usually tied to a very specific concept of harmony, so if you want to use to for other situation you need to generalize it. But if you define a step to be the interval between to adjacent scale notes you get a sort of inconsistency in your terminology and common terminology. In a pentatonic scale we expect to have two steps and then a jump.
More general a scale can be taken as subscale of another scale. Should the terminology then be consistent among these scales?


Como montar esse layout em Bootstrap 3

Question: Estou tentando montar o grid abaixo no Bootstrap 3.

Esse grid está sendo montado dentro de um laço for.
dessa forma estou usando o esquema do Grid System, porém eles ficam alinhados dessa forma:

Esse é o código:

                 21/11/2018

TITULO

AQUI O PAINEL AUMENTA OU DIMINUI CONFORME A QUANTIDAD DE TEXTO QUE VEM DO LAÇO FOR

                    <button type="button" class="btn btn-primary btn-xs">TESTES 1</button>
                    TESTES 2

Comment: É aconselhável fornecer o código que você está utilizando, fica mais fácil sugerir uma edição em cima dele se for necessário, ou mesmo usa-lo como base.
Comment: cara ussa um array bi dimencional
vc cria o primeiro array 4 colunas e dentro de cada coluna vc poe as suas divs dai quando vc for montar printa a primeira coluna com todas divs dentro dela depois a segunda terceira e quarta
Comment: Tá ai @CaiodePaulaSilva
Comment: Poderias expor um exemplo mais claro @Jasar Orion ?sou burrão
Comment: Cara é Bootstrap 3 ou 4? To vendo seu código e vc está usando classes dos dois ao mesmo tempo... isso não faz sentido...
Comment: É o boostrap 3. Desculpe esse mancada, meu forte é back-end. Mas você entendeu o problema.
Comment: já tem resposta, sim. mas totalmente fora do meu contexto, que é o bootstrap.
Answer: Usando o bootstrap 3, infelizmente, é impossível montar um layout igual ao que você deseja de acordo com a primeira imagem acima.
Sugiro que você use o seguinte plugin que assim você pode chegar nesse resultado.
https://masonry.desandro.com/
Comment: valeu. parece ser top. deve ter mais plugins desse tipo por ai. procurei por cascading grid, achei esse aqui também : http://mpezzi.github.io/bootstrap_isotope/
Comment: as vezes não sabemos o  termo certo para pesquisar esse tipo de coisa

Como montar esse layout em Bootstrap 3


Trocar cor de botão em tempo de execução

Question: Pedi ajuda sobre como pintar um botão com 3 cores diferentes:
É possível colocar 3 cores em um botão?
Porém estou tentando trocar a cor dele em tempo de execução e não consigo.
Mesmo instanciando um novo e substituindo.
A classe do botão é esta:
 class MultiColorButton extends JButton {
    Graphics g ;
    public MultiColorButton() {
        setContentAreaFilled(false);

    }
    @Override
    protected void paintComponent(Graphics g) {
        this.g = g;
          int fractionWitdh = 0;
            fractionWitdh = getWidth();
             g.setColor(Color.GRAY);
             g.fillRect(0, 0, fractionWitdh, getHeight());
        super.paintComponent(g);

    }

    void newcolor()
    {

         int fractionWitdh = getWidth()/3;

        g.setColor(new Color(63, 72, 204));
        g.fillRect(0, 0, fractionWitdh, getHeight());

        g.setColor(new Color(181, 230, 29));
        g.fillRect(fractionWitdh, 0, fractionWitdh, getHeight());

        g.setColor(new Color(237, 28, 36));
        g.fillRect(fractionWitdh * 2, 0, fractionWitdh, getHeight());
        super.repaint();
        super.paintComponent(g);

    }
}

o Método newcolor() seria para pintar o botão com novas cores.
Instancio o botão e o coloco em um vetor:
  Botoes[l][c] = new MultiColorButton();

Adiciono ele da seguinte forma:
 getContentPane().add(Botoes[l][c]);

Depois tento trocar sua Cor da seguinte forma,porém sem êxito.
           Botoes[i][c].newcolor();
           Botoes[i][c].repaint();

Não sei o que está faltando,pois esse é o meu primeiro contato com paint no java.
Answer:
Edit.: Otimizei a classe para que não fique limitada a apenas 3 cores, mas a quantidade que você achar necessário.

Basta criar um método  na classe MultiColorButton que receba o array de cores(ou as 3 cores individuais), atribui-las a um array de cores e forçar o repaint() do botão logo após atribuir as cores no array:
class MultiColorButton extends JButton {

    private static final long serialVersionUID = 1L;
    Color[] colors;

    public MultiColorButton() {
        this(new Color[] { new Color(63, 72, 204), new Color(181, 230, 29), new Color(237, 28, 36) });
    }

    public MultiColorButton(Color[] colors) {
        setContentAreaFilled(false);
        setFocusPainted(false);
        this.setColors(colors);
    }

    public void setColors(Color[] colors) {
        this.colors = colors;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {

        int colorsCount = colors.length;

        if (colorsCount > 0) {

            int fractionWitdh = getWidth() / colorsCount;

            for (int i = 0; i < colorsCount; i++) {
                g.setColor(colors[i]);
                g.fillRect(fractionWitdh * i, 0, fractionWitdh, getHeight());
            }
        }

        super.paintComponent(g);
    }
}

Para ilustrar a forma de uso, fiz esse exemplo que gera cores randômicas para o botão, cada vez que ele é clicado:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.multi.MultiRootPaneUI;
import javax.swing.JButton;
import java.awt.Dimension;

public class JButtonMultipleColorsTest extends JFrame {

    private JPanel contentPane;
    private JPanel panel;
    private MultiColorButton multiColorButton;
    private GradientButton gradientButton;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JButtonMultipleColorsTest frame = new JButtonMultipleColorsTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public JButtonMultipleColorsTest() {
        initComponents();
        pack();
        setLocationRelativeTo(null);
    }

    private void initComponents() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300, 200));
        this.contentPane = new JPanel();
        this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(this.contentPane);

        this.panel = new JPanel();
        this.contentPane.add(this.panel, BorderLayout.CENTER);

        this.multiColorButton = new MultiColorButton();
        this.multiColorButton.addActionListener(e -> {

            Random rand =  new Random();

            Color[] colors =  new Color[3];

            for(int i = 0; i < colors.length; i++)
                colors[i] = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));

            multiColorButton.setColors(colors);
        });
        this.multiColorButton.setText("multicolor btn");
        this.panel.add(this.multiColorButton);
    }
    class MultiColorButton extends JButton implements iColorsButton {

        private static final long serialVersionUID = 1L;
        Color[] colors;

        public MultiColorButton() {
            this(new Color[] { new Color(63, 72, 204), new Color(181, 230, 29), new Color(237, 28, 36) });
        }

        public MultiColorButton(Color[] colors) {
            setContentAreaFilled(false);
            setFocusPainted(false);
            this.setColors(colors);
        }

        public void setColors(Color[] colors) {
            this.colors = colors;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {

            if (colors != null &&  colors.length > 0) {

                int colorsCount = colors.length;
                int fractionWitdh = getWidth() / colorsCount;

                for (int i = 0; i < colorsCount; i++) {
                    g.setColor(colors[i]);
                    g.fillRect(fractionWitdh * i, 0, fractionWitdh, getHeight());
                }
            }
            super.paintComponent(g);
        }
    }
}

Veja funcionando:
Comment: Agora vi Onde errei,Obrigado pela atenção e pelo código bem didático !


Running aide --check as a crontab job once a week

Question: I'm having real problems getting a simple (aide --check) job to run as a crontab job. I've tried everything I can think of but it won't seem to run. I've tried specifying the shell in crontab:
SHELL=/bin/bash

I've tried all kinds of variations of the command line:
*/1 * * * * root /bin/bash /usr/sbin/aide --check
*/1 * * * * /bin/bash /usr/sbin/aide --check
*/1 * * * * root /usr/sbin/aide --check
*/1 * * * * root /bin/bash /usr/sbin/aide --check >> /var/log/SystemFileCheck.log

Plus others but just can't get it to run.  I've followed online guides which all say I'm doing it correctly. I've tried putting it into a bash script instead and running that but no luck. What am I doing wrong?
These are some of the errors I'm getting:
Mar 30 11:25:01 localhost CROND[14060]: (root) CMD (root /bin/bash /usr/sbin/aide --check >> /var/log/SystemFileCheck.log)
Mar 30 11:25:01 localhost CROND[14058]: (root) CMDOUT (/bin/sh: root: command not found)
Mar 30 11:28:01 localhost CROND[14397]: (root) CMD (root /bin/SystemIntegCheck.sh >> /var/log/SystemFileCheck.log)
Mar 30 11:28:01 localhost CROND[14395]: (root) CMDOUT (/bin/bash: root: command not found)
Mar 30 11:39:01 localhost CROND[16094]: (root) CMD (/bin/bash /usr/sbin/aide --check)
Mar 30 11:39:01 localhost CROND[16092]: (root) CMDOUT (/usr/sbin/aide: /usr/sbin/aide: cannot execute binary file)
Can anyone shed some light on this?
Thanks in advance
PS. the once a minute is just for testing
Answer: A user id can only be specified in the system crontab file. The entries of a user's crontab file don't take a user id. The entries in question are apparently found in a user's crontab file, which is why you get root: command not found from the first, third and fourth entries.
From the second, you get cannot execute binary file because you ask bash to execute /usr/sbin/aide as a bash script when it's not a bash script. You should be using
*/1 * * * * /usr/sbin/aide --check

Comment: Thanks, I solved the issue with your help. First off I was editing the user crontab when actually I should have been editing the system crontab.  I did get the user one to work but when I swapped back to the system one it still does what I need.  Thanks so much for your help.  Just need to also send the output to a second location now.
Comment: `*/1 * * * * /usr/sbin/aide --check >> /var/log/SystemFileCheck.log` should work just fine. You don't even need to set the `SHELL`  var because the command is a perfectly valid command for the default shell (`/bin/sh`)


FragmentPagerAdapter getItem() method to start at a different position

Question: I'm making a very simple app using the ViewPager. I would like to be able to start at a custom position when the getItem method is called. Below is my current code.
<code>@Override
public Fragment getItem(int position) {

    switch (position) {
    case 0:
        Fragment fragment1 = new Fragment1();
        return fragment1;
    case 1:
        Fragment fragment2 = new Fragment2();
        return fragment2;
    case 2:
        Fragment fragment3 = new Fragment3();
        return fragment3;

    default:
        return null;
    }
</code>
I was wondering how it would be possible to start at position 1 instead of 0 when the getItem method is called and then to be able to swipe to position 0 or 2 from position 1.
Answer: Why don't you simply set selected item to 1 after setting adapter?
<code>mPager.setCurrentItem(1);
</code>


Group by with 3 columns

Question: I have 3 columns to get data.
1- amount, 2- transaction_id and order_id
Made group by (transaction_id),  sum(amount) and get all order_id.
id  order_id    transaction_id   amount
1   1           3333             698.00
1   2           3333             758.00
1   3           3333             560.00
1   4           3333             360.00
1   5           5555             225.00
1   6           5555             102.00
1   7           2222              36.00

See image
TABLE
SELECT sum(amount) as sum, transaction_id, order_id FROM table WHERE ID='1' GROUP BY transaction_id
Got back:
The sum is OK.
The transaction id is OK.
The order id got back just the first of each transaction id.
I what to see order id like this transaction id 3333 - order id 1,2,3,4
Tried explode() but did not work
Help needed.
Answer: Assuming the db is mysql (please tag your db in the question), use group_concat for this like:
SELECT sum(amouNt) as sum, transaction_id, group_concat(order_id) orders FROM table WHERE ID='1' GROUP BY transaction_id
This will return orders column with comma separated values like 1,2,3,4
Comment: @jmart glad to help you. If the answer worked for you, please mark it as correct :)
Comment: Thanks, GAGANSHERA!!!!  First time using stack and response was fast thanks again!!!!
Comment: You'll see a tick mark icon below the upvote/downvote buttons. That's the mark as accepted button.

Group by with 3 columns


How to add to score after a turtle dies

Question: So my go procedure right now is
to Go
  ask turtles with [is-moving?]

  [
    if any? other turtles-here [
      ask other turtles-here [
        die
      ]
    ]
  ]
end

(is-moving? is just a turtles-own variable to specify the only turtle that i want to move)
I wanted to add 5 points to the score everytime it went through the go procedure and a turtle died.  I already set a global variable to score.  Thanks!
Comment: Try formatting your code with four spaces before each line of code.  It is almost impossible to read as it is.
Comment: Why do turtles got to die man?
Answer: If  score is global variable just add set score Score + 5
to Go
  ask turtles with [is-moving?]

  [
    if any? other turtles-here [

      ask other turtles-here [
 set score Score + 5
        die

      ]
    ]
  ]
end

Update:
I think you dont need to multiply it since all turtles will update the score value ! (my mistake! )To monitor Score :
Comment: ohhh , ok I will check it but you can try adding set score Score + 5   just one line before die!
Comment: what should I write under reporter when I add the monitor button?
Comment: If you mean you want to see Score in monitor just add a new monitor to interface and write the variable name (Score) in that monitor
Comment: For some reason the scores not adding on... I did exactly as said
Comment: okay, sorry to bother again but how do you set the ticks to time how long it takes to get through the maze?
Comment: you can use a turtle-own [movement-count] and whenver turtle makes a move increase the movement-count by 1
Comment: by How long do you mean real time or steps?
Comment: um I'm trying to do steps
Comment: If its steps you can follow http://stackoverflow.com/questions/21082953/how-do-i-create-a-timer-on-netlogo
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45329/discussion-between-marzy-and-user3188146)

How to add to score after a turtle dies


How to insert a row with autoincrement id in a multi-primary-key table?

Question: I am writing a turbogears2 application. I have a table like this:
class Order(DeclarativeBase):
    __tablename__ = 'order'

    # id of order
    id = Column(Integer, autoincrement=True, primary_key=True)

    # buyer's id
    buyer_id = Column(Integer, ForeignKey('user.user_id',
        onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)

I want to insert a new row into this table, but I got a "Field 'order_id' doesn't have a default value" error. It seems that I have to set the id of order manually, because I got two primary-key. My question is, how can I insert a row that generate new ID automatically?
If I generate id manually, I got some problem. For example:
maxId = DBSession.query(func.max(Order)).one()[0]
newOrder = Order(id=maxId + 1, buyer_id=xxx)
DBSession.add(newOrder)

Add a new order in this way seems ok, but however, we got some problem if two request run these code in almost same time.
If there is request a and b run this code in following order:
a.maxId = DBSession.query(func.max(Order)).one()[0]
b.maxId = DBSession.query(func.max(Order)).one()[0]
b.newOrder = Order(id=maxId + 1, buyer_id=xxx)
b.DBSession.add(newOrder)
a.newOrder = Order(id=maxId + 1, buyer_id=xxx)
a.DBSession.add(newOrder)

Then the request a might failed, because there is already an order with same id in table. I can catch the exception and try again. But I am wondering, is there any better way to do?
Sometimes, the id is not simple integer, we might need order id like this:
2009090133 standards for 33rd order at 2009-09-01
In these case, autoincrement is not usable. So I have no choice, manualy assign id for order. So my another question is, is there any better way than catch exception and retry to insert a row with id.
Answer: If you want sequential numbers per buyer for your orders then you'll have to serialize the transactions inserting to one buyer. You can do that by acquiring exclusive lock on the buyer row:
sess.query(Buyer.id).with_lockmode('update').get(xxx)
order_id = sess.query(func.max(Order.id)+1).filter_by(buyer_id=xxx).scalar() or 1
sess.add(Order(id=order_id, buyer_id=xxx))

Using this pattern when two transactions try to insert order for one buyer in parallel one of them will block on the first line until the other transaction completes or fails.
Answer: You should be using a default on your column definitions
id = Column(Integer, default = sqlexpression)

Where sqlexpression can be a sql expression. Here is the documentation.  For autoincrement you should use the sql expression coalesce(select max(order.id) from order,0) + 1.  For ease you could import sqlalchemy.sql.text so the id column could look something like
id = Column(Integer, default = text("coalesce(select max(order.id) from order,0) + 1"))


gerar consulta dinamicamente com union

Question: $sql = 'SELECT COUNT(*) FROM ';
$cola = ' UNION '; // Deixar os espaços em branco "em volta".
$colaWhere = ' WHERE ';
$first = true;

$wheres = "";

foreach($arrayNomeBDs as $nomeBD){
    $where = ' status = 2'. ' AND nomePessoa="O aqui vai variar" ';
    if($first == true){
        $wheres .= $sql . $nomeBD .$colaWhere . $where. $cola;
        $first = false;

    } else {
        $wheres .= $sql . $nomeBD .$colaWhere . $where. $cola;
    }
}

Ele está gerando assim:
SELECT COUNT(*) FROM tab1 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT(*) FROM tab2 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT(*) FROM tab3 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION
como eu removo o último union? que dica de implementação vocês poderiam me dar?
uma boa maneira é verificar o ultimo índice do array, se for eu não coloco o UNION? a mesma coisa se só tiver um nome do banco de dados na array, eu devo tirar o UNION
Answer: Você pode utilizar a função rtrim(), além dessa existe a ltrim() e trim() que servem pra remover espaços (se não especificado parâmetro) ou um texto especificado no parâmetro. No caso do rtrim será apenas no lado direito, enquanto ltrim é apenas no lado esquerdo e trim ambos os lados. Exemplo:
$sql = 'SELECT COUNT(*) FROM tab1 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT(*) FROM tab2 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT(*) FROM tab3 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION';
$sql = rtrim($sql, "UNION");

Saída:

SELECT COUNT() FROM tab1 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT() FROM tab2 WHERE status = 2 AND nomePessoa="O aqui vai variar" UNION SELECT COUNT(*) FROM tab3 WHERE status = 2 AND nomePessoa="O aqui vai variar"

IdeOne Exemplo
Answer: Acredito que colocar cada consulta montada em um array e, em seguida, utilizar a função implode seria também uma forma de unir suas consultas.
    $wheres[] = 'SELECT * FROM x';
    $wheres[] = 'SELECT * FROM y';
    $wheres[] = 'SELECT * FROM z';

    $wheres_compiled = implode(' UNION ', $wheres);

    var_dump($wheres_compiled); // SELECT * FROM x UNION SELECT * FROM y UNION SELECT * FROM z

Exemplo IDEONE
Imagino que, no seu caso, o resultado desejado seja algo como abaixo:
$tables = ['table_1', 'table_2', 'table_3'];

$wheres = [];

foreach ($tables as $table) {

    $wheres[] = sprintf('SELECT * FROM %s WHERE nomePessoa="%s"', $table, 'Aqui vai variar');
}

$compiled_with_unions = implode(' UNION ', $wheres);

gerar consulta dinamicamente com union


ACE editor adding special characters

Question: The use case is to display server logs in the UI built using Angular9.
I am using ACE editor to display text content received from server upon a http call and the server responds with recent 1000 lines of logs
To verify the content i did console.log() to view the text content in the chrome dev tool.
Console output received from server
While loading the same content to editor I notice special characters
Ace editor content while using in text mode
Attached 2 screenshot to compare
HTML Content

Typescript
import { Component, ViewChild, ElementRef, Input, SimpleChanges } from '@angular/core';

import * as ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/ext-beautify';

const THEME = 'ace/theme/github';
const LANG = 'ace/mode/text';

@Component({
  selector: 'app-text-editor',
  templateUrl: './text-editor.component.html',
  styleUrls: ['./text-editor.component.css']
})
export class TextEditorComponent {
  @ViewChild('codeEditor') codeEditorElmRef: ElementRef;
  private codeEditor: ace.Ace.Editor;

  @Input() textObject;
  @Input() readMode;

  data: any;
  mode: any;

  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    for (const properties of Object.keys(changes)) {
      if (properties == 'textObject') {
        const currentJSONObject = changes[properties];
        if (currentJSONObject.currentValue && currentJSONObject.firstChange == false)
          this.codeEditor.setValue(currentJSONObject.currentValue, -1);
        else
          this.data = currentJSONObject.currentValue
      }
      if (properties == 'readMode') {
        const currentReadMode = changes[properties];
        if (currentReadMode.firstChange == false)
          this.codeEditor.setReadOnly(currentReadMode.currentValue);
        else
          this.mode = currentReadMode.currentValue
      }
    }
  }

  ngAfterViewInit() {
    const element = this.codeEditorElmRef.nativeElement;
    const editorOptions: Partial<ace.Ace.EditorOptions> = {
      highlightActiveLine: true,
      displayIndentGuides: true,
      highlightSelectedWord: true,
    };
    this.codeEditor = ace.edit(element, editorOptions);
    this.codeEditor.setTheme(THEME);
    this.codeEditor.getSession().setMode(LANG);
    this.codeEditor.setShowFoldWidgets(true);
    this.codeEditor.setHighlightActiveLine(true);
    this.codeEditor.setShowPrintMargin(false);
    this.codeEditor.setReadOnly(this.readMode);
    this.codeEditor.navigateFileEnd();
    if (this.data)
      this.codeEditor.setValue(this.data, - 1);
    if (this.mode)
      this.codeEditor.setReadOnly(this.mode);
  }
}

Comment: Hi Sameer, welcome to Stack overflow. Could you please elaborate your question
Comment: @Harshapps thanks Harsha, I have updated the question and described the problem statement. Could you please help me to identify whether I missing any ace editor **property** ?
Answer: This are not characters added by ace, but color control characters sent by the terminal. If you do not want to display colors, and only want the text use the following function
var CSIRegexp;
function getCSIRegexp() {
  if (CSIRegexp) return CSIRegexp;
  // http://www.inwap.com/pdp10/ansicode.txt

  var classes = {
    C0              :  "\\x00-\\x1F", //
    SPACE           :  "\\x20\\xA0" , // Always and everywhere a blank space
    G0              :  "\\x21-\\x7E", //
    Intermediate    :  "\\x20-\\x2F", //  !"#$%&'()*+,-./
    Parameters      :  "\\x30-\\x3F", // 0123456789:;<=>?
    Uppercase       :  "\\x40-\\x5F", // @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
    Lowercase       :  "\\x60-\\x7E", // `abcdefghijlkmnopqrstuvwxyz{|}~
    Alphabetic      :  "\\x40-\\x7E", // (all of upper and lower case)
    Delete          :  "\\x7F"      , // Always and everywhere ignored
    C1              :  "\\x80-\\x9F", // 32 additional control characters
    G1              :  "\\xA1-\\xFE", // 94 additional displayable characters
    Special         :  "\\xA0\\xFF" , // Same as SPACE and DELETE
    ESC             :  "\\x1b"      , //
    Ignore          :  "\\x7F\\x00-\\x1F\\x80-\\x9F" // Delete|C0|C1
  };

  var g = /:ESC:(\[:Parameters:*:Intermediate:?:Alphabetic:?|:Intermediate:+:Parameters:|:Parameters:|:Lowercase:|)|[:Ignore:]/;

  var inBrackets = false;
  var source = g.source.replace(/(\\.)|([\[\]])|:(\w*):/g, function(_, esc, b, cls) {
    if (esc) return esc;
    if (b) {
      inBrackets = b == "[";
      return b;
    }
    if (!cls) return ":";
    var r = classes[cls];
    if (!/ESC|Delete|C0|C1/.test(cls)) {
      r += classes.Ignore;
    }
    if (!inBrackets && cls != "ESC")
      r = "[" + r + "]";
    return r;
  });

  return CSIRegexp = new RegExp(source, "g");
}

to remove control character before setting data to the editor
 this.codeEditor.setValue(this.data.replace(getCSIRegexp(), ""), - 1);

You can test it with the following call:
"\x1b[1mreal text\x1b[10m".replace(getCSIRegexp(), "")

Comment: this solution worked but now the text content is being displayed in single line, do this regex eliminates \n character? Workaround I did is replaced the \n with ~ and vise versa - this.codeEditor.setValue(this.data.replace(/\n/g, '~').replace(getCSIRegexp(), "").replace(/~/g, '\n'), 1);

ACE editor adding special characters


Failed asserting that two strings are equal in a patch

Question: I have submit a patch on community but I am getting an error in result that Failed asserting that two strings are equal.
This is the patch.
<code>
index 31bf064..fa079cc 100644
--- a/advagg_css_minify/yui/CSSMin.inc
+++ b/advagg_css_minify/yui/CSSMin.inc
@@ -422,7 +422,10 @@ class CSSmin

         // restore preserved comments and strings in reverse order
         for ($i = count($this->preserved_tokens) - 1; $i >= 0; $i--) {
-            $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
+            $preserved_tokens = $this->preserved_tokens[$i];
+            $preserved_tokens = htmlspecialchars($preserved_tokens);
+            $pt_replacepattern =  preg_replace('[^A-Za-z0-9@*.#:/ \-]', '',$preserved_tokens);
+            $css = preg_replace('/' . self::TOKEN . $i . '___/', $pt_replacepattern, $css, 1);
         }

         // Trim the final string (for any leading or trailing white spaces)
@@ -582,7 +585,10 @@ class CSSmin
         // one, maybe more? put'em back then
         if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
             for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
-                $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
+                $comment = $this->comments[$i];
+                $comment = htmlspecialchars($comment);
+                $replacepattern =  preg_replace('/[^A-Za-z0-9@*. \-]/', '',$comment);
+                $match = preg_replace('/' . self::COMMENT . $i . '___/', $replacepattern, $match, 1);
             }
         }
</code>
Comment: I formatted the patch for legibility. Also, here's the link to the actual test failure: https://www.drupal.org/pift-ci-job/1711396
Comment: And the relative issue is https://www.drupal.org/project/advagg/issues/3138865.
Answer: It looks like the problem might have to do with HTML escape sequences for quotes, ampersands and other meta-characters (at least in part).
Compare these lines:
<code>-  content: '/* \" \' */';\n
+  content: '/* quot  */';\n
</code>
and these:
<code>-}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon & escaped double \" quotes \"."}q:after{content:' (brackets & escaped single \' quotes \') '}q:after{content:"I'm Quote"}'
+}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon & escaped double \" quotes \"."}q:after{content:' (brackets & escaped single \' quotes \') '}q:after{content:"I'm Quote"}'
</code>
Hopefully that sets you on the right path. Don't just look at your diff, look at the PHPUnit test to see exactly what test you are failing. Good luck!
Comment: Does that mean that adding those calls to `htmlspecialchars()` causes the tests to fail?
Comment: That's my hunch but I can't really tell without running the tests myself to see where they are actually failing.


Sigma Algebra of Events for Uncountable Sample Space

Question: If $\Omega$ is an uncountable sample space, why are we not allowed to take the sigma-algebra of events $\cal{F}$ to be the power set of $\Omega$?
The Wikipedia page devoted to Probability spaces
 states that this power set may be too large so that there may be events for which it is impossible to assign a unique probability measure.
(1) Why can't we assign probabilities to all of the events?
(2) Can't we just set most of the probabilities to be $0$ and deal with the probabilities that we can assign?
Comment: You are correct. For example, choose $\omega \in \Omega$. For every $A \in 2^{\Omega}$, let $P(A)=1$ if $\omega \in A$ and $P(A) = 0$ if $\omega \notin A$. This is a probability defined over $2^\Omega$. The problem is defining a probability over $2^\Omega$ with an uncountable support.
Answer: The problem is not that you can not define a measure on power set of $\Omega$ (example by madprob above shows that you can), but that measures you can define can't have some nice properties you might need.
For example, to model "picking a random number from an interval $[0,1]$", you might need a measure $\mu$ such that

$\mu([a,b])=b-a \; $ for $\; a,b \in [0,1] \;$ and,
translation of subset $A \subset [0,1]$ by $x \in [0,1]$ defined as $$A \oplus x = \{ a+x \mid a \in A, a+x \le 1 \} \cup \{ a+x-1 \mid a \in A, a+x>1\}$$ does not change it's measure, i.e. $\mu(A)=\mu(A \oplus x)$.

It turns out that no such measure can be defined on power set of $[0,1]$, and you will have to contend yourself with such measure defined on some smaller $\sigma$-algebra, usually the $\sigma$-algebra of Borel sets.
The proof of this can be found in every measure theory textbook. It goes something like this: suppose $\mu$ is such measure, and observe equivalence classes of relation defined by $x \sim y$ iff $x-y \in \mathbb Q$ for $x,y \in [0,1]$. By Axiom of Choice, there is set $H$ consisting of precisely one representative of each equivalence class. We can write interval $[0,1]$ as disjoint union $$[0,1] = \bigcup_{x \in [0,1] \cap \mathbb Q} H \oplus x$$. By $\sigma$-additivity of $\mu$, $$\mu([0,1])=\sum_{x \in [0,1] \cap \mathbb Q} \mu(H \oplus x)$$ and by shift invariance all summands are equal. But this infinite sum can only equal 0 and $\pm \infty$, not 1.

ADDED: As madprob mentioned in a comment below, we could drop 2. (translation invariance) and there still would be no measure on the power set of $[a,b]$ satisfying 1. For example, Ulam proved in 1930 that if a measure is defined on all subsets of uncountable set, and all singletons have measure zero, then every set must also have measure zero (thus the only measures defined on power set of $\Omega$ are like the one in madprob's example).
Comment: I think that the problem is even more fundamental than the one you describe. That is, the lack of shift invariance is not the main reason why a measure is usually not defined over $2^{\mathbb{R}}$. Stronger than that, one can prove that every measure over $2^{\mathbb{R}}$ is discrete.
Comment: @madprob Thanks.


Manage display of geofield with wkt input widget

Question: I am stuck on something that seemed very simple and need your help.
I have an input form where there is a geofield input field of type WKT. So the user gives the WKT of a point. When the node is viewed I would like the WKT that the user previously gave to be displayed on a map. On the manage display tab all the other options seem to work (WKT, KML, description etc), except from the map option like leaflet, openlayers and geofield maps. There is empty space where the map was supposed to be.
Can anyone help me on this?
Comment: hi Mat, did u already check for any errors in the installation of your (leaflet) map? What is the format of the wkt that you are filling in? Are there maybe any errors there? Could u provide more information about the points that the users have to fill in? I was stuck with the same things in the beginning. I got it working with geocode the map form another field. For that field i used address field. More user friendly in my case because the user can fill in their address instead of wkt.
Answer: Some suggestions:

make sure that you edit the right format when you filled in the wkt.
check for any errors in the installation of the map.

I had the same problems in the beginning with mapping too. I had an error in the installation of my leaflet map. In the end I solved it with a new installation and I geocoded the geofield from my address field.
Comment: If you have a new question, please ask it by clicking the [Ask Question](http://drupal.stackexchange.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/low-quality-posts/77420)
Comment: I wanted to try to help by asking if the op already checked those things. I had the same problems in the beginning with mapping too. I had an error in the installation of my leaflet map. In the end i solved it with a new installation and i geocoded the geofield from my address field.
Comment: but if you need more information add a comment, this is not a answer
Comment: I am sorry.. I tried that but I am not allowed to post new comments yet. My intentions weren't bad. Only wanted to help the op. If i can add a comment next time I will do that or otherwise don't ask my questions in the answer section.
Comment: don't worry, try again, you need 50rep to make a comment ;-)
Comment: Thnx.. I did:-). I will delete my answer.
Comment: @Lucy : please check my edits of your answer, in which I mostly only integrated your comment, and transformed "questions" to "suggestions". With that I think it's OK to not delete it, but of course: up to you ... Just trying to help, ok?
Answer: Problem solved, I suppose it was a bug. The content type had two maps with location. When the first was empty then the second didn't show up and caused the empty space. When I removed the first map everything worked fine. But now I am stuck to this if anyone could help...
Hide grey leaflet map if empty


Behind AWS ELB : How to grab the Real IP from "netstat"?

Question: I'm using AWS Elastic Load Balancing (ELB) in front of 2 Linux Web Servers. But (based on my requirement) i need to know the Real IPs from the Web Servers' perspective, especially when i use netstat.
I need to know the number of incoming connections from each IPs (from NETSTAT), as in real time. So basically in Linux (without ELB in front), below netstat command perfectly works:
netstat -tn 2>/dev/null | grep :80

But now i can only see the internal IP(s) of the ELB; which is making the whole thing quite difficult.
What is the solution for this please? Thanks.
Comment: why are you doing so? can't you include log in your application based on x-forwarded-for header?
Answer: You could get the client source IP from ELB Access Logs and use EMR with Hive to count the number of times a client request came in from the same IP.
Answer: If you prefer a more "manual" ways: you could use tcpdump or ngrep and search for "x-forwarded-for" header on your web servers.
If you want a proper way: set some logging in your application, log the clients requests with the x-forwarded-for header.
Whatever method you choose, you could then install cloudwatch logs agent on your machines to monitor the logs generated. This agent takes care of log rotation, sending your logs to AWS as a stream (through kinesis behind the scene), and you can then create log metrics to monitor whatever you like in your logs, e.g the number of connections in real time, and even configure alarms based on this if you like.
You can then create dashboards with your metrics and have a nice monitoring panel including your custom log metrics.


Can I create a Groovy Node without escaping attribute values?

Question: I'm writing a Gradle build script that is to build an Ivy module descriptor. I need a Node like
<dependency [...] conf="default->foo"/>

I would like to do this:
node.dependencies[0].appendNode("dependency", [
                        // [...]
                        conf: "default->${dep.configuration}",
                        ])

where node is a Node instance and dep.configuration == 'foo'. But it comes out as
<dependency [...] conf="default->foo"/>

Is there a comfortable way to create a Node without escaping >s in attribute values?
Comment: As a workaround for this particular use case, I've currently resorted to specifying the configuration using a nested `` element instead, since then I don't need any `>`s in attribute values.
Answer: Ivy uses an XML parser to read the module descriptor and so it will not complain about the > entity reference. While > in attribute values is valid XML, the JAXP serialization does not print it that way and there is no way to configure it.
If you want to change this for aesthetic reasons, you would have to replace it after the XML file has been written.
Comment: So `groovy.util.Node` uses JAXP internally to serialize objects to XML text?
Comment: Yes, that's the case.
Comment: Oh right. I only realized just now, after reading your answer again, that `>` will actually expand to `>` when parsed as XML... *facepalm*
Comment: And I just realized that stackoverflow will also expand `>` if it's not in code quotes :-)


Comparing moduli of holomorphic functions

Question: Suppose we have holomorphic functions $h_1$, $h_2$ in some connected, open subset $\Omega$ of $\mathbb{C}$ containing $0$. Assume further that $h_1(0)=h_2(0)=0$ and most importantly that $$|h_1(z)|=|h_2(z)|^\alpha$$ for any $z \in \Omega$ and $\alpha\ge0$.
My question is how strongly related are $h_1$ and $h_2$?
In case when $\alpha \in \mathbb{Z}$ the problem is easy since either both functions are identical zero or in a neighborhood of $0$ their ratio is of a constant modulus so $h_1=\xi_k \cdot h_2^k$ for $\xi_k$ being a square root of unity.
Unfortunately the power function is not well defined for rational and irrational $\alpha$ so one can not repeat that reasoning. I would be grateful for Your attempts/ideas.
Answer: If $\Omega$ didn't contain $0$ we could have interesting examples.
Take a small open region $U$ away from any zeros of either function.
If it's small enough, there will be branches of $\ln h_1$ and $\ln h_2$
there. Then $\Re(\ln h_1)-\alpha\Re(\ln h_2)=0$ on $U$. This means
that $\Im(\ln h_1)-\alpha\Im(\ln h_2)$ is constant on $U$. So locally
$h_1$ is a constant of absolute value $1$ times an $\alpha$-th power
of $h_2$.
But $0\in\Omega$, and
$|h_1(z)|\sim C_1|z|^a$ and $ |h_2(z)|\sim C_2|z|^b$ as $z\to0$,
with $a$, $b\in\Bbb N$. This means that $\alpha=a/b\in\Bbb Q$.
Comment: The second part of Your answer is very helpful. Any ideas for rational case then ?
Comment: In the rational case, there will be some integers $r$ and $s$ with $ra+sb=g=\gcd(m,n)$. Consider $h_3=h_1^rh_2^s$. Up to constants, $h_1$ and $h_2$ will be powers of $h_3$.


How do I use "each" on an Openstruct object?

Question: I have a OpenStruct hash like this:
#<OpenStruct object1={
                       "param1"=>"2",
                       "param2"=>"1"
                     },
             object2={
                       "param1"=>"2",
                       "param2"=>"1"
                     },
             object3={
                       "param1"=>"2",
                       "param2"=>"1"
                     }...

How can I use each on this?
Answer: OpenStruct has a method called marshal_dump that returns the underlying hash structure:
your_open_struct.marshal_dump.each{ |k,v| puts "#{k} => #{v}" }

If you are using Ruby 2.0, you can use also to_h like so:
your_open_struct.to_h.each{ |k,v| puts "#{k} => #{v}" }

Unlike marshal_dump, which returns the actual hash structure, to_h returns a hash with all the keys converted to symbols for easier access.


Can we say delta% is significant if delta is significant?

Question: The question is simple. As for most of the online A/B test,  we are more interested in the delta% than delta, for example:
<code>delta = (mean of treatment - mean of control)
delta% = (mean of treatment - mean of control)/mean of control.
</code>
Let say if we use two-mean T-test, (statistics is Delta) we found the statistics Delta is significant. Then can we say delta% is significant?

If yes, why?
If not, in this case, then use delta% as statistics, how do we know its distribution (let's say the sample size is big)?
Comment: You need to distinguish between statistical significant and practical significance. For example, if you have 1+ million samples, you could show the treated groups spends a statistical significant 2 extra seconds viewing the web page, but if the average time per page is 5 minute, is that extra time an improvement? (a practical improvement? this is business decision and not a statistics question)
Comment: @Dave2e Your point about the distinction between economic and substantive significance is very relevant. But it is certainly possible to cook up an example where only one of the two passes at $\alpha = 5 \%$. After all, $X-Y$ and $(X-Y)/Y$ are different random variables, with different distributions.
Comment: @Dave2e  You are right. But you misunderstand my question. Actually, I was asking, in order to know delta% significant, could we use delta as the statistics? if not we have to use delta% as the statistics in the hypothesis test. The question is not asking if it is practically significant.
Comment: @DimitriyV.Masterov That what I am asking. (−)/  usually we have way to estimate the variance but it is difficult for me to determine its distribution. So usually I will use (−) as the Rv to determine if (−)/. I am not sure if this is strict.
Answer: The absolute (delta) and relative (delta%) changes are different random variables, so you should try to calculate the ratio-based standard errors, CIs, and p-values if you care about the latter. This will not change your decision most of the time, but you will come across examples where it does matter (wider CIs, higher p-values, etc.). Ratios can be tricky like that.
Here's a toy example to make things clearer. Consider a two-sample test with a binary outcome where $N_T=N_C=1,359$. There are 163 successes in treatment, and 136 in control. The p-value on the absolute diff is 0.098, so you would reject the null that the two groups are same at $\alpha=.10$. However, the p-value on the relative difference is 0.101, so you would fail to reject. In some sense, this is an artifact of using a fixed threshold for significance and the approximation inherent in using delta method, but could lead to different decisions with the same data and decision rule but different definitions of difference.
Now on to your second question. There are many ways to calculate the variance, with varying complexity. It depends on what tools you have access to, features of your data and experiments, and your company's level of statistical sophistication.
These methods are:

Delta method (either with correlated means or uncorrelated means)
Fieller's method (with correlated or uncorrelated means or regression version)
Regression (either transforming the outcome, or transforming the coefficients or using a GLM and then using the delta method or Fieller's method)
Bootstrapping (relative difference itself or regression), permutation tests
Some combinations of the above, like bootstrapped GLM regression

If you are willing to assume that the two means are uncorrelated (which usually makes sense in an A/B test), there are simple formulas linked above you can use (either delta method or based on Fieller's method). There are also canned commands/packages/online calculators.
If you are not willing to assume that, you can use regression since that returns the covariances pretty easily. Then you can use either the more complicated formulas that have the covariance term or have some stats package handle that for you. Another potential option is to log the outcome or use a GLM model to get the effects in percent.
Personally, I find some version of regression easiest, and that still works even if there is no correlation since in that case the covariance will be close to zero.
You can also bootstrap easily, ether the relative change itself or using regression coefficients. There is no formula since this is a resampling method. Make sure to set the seed so that you can replicate your work each time.
None of these approaches are exact, they are all approximations. In the toy example below, they align pretty closely.
For example, the delta method formula for the standard error of the relative change is
$$SE \left( \frac{B-A}{A} \right) \approx \sqrt{\frac{Var(B)\cdot B^2  - 2 \cdot Cov(A,B)\cdot A \cdot B + Var(A)\cdot A^2}{A^4}},$$
where $A$ is the mean in the control group and $B$ is the mean in the treatment group. Assuming uncorrelated means leads to covariance term being zero, simplifying the formula. Otherwise, regression is the easiest way to get the covariance between the two means.
Below I will compare blood pressure between men and women (analogous to a treated and control group) using Stata. I annotated the Stata code with some brief explanations.
You can find some regression-based examples of Stata and R code in Lye, J., & Hirschberg, J. (2018). Ratios of Parameters: Some Econometric Examples. Australian Economic Review, 51(4), 578–602. doi:10.1111/1467-8462.12300.
In this dataset, women have 5% lower BP relative to men, which is about 8 mmHg in absolute terms. All of the relative difference CIs are roughly in the [-8%,-2%] range:
<code>. sysuse bplong, clear
(fictional blood-pressure data)

. keep if when=="After":when
(120 observations deleted)

. isid patient

. /* summary stats */
. table sex, c(mean bp semean bp sd bp N bp)

----------------------------------------------------------
      Sex |   mean(bp)     sem(bp)      sd(bp)       N(bp)
----------+-----------------------------------------------
     Male |   155.5167    1.967891    15.24322          60
   Female |      147.2    1.515979    11.74272          60
----------------------------------------------------------

. label list sex
sex:
           0 Male
           1 Female

. set seed 10122020

.
. /* (A) Absolute effect */
. ttest bp, by(sex) reverse

Two-sample t test with equal variances
------------------------------------------------------------------------------
   Group |     Obs        Mean    Std. Err.   Std. Dev.   [95% Conf. Interval]
---------+--------------------------------------------------------------------
  Female |      60       147.2    1.515979    11.74272    144.1665    150.2335
    Male |      60    155.5167    1.967891    15.24322    151.5789    159.4544
---------+--------------------------------------------------------------------
combined |     120    151.3583    1.294234    14.17762    148.7956     153.921
---------+--------------------------------------------------------------------
    diff |           -8.316667    2.484107               -13.23587   -3.397459
------------------------------------------------------------------------------
    diff = mean(Female) - mean(Male)                              t =  -3.3480
Ho: diff = 0                                     degrees of freedom =      118

    Ha: diff < 0                 Ha: diff != 0                 Ha: diff > 0
 Pr(T < t) = 0.0005         Pr(|T| > |t|) = 0.0011          Pr(T > t) = 0.9995

. regress bp i.sex

      Source |       SS           df       MS      Number of obs   =       120
-------------+----------------------------------   F(1, 118)       =     11.21
       Model |  2075.00833         1  2075.00833   Prob > F        =    0.0011
    Residual |  21844.5833       118  185.123588   R-squared       =    0.0867
-------------+----------------------------------   Adj R-squared   =    0.0790
       Total |  23919.5917       119  201.004972   Root MSE        =    13.606

------------------------------------------------------------------------------
          bp |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |  -8.316667   2.484107    -3.35   0.001    -13.23587   -3.397459
       _cons |   155.5167   1.756529    88.54   0.000     152.0383    158.9951
------------------------------------------------------------------------------

.
. /* (B) Relative Effect */
.
. /* (-1) logged outcome t-test (works for strictly positive data and small relative differences) */
. generate ln_bp = ln(bp)

. ttest ln_bp, by(sex) reverse

Two-sample t test with equal variances
------------------------------------------------------------------------------
   Group |     Obs        Mean    Std. Err.   Std. Dev.   [95% Conf. Interval]
---------+--------------------------------------------------------------------
  Female |      60    4.988759    .0100682    .0779881    4.968612    5.008905
    Male |      60    5.041963    .0127957    .0991153    5.016358    5.067567
---------+--------------------------------------------------------------------
combined |     120    5.015361    .0084655     .092735    4.998598    5.032123
---------+--------------------------------------------------------------------
    diff |            -.053204    .0162819               -.0854466   -.0209615
------------------------------------------------------------------------------
    diff = mean(Female) - mean(Male)                              t =  -3.2677
Ho: diff = 0                                     degrees of freedom =      118

    Ha: diff < 0                 Ha: diff != 0                 Ha: diff > 0
 Pr(T < t) = 0.0007         Pr(|T| > |t|) = 0.0014          Pr(T > t) = 0.9993

.
. /* (0) bootstrap means */
. capture program drop mybs

. program define mybs, rclass
  1.         quietly summarize bp if sex=="Female":sex
  2.         scalar female_avg_bp = r(mean)
  3.         quietly summarize bp if sex=="Male":sex
  4.         scalar male_avg_bp = r(mean)
  5.         return scalar ratio = (female_avg_bp - male_avg_bp)/male_avg_bp
  6. end

.
. bootstrap ratio = r(ratio), reps(500) nodots nowarn: mybs

Bootstrap results                               Number of obs     =        120
                                                Replications      =        500

      command:  mybs
        ratio:  r(ratio)

------------------------------------------------------------------------------
             |   Observed   Bootstrap                         Normal-based
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       ratio |  -.0534777   .0153194    -3.49   0.000    -.0835031   -.0234522
------------------------------------------------------------------------------

.
.
. /* (1b) delta method using regression and ratio of predictions by hand */
. regress bp i.sex

      Source |       SS           df       MS      Number of obs   =       120
-------------+----------------------------------   F(1, 118)       =     11.21
       Model |  2075.00833         1  2075.00833   Prob > F        =    0.0011
    Residual |  21844.5833       118  185.123588   R-squared       =    0.0867
-------------+----------------------------------   Adj R-squared   =    0.0790
       Total |  23919.5917       119  201.004972   Root MSE        =    13.606

------------------------------------------------------------------------------
          bp |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |  -8.316667   2.484107    -3.35   0.001    -13.23587   -3.397459
       _cons |   155.5167   1.756529    88.54   0.000     152.0383    158.9951
------------------------------------------------------------------------------

. nlcom ratio:(_b[1.sex])/_b[_cons]

       ratio:  (_b[1.sex])/_b[_cons]

------------------------------------------------------------------------------
          bp |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       ratio |  -.0534777    .015552    -3.44   0.001     -.083959   -.0229963
------------------------------------------------------------------------------

. margins, eydx(sex) // another way: calculate the elasticity

Conditional marginal effects                    Number of obs     =        120
Model VCE    : OLS

Expression   : Linear prediction, predict()
ey/dx w.r.t. : 1.sex

------------------------------------------------------------------------------
             |            Delta-method
             |      ey/dx   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |  -.0549607   .0164307    -3.35   0.001    -.0874979   -.0224235
------------------------------------------------------------------------------
Note: ey/dx for factor levels is the discrete change from the base level.

.
. /* (2a) logged outcome regression */
. /* works for strictly positive data and small relative differences */
. regress ln_bp i.sex

      Source |       SS           df       MS      Number of obs   =       120
-------------+----------------------------------   F(1, 118)       =     10.68
       Model |  .084920032         1  .084920032   Prob > F        =    0.0014
    Residual |  .938452791       118   .00795299   R-squared       =    0.0830
-------------+----------------------------------   Adj R-squared   =    0.0752
       Total |  1.02337282       119  .008599772   Root MSE        =    .08918

------------------------------------------------------------------------------
       ln_bp |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |   -.053204   .0162819    -3.27   0.001    -.0854466   -.0209615
       _cons |   5.041963    .011513   437.94   0.000     5.019164    5.064762
------------------------------------------------------------------------------

.
. /* (2b) GLM with exponentiated coefficients */
. glm bp i.sex, family(gaussian) link(log) nolog

Generalized linear models                         Number of obs   =        120
Optimization     : ML                             Residual df     =        118
                                                  Scale parameter =   185.1236
Deviance         =  21844.58333                   (1/df) Deviance =   185.1236
Pearson          =  21844.58333                   (1/df) Pearson  =   185.1236

Variance function: V(u) = 1                       [Gaussian]
Link function    : g(u) = ln(u)                   [Log]

                                                  AIC             =   8.075427
Log likelihood   = -482.5256155                   BIC             =   21279.66

------------------------------------------------------------------------------
             |                 OIM
          bp |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |  -.0549607   .0164307    -3.35   0.001    -.0871643   -.0227571
       _cons |   5.046753   .0112948   446.82   0.000     5.024616     5.06889
------------------------------------------------------------------------------

.
. /* (3) bootstrap ratio of predictions from regression by hand */
. bootstrap ratio = (_b[1.sex]/_b[_cons]), reps(500) nodots: regress bp i.sex

Linear regression                               Number of obs     =        120
                                                Replications      =        500

      command:  regress bp i.sex
        ratio:  _b[1.sex]/_b[_cons]

------------------------------------------------------------------------------
             |   Observed   Bootstrap                         Normal-based
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       ratio |  -.0534777   .0147228    -3.63   0.000    -.0823338   -.0246215
------------------------------------------------------------------------------

.
. /* (4) Fieller's method (uncorrelated means) */
. /* there is also a correlated means version */
. fieller bp, by(sex) reverse
Confidence Interval for a Quotient by Fieller's Method (Unpaired Data)

Numerator Mean:   147.2
Denominator Mean: 155.51667
Quotient:         .94652234
95% CI:      .91652092�.97771318

.
. /* (5) delta method by hand (uncorrelated means) */
. /* there is also a correlated means version */
. table sex, c(mean bp sd bp N bp)

----------------------------------------------
      Sex |   mean(bp)      sd(bp)       N(bp)
----------+-----------------------------------
     Male |   155.5167    15.24322          60
   Female |      147.2    11.74272          60
----------------------------------------------

. display "SE(ratio) = " sqrt(((15.24322^2/60)*(155.5167)^2+(11.74272^2/60)*(147.2)^2)/(155.5167^4))
SE(ratio) = .01566056
</code>
The Filler method above calculates $\frac{\bar Y_{female}}{\bar Y_{male}}$ rather than the relative change, but they are equivalent. The paper linked above has R and Stata code to calculate the relative change with regression.

Here is some code showing that the p-values can also differ depending on whether absolute or relative change is used with Wald and Wald-type tests:
<code>. sysuse bplong, clear
(fictional blood-pressure data)

. keep if when=="After":when
(120 observations deleted)

. estimates clear

. qui regress bp i.sex

. /* Absolute effect Wald-type test */
. testnl _b[1.sex] = 0

  (1)  _b[1.sex] = 0

               chi2(1) =       11.21
           Prob > chi2 =        0.0008

. display r(p)
.00081412

. /* Relative effect Wald-type test */
. testnl _b[1.sex]/_b[_cons] = 0

  (1)  _b[1.sex]/_b[_cons] = 0

               chi2(1) =       11.82
           Prob > chi2 =        0.0006

. di r(p)
.00058466

. /* Absolute effect Wald test */
. test _b[1.sex] = 0

 ( 1)  1.sex = 0

       F(  1,   118) =   11.21
            Prob > F =    0.0011

. display r(p)
.00109302

. /* Relative effect Wald test */
. margins, eydx(sex) post

Conditional marginal effects                    Number of obs     =        120
Model VCE    : OLS

Expression   : Linear prediction, predict()
ey/dx w.r.t. : 1.sex

------------------------------------------------------------------------------
             |            Delta-method
             |      ey/dx   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         sex |
     Female  |  -.0549607   .0164307    -3.35   0.001    -.0874979   -.0224235
------------------------------------------------------------------------------
Note: ey/dx for factor levels is the discrete change from the base level.

. test _b[1.sex] = 0

 ( 1)  1.sex = 0

       F(  1,   118) =   11.19
            Prob > F =    0.0011

. di r(p)
.00110368
</code>
Comment: Hi Dimitriy, Thanks for this comprehensive explanation. It helps me a lot. I think to estimate the variance of ratio, I know how to do also you list several methods above. but have the estimation of the variance of the ratio is not enough, we need to know the distribution of stats in order to calculate the p-value if using a parametric test. I am not familiar with the wald-test above. Just take the example you gave " a two-sample test with a binary outcome" which test you are using and how did you calculate the p-value?
Comment: I used regression to do that part, with the delta method for the relative difference variance. You can also bootstrap to get the distribution of the statistic. Fieller's method could be used to iteratively to get a p-value. I suppose permutation tests are another option to get the distribution under the null.
Comment: Thanks. For the nonparametric method, it is easy as we don't assume any distribution here. for the parametric method, I was confused about how to do it. Thanks a lot.
Answer: Equivalent null hypotheses
Yes
When you are asking the question about significance then you relate to hypothesis testing.
For your situation, the hypotheses $H_0: \Delta = 0$ and $H_0: \Delta\% = 0$ are equivalent if you assume that 'mean of control' is non-zero (and if you do not assume that, then the $\Delta\%$ becomes a problematic definition due to the potential division by zero).
So if $\Delta$ is significantly different from $0$ then you can also claim that  $\Delta\%$ is significantly different from $0$.
Distribution of the data, not the parameter estimate
Also, note that the testing is normally not performed by observing only $\Delta$ or only $\Delta\%$. In that case, you would have a problematic situation with unknown nuisance parameters.
Instead, you use some test statistic which is based on the observations of treatment and observations of control, e.g their means $\mu_{treatment}$ and $\mu_{control}$. The test procedure would be the same for hypotheses $H_0: \Delta = 0$ and $H_0: \Delta\% = 0$ because you do not base yourself on the sample distributions of $\Delta$ or $\Delta\%$, but instead on the joint sample distribution of $\mu_{treatment}$ and $\mu_{control}$. You base a significance test on the data.
You might think that the significance test is different because estimates of $\Delta$ and $\Delta\%$ have different sample distributions. However, the parameter estimate and it's sample distribution is not necessarily the statistic that is used as a significance test.
For instance, when we perform linear regression, then we might estimate a parameter and perform a t-test which relates to the sample distribution of the parameter. But, we could also perform an analysis of variance and perform a F-test, which doesn't care how you express the parameter.
Significance testing is not primarily about the distribution of the estimate of some statistic (it can be used in testing, but it is derivative and not a first principle). Instead, it is in the first place about the distribution of the data conditional on the null hypothesis being true. The sample distribution of the data is the same for both null hypotheses. Therefore if an observation is significant for the one hypothesis, then it is also significant for the other.
Significance means that you made an extreme observation given the null hypothesis.

Confidence intervals
Where the use of $\Delta$ and $\Delta\%$ may differ is in the expression of confidence intervals. In this case, we are not talking anymore about the null hypothesis $H_0: \Delta = 0$ that assumes the parameter is equal to zero. But instead we consider the range of parameters $\theta$ for which the hypothesis $H_0: \Delta = \theta$ will pass a significance test (passing means no significance). The hypothesis $H_0: \Delta = \theta$ and $H_0: \Delta \% = \theta$, with $\theta \neq  0$ are not equivalent.
Comment: The p-values could definitely differ between the two because as you said, they are different random variables with different sampling distributions under $H_0$. The point is that any test that rejects one $H_0$ rejects the other. One test may be more powerful, though. It's not that uncommon for multiple tests to test the same null hypothesis in different ways with different test statistics and p-values, like Bartlett's test and Levene's test for equality of variances.
Comment: Does the p-value invariance hold in a regression setting? I added an example above where the p-values do seem to vary slightly depending on whether relative or absolute change is used. Or am I missing something?
Comment: @DimitriyV.Masterov I agree with Noah, the p-values *can* differ for different tests. But when we consider $H_0:\Delta$ or $H_0:\Delta\%$ we are not necessarily considering different tests. The parameter estimates may be different statistics with different sample distributions, but they are not typically used to do the inference (in the same way in linear regression: you could consider the sample distribution of a coefficient, and perform a t-test, but for a more optimal test you should consider a F-test, which considers the residuals/data, and doesn't care how you express the coefficient).
Comment: @DimitriyV.Masterov I am not sure why your examples relate to different null hypotheses. You consider different variables, like the logarithm, but why does the one relate more or less than the other to a hypothesis like  $H_0:\Delta=0$ or $H_0:\Delta\%=0$?
Comment: Significance testing is not about the distribution of the estimate of some statistic (it can be used in testing, but it is derivative), but it is in the first place about the distribution of the data conditional on the null hypothesis being true. **The sample distribution is the same for both null hypotheses.** Therefore if an observation is significant for the one hypothesis, then it is also significant for the other.
Comment: The example at the bottom of my post does not involve logarithms. I have two types of tests for the absolute difference and the relative difference, with different p-values.
Comment: @DimitriyV.Masterov with those two Wald tests you are not testing different hypothesis, you are just using different statistics (the estimates of the coefficients $\hat\Delta$ vs $\hat\Delta\%$ and estimates of their sample distributions) to perform the significance test. The tests are indeed different, but it does not mean that the related hypotheses are different.


Home run scored or out

Question: A batter hits a home run, the ball leaves the field of play. The batter does not tag home plate in a celebration. The umpire gives the catcher a new ball. The batter goes back to touch home plate but the catcher tags the batter and the umpire calls the batter out. Run does not count. Is the batter out or safe?
Comment: I find the question ambiguous.  How far was the runner that he had to "go back" to the plate? Was it two steps and turned around?  Was it down to the dugout when someone pushes him back onto the field?  5.09(b)(2) is possible.
Answer: I am referencing Major League Baseball's Official Rules for 2017 (pdf). On page 49, under rule 5.09(c) - Appeal plays, it says:

Any runner shall be called out, on appeal, when:...(4) He fails to touch home base and makes no attempt to
  return to that base, and home base is tagged.

I would also cite rule 5.02 on page 34, which says (emphasis added):

5.02 After the umpire calls "Play" the ball is alive and in play and remains alive and in play until for legal cause, or at the umpire's call of "Time" suspending play, the ball becomes dead. While the ball is dead no player may be put out, no bases may be run and no runs may be scored, except that runners may advance one or more bases as the result of acts which occurred while the ball was alive (such as, but not limited to a balk, an overthrow, interference, or a home run or other fair ball hit out of the playing field).

and rule 5.12 about dead balls, which states:

After the ball is dead, play shall be resumed when the pitcher takes his place on the pitcher's plate with a new ball or the same ball in his possession and the plate umpire calls "Play." The plate umpire shall call "Play" as soon as the pitcher takes his place on his plate with the ball in his possession.

In this case, the ball was dead (by virtue of being a homerun). From Rule 5.02, no player may be put out while the ball is dead. According to rule 5.12, the ball is not "Live" yet, since the pitcher had not taken his place on the plate with a new ball and the umpire didn't say "Play". The batter was trying to return to the base while the ball was still dead. So I'd conclude that the requirements for 4.09(c)(4) were not met and the player should have been safe.

Home run scored or out


DiscordJS Como faço quando ao finalizar um audio ele tocar outro

Question: Minha duvida é seguinte, tenho um código que ele faz bot conectar ao canal de voz do discord quando usuário da comando "!!play url_video_youtube". Quando é digitado novamente comando é incrementado a array "listMusic". Minha duvida é como faço ao finalizar musica atual ele avança-se para próxima.
No "dispatcher.on('finish') consigo saber quando finalizou a musica, só não sei como faço pra tocar próxima musica de acordo com item da array.
async onPlayMusic (message:Message, url:string){
    listMusic.push(url);

    const voiceChannel = message?.member?.voice.channel;

        if (!voiceChannel) {
            return message.reply('precisa está em canal de voz!');
    }

    [0,1]

    voiceChannel.join().then(connection => {
            const stream = ytdl(url, { filter: 'audioonly' });
            const dispatcher = connection.play(stream);

            dispatcher.on('finish', () => {

        let musics = listMusic.length;

        if(musics > 1){
          listMusic[listMusic.length-1];
        }
        //voiceChannel.leave()
      });
    });
  },

Answer: Basicamente você tem que criar um loop que verifica quantos links há em seu array, e que quando terminar de reproduzir ele passe para o próximo item do array.
Seria algo mais ou menos assim:
let url = ["www.musica.com", "www.proxima-musica.com"];// não sei como você cria o array com os link de reprodução, mas deve ficar asim imagino.
let index = 0;

function playMusic()//crisse uma função para que seja chamada novamente dentro de "on.finish"
{
    if ( url.length >= index )
    {
        voiceChannel.join().then(connection =>
        {
            const stream = ytdl(url[index], { filter: 'audioonly' });
            const dispatcher = connection.play(stream);

            dispatcher.on('finish', () =>
            {
                let musics = listMusic.length;

                if(musics > 1)
                {
                  listMusic[listMusic.length-1];
                }

                index++//quando terminar de reproduzir ele acrecentar +1 no index;
                playMusic();//callback, que força um loop
            });
        });
    }else{
        //não á mais links no array para serem reproduzidas.
    }
}

Comment: Obrigado. Vou da uma estuda em callback achei bem interessante.


Transfer DNS to resolve domain to my server

Question: I have bought a domain name www.mydomain.com on Namecheap, and I have successfully managed to set up redirections to my personal server available at the IP address XXX.XXX.XXX.XXX.
The problem is when I visit www.mydomain.com, the address bar changes to XXX.XXX.XXX.XXX because of the redirection.
I want DNS servers to automatically resolve www.mydomain.com to XXX.XXX.XXX.XXX to avoid the redirection. Namecheap allows me to "Transfer DNS to Webhost", but I do not know what details to enter there (I need to enter DNS server domains).
Is there a procedure to inform DNS servers around the world that www.mydomain.com should now resolve to XXX.XXX.XXX.XXX? What DNS information should I give Namecheap to transfer DNS?
Answer: There are four entities in this problem and it rather confuses things that NameCheap are three of them.

Your registrar is the company that takes your money to register a domain with ICANN.  They tell the root DNS servers where your nameservers are.  For you, this company is NameCheap.  If NameCheap are running your nameservers for you, they will use their own domain name and IP addresses at this stage.
Your nameserver is the nameserver that holds all the DNS records for your domain.  Bind, PowerDNS and djbdns are three popular examples of DNS software.  For you, this company is also NameCheap.  NameCheap should provide a web interface that will allow you to change most of these records.
NameCheap's webserver is part of this due to the redirection you set up to redirect to your webserver.  When you did this, NameCheap changed the DNS record for www.example.com to point to their webserver and then configured their webserver to respond to all HTTP requests with an HTTP 301 or 302 redirect response with a Location: header that indicated your IP address.  This is probably not what you wanted to happen.
Your webserver has an IP address but there are no DNS records in any system that contain that IP address.  There is no mapping from a name to that IP address.

What you should do now is log into NameCheap's web interface, find your domain manager and set up an A record for the root of your domain (probably displayed as an @ symbol) that contains your IP address.  Then create another A record for the www subdomain that also contains your IP address.  Both of these records probably already exist and you will simply need to change them to be A records and to contain your IP address.
Having just watched this NameCheap tutorial I would like to wish you the best of luck getting this right.  That video has pushed GoDaddy off the top of the most confusing DNS interface implementations list.  It's seriously bad.  I hope it's cheap.
Comment: He, thank you for this excellent clarification. Do you know of good domain registrars, as alternatives to GoDaddy and NameCheap?
Comment: If you are registering thousands of domains then the price your registrar offers will matter, if not then customer relations matter more.  Since you don't normally change DNS records very often, reliability and uptime matter more than the interface with a nameserver provider.  StackExchange is not a good place for product recommendations but Wikipedia has lists of registrars and nameserver providers that would be a good place to start.
Answer: You must to create a 'A' record for 'www.mydomain.com.' in your server that points to your ip. Redirection is not a real DNS entry, is a html in your home directory that redirects to your server. When you go to www.mydomain.com you will be redirected to xxx.xxx.xxx.xxx for this rason you are seeing this ip instead of the domain.
Comment: @randomblue It made perfect sense to me. What are you unclear about?
Comment: How can I create an 'A' record for my domain?


Is the notion of a set always a primitive notion?

Question: Is there an approach in set theory where we have a definition of a set, or do we always consider the notion of a set as being a primitive notion that cannot be defined in terms of previously defined other notions?
Comment: @William: How do you define a "power set" without appealing to "set" in the first place?
Comment: If you believe in the foundation axiom, you can take $\emptyset$ as your primitive notion. Then all other sets come from iterating powerset and union operations. Look into the well-founded universe for more information about this.
Comment: To formally define what a set is (e.g. $x$ is a set iff...), you would also have to define what is *not* a set. It doesn't seem possible.
Comment: If, for example, you define $x$ to be a set iff $\exists a\in x$, then the so-called empty set could not exist. That would be very troublesome indeed.
Comment: @William Well, that's in $\sf ZFC$. The OP isn't restricting himself to $\sf ZFC$, I believe.
Answer: The $\lambda$-calculus (and similar systems defined using combinators) can be seen as an attempt to define a mathematical world in which everything is a function. See https://www.encyclopediaofmath.org/index.php/Illative_combinatory_logic for references.
More recent work on mathematical foundation systems of this kind generally involves some notion of type (see http://en.wikipedia.org/wiki/Intuitionistic_type_theory) and it is a topic for debate whether type-theoretic foundations and set-theoretic foundations are really different. Proponents of type theory will generally say that they are.
Answer: There are candidates for foundational theories, such as category theory and the theories that Rob mentions, in which the notion of "set" is not primitive, but I don't think these count as set theories even if they turn out to be mutually interpretable with set theories.
In set theory you can get close to what you want, I think, with NBG set theory (the one-sorted formulation) in which "class" is the primitive notion and a set is defined as a class that is contained in some other class.
Comment: The sentence you quoted sounds like naive set theory rather than axiomatic set theory (note that the ZFC axioms https://en.wikipedia.org/wiki/ZFC#The_axioms do not define "set".)  In the context of that sentence "well-defined" probably means defined by a logical formula (rather than by some fuzzy natural language definition.)
Comment: By a class do you mean an "object"?
Comment: @palio I'm not sure what your question means.  Could you clarify it?
Comment: Because many introductory books on set theory say that "a set is a well defined collection of distinct objects" and here "object" is always a primitive notion. And by the way what does "well defined" mean in this sentence? thank you !!


Roman numeral analysis for melody?

Question: This is mainly a notation question. But when analyzing a melody how do you notate melody notes?
Is it 1, 2, 3, 4, 5, 6, 7 or I, II, III, IV, V, VI, VII (or maybe lower case) or do, re, mi, fa, sol, la, ti, or something else? or maybe melody is not notated at all?
Comment: I don't.  The melody speaks for itself.  The chords need a separate notation, but the melody doesn't.
Comment: I was about to edit what I thought was a mistake, but after searching you really use "ti" instead of "si" in english? That is pretty strange..
Comment: @Kaddath The Sound of Music (do-re-mi) calls that note ["a drink with jam and bread"](https://en.wikipedia.org/wiki/Do-Re-Mi). So indeed, "ti" instead of "si".
Comment: @00 but the song is based on the notes, not the other way round.. I found [here](https://www.studybass.com/using-the-site/american-english-music-terminology/) that it's because they didn't want notes beginning with the same letters..
Comment: @Kaddath I didn't claim the notes originate with the song. Instead, the song, as a well-known song, just shows the use of "ti" in the English language.
Answer: Lots of harmony books use numbers with a circumflex accent. It's sometimes not so simple to type. Then the circumflex is prefixed. Tonic note is ^1 and the dominant ^5, etc. Flats and sharps are prefixed meaning raise or lower within the context of the scale.
I find it a bit clumsy as no tempo indication is given. While harmonies may remain for a measure or more, melodies tend to move around a lot.
Answer: Circumflex to indicate scale degree. But also, if the music is homophonic, label non chord tones. To the extent the music exhibits motifs, label those and their variations, along with inversion and retrograde. Not all music uses those devices, so label only if appropriate. I think labeling cadences, phrase ending types is helpful too. That brings in harmonic analysis, but it does help to understand melodic phrases within the larger compositional structure.
Answer: 'How do you notate melody notes?'
Well, I certainly don't use Roman numerals. They are kept for harmony and chords only.
I might use Arabic numbers, with approriate sharps or flats before (or after) them.
I might use solfege, whiich works well in movable doh, where doh is the root of the key.
I might use fixed doh, where doh is C always. This can become messy with every note having its own name, and often incurs extra 'dieze' or 'bemole' being attached to notes, which does make it tricky when singing those notes.
All of which won't have any timings shown.
So, the simplest, for me, since that's what you ask, is to eschew those and go for the old-fashioned dots on staves. Which actually can be read by any muso, anywhere, with no confusion. I.e. it works!
Comment: "Fixed doh", must be the Homer Simpson notation style
Comment: @piiperiReinstateMonica - for me, it certainly smacks of him...

Roman numeral analysis for melody?


Show infinite primes of the form $12k + 1$

Question: Show that there are infinite amount of primes of the form $12k + 1$ for $k \in \Bbb{N}$.
I tried to use similar techniques I have seen to prove that there are infinite prime for primes of the form $4k + 3$.
The technique was assume that there are finite number of that form $p_1$ to $p_n$ and get a contradiction by considering the number $$4\left(\prod_i^n p_i\right) + 3$$but couldn't apply the same methods in this case.
Comment: The sequence $a_k=12k+1$ contains an infinite amount of prime numbers, since $12$ and $1$ are coprime integers (according to [Dirichlet's theorem on arithmetic progressions](https://en.wikipedia.org/wiki/Dirichlet's_theorem_on_arithmetic_progressions)).
Comment: There are several obstacles to trying to use the old familiar Euclidean method to primes of this form. It might help you, maybe just in this particular case, to see it as a matter of construction rather than contradiction. That is, if we have a finite list of primes of this form, how do we use that list to obtain another prime of that form to add to our list? Trouble is, the potential new prime might actually be the product of primes of the form $12k + 5$, $12k + 7$ and/or $12k + 11$.
Answer: Hint. Consider the polynomial $x^4-x^2+1$.

 If there were finitely many, let $x$ be their product and consider a prime divisor $p$ ($\neq2,3$) of $x^4-x^2+1$. Then $x^6\equiv-1\pmod p$, so $p\equiv1\pmod4$, and $(2x^2-1)^2\equiv-3\pmod p$, so $-3$ and thus $3$ is a square mod $p$, so $p$ is a square mod $3$ by QR, so $p\equiv1\pmod3$. Contradiction.

More generally, the prime divisors of $\Phi_n(x)$ ($n$th cyclotomic polynomial) for $x\in\mathbb Z$ are either prime divisors of $n$ or $\equiv1\pmod n$.