When can we "safely" use extended real numbers

Question: I learned that we can define extended reals and some related arithmetic operations. I wonder when can we use these notations without worrying about consistency.
For example, if $\lim_{n\to\infty}a_n=\lim_{n\to\infty}b_n=\infty$, I can verify that 1. by definition, $\infty+\infty=\infty$; 2. using $\epsilon-\delta$ method, I can prove that $\lim_{n\to\infty}a_n+b_n=\infty$. Thus in terms of limits, it's ok to apply the addition rule to even infinite limit points.
However, what about other maths concepts I had learned? Is it always true that as long as there exists a clear definition that includes infinity (such as limits of a $\bar{\mathbb{R}}$-valued function), then all rules that apply to finite numbers (such as addition of limits) also apply to infinity? If not, do I need to check every time by myself?
Comment: $\infty + \infty = \infty$ and $\infty \cdot \infty = \infty$ are fine, past that it gets messy. See https://en.wikipedia.org/wiki/Indeterminate_form for a list of what doesn't work.
Comment: This is not a duplicate, but you may also be interested in [my answer](https://math.stackexchange.com/a/4097209/26369) to [When do we cannot split an improper integral?](https://math.stackexchange.com/q/3854034/26369) which spells out many cases of to what extent limit laws do and do not work with $\infty$ around.
Answer: All of the limit laws work just as well as before. If $l$ and $m$ are extended real numbers, and $f(x)\to l$, $g(x)\to m$ as $x\to a$, then

$(f-g)(x)\to l-m$
$(f+g)(x)\to l+m$,
$(f\cdot g)(x)\to l\cdot m$,
$(f/g)(x)\to l/m$,

provided that those expressions to the right of $\to$ are defined. Remember that $\infty-\infty$, $0\cdot\infty$, $\infty/\infty$, and $l/0$ are undefined.
This is no accident. In fact the reason that it makes sense to define $\infty+\infty$ as $\infty$ is that the "sum limit law" still holds under this definition. Contrariwise, since there is no way of defining $\infty-\infty$ to make the "subtraction limit law" work out, we ought to leave this expression undefined.
More deeply, one of the motivations behind the extended reals is to extend the usual arithmetic operations such as $+$ and $\cdot$ to $\pm\infty$ by continuity. The usual addition function $+:\mathbb R^2\to\mathbb R$ can be continuously extended to the point $(\infty,\infty)$, and so this is what we do.
A caveat: in measure theory and probability, I believe it is common to define $0\cdot\pm\infty=0$, even though this is not a continuous extension of multiplication. I have no doubts that this convention must be useful for other reasons, but I do not know what they are.
Comment: Yes, I also noticed that limit laws still hold. I'm mostly concerned with other situations and, as you mentioned, things like $0\cdot \infty$ in measure theory.
Comment: @DanielMendoza: Sorry, I think I misread your question. There is no general principle that allows you to "transfer" true statements about the reals to the extended reals, nor is there a principle that allows you to transfer statements in the other direction. So you do have to check things individually. Some things might hold for the reals, but not for the extended reals, and vice versa. Examples: in the extended reals, every set is bounded above; the real numbers are a field, but the extended reals are not, etc.
Comment: As for $0\cdot\infty$, unless you are actually doing measure theory, I would suggest that it is better to leave it undefined. Otherwise, you are just introducing exceptions to the limit laws for no good reason.


query joining three tables yii

Question: How to convert  mysql query to yii.?
I have 3 table

user_header
customers
customer_ratings

and this is my sql query
SELECT t.email
FROM   otz_user_header t
       JOIN otz_customers r
         ON t.user_id = r.customer_user_id
       JOIN otz_customer_ratings cr
         ON cr.customer_user_id = r.customer_user_id
WHERE  r.rate_auto_approve = 0
       AND r.rate_email_time IS NOT NULL
       AND r.total_rating_count IS NOT NULL
       AND cr.rating_date < Curdate()
       AND cr.rating_date > Date_sub(Curdate(), INTERVAL 7 day)

How to convert  this query to yii ?
Thanks in advance.
Comment: You can run mysql statements directly in Yii. But if you would like to use the active record approach, you can consult Yii's doc on [relational active records](http://www.yiiframework.com/doc/guide/1.1/en/database.arr).
Comment: One issue i don't understand. For complex queries with multiple joins, active record is slower than DAO in any benchmark. Even yiis guide mentions it. As far i did long ago, i always found it a second slower. But still people opt for active record.... Am i missing something here? Even query builder is faster than AR.
Answer: "itachi"  answer's right, but if you are looking for in activerecord way...
model: UserHeader
relations:
'activeCustomers' => array(
     self::HAS_MANY,
     'Customer',
     'customer_user_id',
     'condition' => 'activeCustomers.rate_auto_approve=0
                  AND activeCustomers.rate_email_time IS NOT NULL
                  AND activeCustomers.total_rating_count IS NOT NULL'
),

model: Customer
relations:
'lastWeekRatings' => array(
     self::HAS_MANY,
     'CustomerRating',
     'customer_user_id',
     'condition' => 'lastWeekRatings.rating_date < CURDATE()
        AND lastWeekRatings.rating_date > DATE_SUB( CURDATE(), INTERVAL 7 DAY )'
),

and the below code returns the MODEL objects as same as your query. ( I haven't tested it )
$useremails = UserHeader::model()
     ->with('activeCustomers', 'activeCustomers.lastWeekRatings')
     ->findAll(array(
           'select' => 't.email'
      ));
print_r($useremails);

Comment: @ElsonSolano,  findAll() always return an array(or arrayaccess object). you can loop through foreach ($useremails as $userHeader)  and you can access fields as '$userHeader->email' and the relations '$userHeader->activeCustomers' this is list of Customer records  and '$userHeader->activeCustomers->lastWeekRatings' this is list of CustomerRating objects.
Comment: How to we access those data using foreach statement?
Answer: USE DAO (data access object)
MODEL

public function test(){
        $sql = "SELECT t.email
            FROM otz_user_header t
            JOIN otz_customers r ON t.user_id = r.customer_user_id
            JOIN otz_customer_ratings cr ON cr.customer_user_id = r.customer_user_id
            WHERE r.rate_auto_approve =0
            AND r.rate_email_time IS NOT NULL
            AND r.total_rating_count IS NOT NULL
            AND cr.rating_date < CURDATE( )
            AND cr.rating_date >DATE_SUB( CURDATE( ) , INTERVAL 7
            DAY )";

        return Yii::app()->db->createCommand($sql)->queryAll();
            }

query joining three tables yii


javascript alert block page loads

Question: My client wishes to show an alert when entering a web page.
However, an alert blocks further loading of the page until "Ok" is clicked, and the page needs to load in the background while the alert is displayed.
One solution would be to use a custom alert using HTML and CSS, but this is not answering the client's needs.
Is there a solution using 'core javascript' or jQuery to allow the page to load while the alert is displayed?
Thanks.
Comment: Why not just wait that the page is loaded to display the alert?
Comment: I understand... So you could make a custom alert that looks exactly the same as the native alert :)
Answer: You should run it through a setTimeout:
setTimeout(function() { alert('hello world'); }, 1);

This is shown here:
Is there a JavaScript alert that doesn't pause the script?
Comment: This is not working: http://jsfiddle.net/g33Et/   Javascript is a single thread language
Comment: Actually `alert` is executed after the page has been parsed: [jsFiddle](http://jsfiddle.net/24mnG/2/).
Comment: Seems great then, but could you provide a link to see it working?
Comment: @FunKy  Your fiddle doesn't show any multi threading, it only show that you alert after few ms. This as nothing to do with the question. See my jsfiddle, this is how we should expect multi threading to work: when alert() display, console.log() should still works, which is obviously not the case
Comment: @roasted That's what he wanted. He wanted an alert to show up, and in the meanwhile the rest of the page to load. If you notice you can tell you see the text before clicking the ok. Check this to see the difference:
http://jsfiddle.net/xfunky/WcLS6/2/
Comment: @DipeshParmar  do you see what i see in your jsfiddle? When alert is displaying, UI is blocked!  Just use the 'run' button and you should understand what i'm talking about
Comment: @roasted i am sorry but i can see site is loading in back ground...may be i am using Firefox that's why i am seeing overlay. But as of now this did the trick..
Comment: @DipeshParmar  That's true, using FF the alert is not blocking! Well, this is quite new for me! Seems like FF implement some kind of web workers, really interesting!  Thx guys!  Of course, this is not cross browser.
Comment: @roasted Works on chrome for me. Just have to check for IE compatablity
Comment: @FunKy  in chrome (win7) and IE the iframe is not loaded. The request is done of course because the delay of the timeout but the UI is not updated until the alert dialog is closed. Could you confirm it on your side?
Comment: @roasted I'm running linux, so no IE, but the Chrome works just like the Firefox.
Comment: @roasted I just now understood what you said about the iframe, SORRY!! It doesn't load for me either, the request is sent but nothing loads. Very odd. - Screenshot : http://oi42.tinypic.com/2qau4k7.jpg
Comment: This is an interresting article from John Resig: http://ejohn.org/blog/how-javascript-timers-work/
Comment: this obviously only works if the other part of the script needs less than 1ms to execute. the alert is still blocking as soon as it is called.
Answer: EDIT
see @FunKy's answer for a workaround in Firefox.  (really interesting!)

Simple answer is no, it's not possible!
Reason is native alert() dialog is UI blocking and javascript is a single thread language.
You have to use a customized dialog message.
But, if some ajax request are done just before blocking UI, when alert() dialog is closed, the ajax response will/should be available. So, you still can make some ajax request just before showing alert.
Comment: @FunKy No, i cannot see how this could work. Webworkers could be a solution but its not really still implemented
Comment: It works, however I haven't heard of Web Workers until now. Seems promising.
Answer: You can use a custom dialog box instead of an alert box (which block page load). For exemple, Jquery UI Dialog is easy to use (but there are many plugins which do exactly the same thing).

javascript alert block page loads


Why results of map() and list comprehension are different?

Question: The following test fails:
#!/usr/bin/env python
def f(*args):
    """
    >>> t = 1, -1
    >>> f(*map(lambda i: lambda: i, t))
    [1, -1]
    >>> f(*(lambda: i for i in t)) # -> [-1, -1]
    [1, -1]
    >>> f(*[lambda: i for i in t]) # -> [-1, -1]
    [1, -1]
    """
    alist = [a() for a in args]
    print(alist)

if __name__ == '__main__':
    import doctest; doctest.testmod()

In other words:
>>> t = 1, -1
>>> args = []
>>> for i in t:
...   args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
...   args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
...   args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]

Comment: For those like me read the question but don't notice any problem at first: note the `[-1, -1]`!  Essentially `lambda i: ...` in a loop doesn't capture the current value of i.
Comment: related from Python FAQ: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result)
Answer: They are different, because the value of i in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in f.
By that time, i is bound to the last value if t, which is -1.
So basically, this is what the list comprehension does (likewise for the genexp):
x = []
i = 1 # 1. from t
x.append(lambda: i)
i = -1 # 2. from t
x.append(lambda: i)

Now the lambdas carry around a closure that references i, but i is bound to -1 in both cases, because that is the last value it was assigned to.
If you want to make sure that the lambda receives the current value of i, do
f(*[lambda u=i: u for i in t])

This way, you force the evaluation of i at the time the closure is created.
Edit: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope.
Comment: @S.Lott: Ordinary functions in Python are not that different. `def f(): return i` You don't know what `i` really is regardless function or lambda is considered.
Comment: In Python3, ["the loop control variables are no longer leaked into the surrounding scope."](https://docs.python.org/3.0/whatsnew/3.0.html#changed-syntax)
Comment: Lambdas are evil because it isn't clear what what runtime context really is.
Answer: The lambda captures variables, not values, hence the code
lambda : i

will always return the value i is currently bound to in the closure.  By the time it gets called, this value has been set to -1.
To get what you want, you'll need to capture the actual binding at the time the lambda is created, by:
>>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]
[1, -1]

Answer: Expression f = lambda: i is equivalent to:
def f():
    return i

Expression g = lambda i=i: i is equivalent to:
def g(i=i):
    return i

i is a free variable in the first case and it is bound to the function parameter in the second case i.e., it is a local variable in that case. Values for default parameters are evaluated at the time of function definition.
Generator expression is the nearest enclosing scope (where i is defined) for i name in the lambda expression, therefore i is resolved in that block:
f(*(lambda: i for i in (1, -1)) # -> [-1, -1]

i is a local variable of the lambda i: ... block, therefore the object it refers to is defined in that block:
f(*map(lambda i: lambda: i, (1,-1))) # -> [1, -1]


How to submit a form OnKeyPress with Javascript?

Question: I want to make a form like this, and i want to post the form - with javascript - in all the keydowns.
<form action="{$formaction}" enctype="multipart/form-data" method="post">
<input type="text" name="n">
<input type="password" name="pw">
<button name="in" type="submit">enter</button>
</form>

please tell me how to do this.
Answer: <form onkeydown="this.submit();">

</form>

Answer:

Comment: Go with matt's solution, it's the cleanest. however i doubt the practical use.
Answer: If you do that, the page will reload, just as if you were clicking the submit button.
What you probably want is to attach an onkeydown handler to the password field and submit key presses via AJAX.
For an example look at one of javascript auto-suggest libraries, e.g. AJAX Auto Suggest.
Comment: Yep, but i wanted to try it without ajax. :)  Its just a login form and i want to save some cap from the server. Anyway its not workin as i want to so i have to do it with ajax :)


Complex limit using $\delta$-$\epsilon$

Question: I'm just starting my complex limits and this was the limit I needed to prove $\lim_\limits{z\to z_0}\Re(z)=\Re(z_0)$ proceeding with the standard process $|\Re(z)-\Re(z_0)|<\epsilon$ and $|z-z_0|<\delta$ Using the fact that $\Re(z)=\frac{z+\bar{z}}{2}$ we get $\left|\frac{z+\bar{z}}{2}-\frac{z_0+\bar{z_0}}{2}\right|\implies\left|\frac{z-z_0+\overline{z-z_0}}{2}\right|<\epsilon$ at this point I did not know what to do, I remembered in previous $\delta-\epsilon$ proofs I put $\epsilon$ in terms of $\delta$. That doesn't make sense in this case because we get $\left|\frac{\delta+\bar{\delta}}{2}\right|<\epsilon$ which means $\left|\Re(\delta)\right|<\epsilon$. How do I proceed?
Comment: Triangular inequality ?
Comment: Do you know that Re is real-linear and hence continuous?
Comment: An alternative way could be to note that $|z| \geq \sqrt{(\Re(z))^2} = |\Re(z)|$ and apply $z \mapsto z - z_0$.
Answer: Hint: Try to show that $|\Re(z)-\Re(z_0)|\leq |z-z_0|$.
Answer: $\newcommand{\R}{\operatorname{Re}}\newcommand{\I}{\operatorname{Im}}$
\begin{align}
\left|\R (z) - \R(z_0)\right| & = \sqrt{(\R(z) - \R(z_0))^2} \\[10pt]
& \le \sqrt{(\R(z) - \R(z_0))^2 + (\I(z) - \I(z_0))^2} = |z-z_0|.
\end{align}

Complex limit using $\delta$-$\epsilon$


Google Sheets Query Works with Contains but not with Matches

Question: I can't figure out why my query with Matches does not work while it works fine with contains.  I want to eventually pipe additional things into the match but need it to work first.
Contains: =QUERY(Raw!A2:P,"SELECT * WHERE K contains '<m>, 5/2/2020' ",0)
Matches: =QUERY(Raw!A2:P,"SELECT * WHERE K matches '.*<m>, 5/2/2020.*' ",0)
it semi-works when I remove/change the 5 but doesn't return all the matches... the sample data provided won't allow testing but I tested with 2,3,4,6 for example:  =QUERY(Raw!A2:P,"SELECT * WHERE K matches '.*<m>, 3.*' ",0)
Sample data for one cell in column K:
Keith <k>, 5/2/2020: @Me: Thank you
_______________________
Keith <k>, 5/2/2020: @S: this is some text
_______________________
Mo <m>, 5/2/2020: @Me: more text is here
_______________________
ME <me>, 5/6/2020: text is here
_______________________
Jonathan <j>, 5/6/2020: @Me: Thank your
_______________________
Jonathan <j>, 5/6/2020: @S: text

Comment: Provide sample data as text
Comment: Provide "sample": dummy strings that prove that the issue actually exists. See [mcve]. If I were to copy your text to a sample column with your formula, I should be able to reproduce the problem, which you claim exists.
Comment: I'm stumped then... my sheet keeps sayin query completed with empty output.
Comment: Reproducible if put in "one cell"
Comment: is it possible the code is executing 5/2/2020 as a math equation? so it's looking for .0012376 instead of the actual text of 5/2/2020?
Comment: No. It's the absence of single line regex flag support`(?s)`
Answer: Query's matches in Google sheets web app(unlike  official mobile apps) doesn't seem to support regex flags like single line mode: (?s). Consider creating a issue with a link to this post in

Google Visualization issues

Google sheets > Help > Help sheets improve.

Workarounds:

Query function seems to run client side unlike other functions. If supported use, (?s) like:
=QUERY(Raw!A2:P,"SELECT * WHERE K matches '(?s).*<m>, 5/2/2020.*' ",0)

If not, simulate single line mode using (.|\n) (any character or new line):
=QUERY(Raw!A2:P,"SELECT * WHERE K matches '(.|\n)*<m>, 5/2/2020(.|\n)*' ",0)

Use contains instead. contains with OR should simulate matches' pipe | joining.
=QUERY(Raw!A2:P,"SELECT * WHERE K contains "&JOIN( " or K contains ","'<m>, 5/2/2020'" ,"'<k>'")&"",0)

Comment: Yeah I'm just going to use contains.  The idea was to be able to enter a start and end date and have the query pull all entries from a user with those dates so if you specified say 5/2/2020 to 5/9/2020 for user  it would look for , 5/2/2020 or , 5/3/2020 or , 5/4/2020 or ... , 5/9/2020.  based on [research](https://infoinspired.com/google-docs/spreadsheet/multiple-contains-in-where-clause-in-query) i thought building a  textjoin to create a string to pipe them together would be best but guess not.


Jtable com valor monetário em uma unica coluna

Question: Buscando implementar uma formatação de valor monetário em uma jtable, tentei usar a pergunta do Rafael Chaves como base e consegui fazer o codigo abaixo.
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;

public class PrincipalTabelaValor extends JFrame {

    private final JTable table;
    private final int id1 = 1;
    private final int id2 = 2;
    private final int id3 = 3;
    private final double qtd1 = 10.10;
    private final double qtd2 = 9.20;
    private final double qtd3 = 8.30;
    private final double vl1 = 5.50;
    private final double vl2 = 6.51;
    private final double vl3 = 7.52;

    public PrincipalTabelaValor() {
        super("Tabela de Cadastro de Produtos");

        // constructs the table
        String[] columnNames = new String[]{"ID", "Descrição", "quantidade", "Preço"};
        Object[][] rowData = new Object[][]{
            {id1, "TOMATE", qtd1, vl1},
            {id2, "BANANA", qtd2, vl2},
            {id3, "UVA", qtd3, vl3}
        };

        table = new JTable(rowData, columnNames);
        table.setDefaultRenderer(Object.class, new CONTabelaProduto());

        add(new JScrollPane(table));

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(640, 150);
        setLocationRelativeTo(null);
    }

//  CONTROLA A TABELA
    public class CONTabelaProduto extends DefaultTableCellRenderer {

        private final NumberFormat FORMAT = NumberFormat.getCurrencyInstance();

        @Override
        public Component getTableCellRendererComponent(JTable jtable, Object conteudo, boolean linhaSelecionada, boolean hasFocus, int linha, int coluna) {
            super.getTableCellRendererComponent(jtable, conteudo, linhaSelecionada, hasFocus, linha, coluna);

            if (linha % 2 == 0) {
                setBackground(new Color(102, 102, 255, 80));
            } else {
                setBackground(new Color(102, 102, 255, 20));
            }

            if (linhaSelecionada) {
                setBackground(new Color(0, 0, 102, 100));
            }

            if (conteudo instanceof Double) {
                setText(FORMAT.format(conteudo));
            }

            jtable.setRowHeight(25);
            jtable.setFont(new Font("Verdana", 0, 14));
            jtable.setOpaque(false);
            return this;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PrincipalTabelaValor().setVisible(true);
            }
        });
    }
}

Como podem ver, a formatação foi atribuída também na coluna "quantidade", e eu gostaria de atribuir essa formatação apenas na coluna "preço".
Tentei seguir o exemplo do Rob Camick criando a class abaixo.
import java.text.NumberFormat;
import javax.swing.SwingConstants;

public class NumberRenderer extends FormatRenderer {

    public NumberRenderer(NumberFormat formatter) {
        super(formatter);
        setHorizontalAlignment(SwingConstants.RIGHT);
    }

    public static NumberRenderer getCurrencyRenderer() {
        return new NumberRenderer(NumberFormat.getCurrencyInstance());
    }
}

E chamando a class com
jtable.getColumnModel().getColumn(3).setCellRenderer(NumberRenderer.getCurrencyRenderer());

Mas acaba sobrescrevendo o background definido.

Gostaria de verificar se existe uma forma de atribuir esse tipo de formatação sem que sobrescreva a definição de background.
Comment: Sua tabela so tem 4 colunas?
Comment: A tabela original tem bem mais colunas, criei esse código apenas para demonstrar de for simples o dilema que estava passando.
Comment: @CarlosHeuberger concordo, esse trecho não haveria necessidade de estar ai, poderia ser definido direto na classe principal, junto com a propria tabela.
Comment: Criei assim porque minha `DefaultTableCellRenderer` fica em uma class separada, mas obrigado pela dica.
Answer: A solução mais simples neste código é, dentro do seu DefaultTableCellRenderer pegar o índice da coluna preço ao invés do tipo da coluna, e quando o indice for o mesmo, aplicar a formatação:
if (coluna == 3) {
    setText(FORMAT.format(conteudo));
}

ou se a coluna preço for sempre a última, independente da quantidade de colunas:
if (coluna == (jtable.getColumnCount()-1)) {
    setText(FORMAT.format(conteudo));
}


Roundness in Taxicab Geometry

Question: I was just wondering whether circles are considered "round" still in taxicab geometry. I know that "roundness" is probably not a well-defined term and I know what a circle /appears/ to look like in taxicab geometry, but the question is deeper than that. From within the taxicab geometry, would the notion of "roundness" as intuited in Euclidean geometry become meaningless or different? From within the perspective of the geometry, a circle is still a circle and it might therefore still be round.
In lieu of this question, I have a few others. Could we still work with curvature (differential geometrically)? If so, and if it has the same definition and we base roundness on curvedness, one might (I think) still be able to call circles "round" in taxicab. Also, in taxicab, can there be a shape that /appears/ to be like a circle (in Euclidean)? It would not be a circle, but if roundness is understood that way, then a taxicab circle would not be round.
Thank you!
Comment: How would you define a circle?  If it is those points a given distance from a given centre, then you will get a rotated square.
Comment: Yes and I do, but if we intrinsically define roundness to be "circular", then the problem might still persist.
Comment: Unless you meant to respond to my last question (an apparent circle in taxicab geometry), in which case, it is not a circle, it just looks like one to Euclidean thinkers.
Answer: One possible definition of "round" would be "convex and without corners", where the definition of "corner" would be "discontinuity in the speed vector" for some parametrization. So what about this speed vector in a taxicab circle? Even there, you go one direction and the suddenly go a different direction. I can think of no definition which would still consider this continuous.
So I'd say no, a circle in taxicab geometry is not round.
Comment: That seems reasonable and I agree. Thank you!

Roundness in Taxicab Geometry


Help with multiple voice harmonization

Question: I recently started composing using software, before that I only used guitar and memory, so this opened up lots of new possibilities with voices, intervals, ranges, etc. I started composing a chorale based on a children's song's melody, which is EFEFGG x2 AGAGAFF GFGFEE in a rhythm of 4 eighths and 2 quarters.
In the third part my idea was to have the 2 altos, one doing the quarter note pitches (G, G, F, E) and the other doing a chromatic ascend (B, C, C#, D) in half notes while the soprano alternates the eighth note pitches in quarters. I want the bass and tenor to have several voices constantly overlapping each other and creating a wall of sounds with m2,M2,m7 and M7's, or just sharp dissonances, flowing in and out of whatever seems appropriate.
I've never harmonized >2 voices, so I don't know how to approach this. In the current state (sheet music and flac file {+embedded player}) in part III bars 1 and 5 are examples of where it's decent, the others kinda of work on their own, as in, tenor and bass separated, but not tog
Comment: Any specific questions? Otherwise the answer is too broad
Comment: How do I approach the task? I'm not asking somebody to write it for me, just advice where to begin. Each measure has 4 notes, each one can have different duration to simulate the flowing in&out of overlap I'd like, but in the end I just have a lot of subsequent notes pressed together and the melody is lost.
I noted what chords the alt and soprano are playing to see if I could that would help from a scale-standpoint, what notes would fit; but deciding the duration is the daunting part.
Comment: I don't like simplicity for the most part, I don't want to repeat the notes in the upper voices unless for melody's sake, nor would I like simple 3-note chords. I've never studied counter-point, so if that would help, say so. I'd like only a push in the right direction.
Comment: FYI - I got a lot of popups on that zippyshare link (no ad-blocker on this computer).  For sharing your compositions, I would recommend [SoundCloud](https://soundcloud.com/) (lets you enable downloads), or [Clyp.it](https://clyp.it/) if you don't want to make an account.
Answer: This is quite opinion-based, so these are not universal rules, but here are some principles that match how I think about harmony.  I apologise if some/all are either too obvious or completely nonsensical!

General principles, and complexity

It's all about how easily the listener's brain can intuitively understand the chord progression.  Too easily understood and it's boring, but too confusing and it just dissolves into a pile of notes instead of music.  The optimum amount of challenge/complexity is a matter of personal preference (and the listener's skill/practice at hearing harmony), but it's usually good to keep the level consistent to keep it interesting but not impossible.
The "complexity" a progression sounds is a result of both the chords themselves, and also how smooth/jumpy the transitions are.  You can get away with more discord if the transitions are smooth, and you can get away with a more drastic transition if the chord you're transitioning to is more simple/harmonious.

Constructing chords

The most common chords (simple to understand) are majors and minors. Next-simplest are variations/additions (e.g. 2nds/7ths), which can be viewed as borrowing notes from other chords.  Using one of these extra notes hints towards some chord that uses it, so it's smoothest to use notes that are also used in your other chords.
Evenly-spaced notes in a chord will sound rich instead of sparse.  It is better to have the notes slightly crowded together at the top end than the bottom end (because small intervals at low pitches sound "muddy").
Think about the "centre of gravity" of your chord in terms of pitch.  For example, if your soprano line is jumping up or down, then you can counterbalance that motion using the tenors/basses to keep things neutral (a good default), or deliberately move the entire chord to a different register for effect - but it's good to know which one you're doing.
If you are going to have multiple parts singing the same note (or octaves), then it matters which note it is.  Doubling up the root note of the chord will sound the most balanced, doubling up the fifth is OK, and doubling up other notes can sound less "stable".  This is basically a way to hint to the listener which note is most important, so their brain can start forming a chord around it more easily.

Transitions

If your next chord has a clear root note, then your bassline can jump to this root note from any distance and it won't sound awkward.  If your bassline is not going to the root note (because you're using an inversion, or your chord is too weird to have a clear root) then it is best for the bass part to not jump a long way, or the listener will have trouble tracking the change.
If two parts are an octave or a perfect fourth/fifth apart, moving them in parallel can sound clunky (e.g. if your tenors and basses are an octave apart, then they should not also be an octave apart next time they move).  Octaves and perfect fourths/fifths are (mathematically) the simplest interval, and so moving them together can make the transition sound too simple.
Having some notes kept constant makes a transition smoother.  The shared notes keep the transition more comprehensible even if the chords themselves are bizarre.  (Remember - the smoother your transitions, the more discord you can get away with - see point #1.2.)  For chords with few/no notes in common, you can artificially produce this by moving some notes early or late (which can also add some extra discord/interest for the short period until it is resolved).

Hopefully, these guidelines don't limit the actual chord progressions you use - instead they're about how to spread out the notes from your chords across multiple parts in a way that makes sense to the listener.
While I personally work on the piano/keyboard, and I find it very convenient for planning out harmonies, I don't think it's necessary.  If you work out what chords you want to play (e.g. using the guitar), then you can look at the notes that are actually in that chord, then lay the notes from the chord out as a separate step (and that's how I used to do my harmony work at school). :)
Answer: Do you have access to a music keyboard, either that can play its own sounds or that can generate sounds via your software?  I find trying out different sequences and making notes to myself about the ones that 'work' is the best approach to a task like this.  Since my primary instrument is piano, that's where I work it out.
Sounds to me like you're on the right track so far.  I do think some study of 16th century counterpoint (Fuchs) might help, though you need to realize that that is built around avoiding or resolving dissonances rather than emphasizing them, which it sounds like you would like to do.  (I don't think 18th-century style would help though.)
The tune itself is simple, and while you say you want to avoid the simple in working out your composition, I think you need to make it at least SEEM simple in order to maintain the overall atmosphere.  What follows is NOT advice: you need to work it out your own way, in your own musical language, in your own style.  But what I would do if it were me would be to make the accompanying rhythm and harmony gradually more and more complex, and more and more dissonant, until a climax is reached, and then go back the other way, until more and more simplicity is reached, ending as simple as the tune itself.  But that's just me.  You need to be you.
If you're into classical at all, I'd suggest studying the works of William Walton and William Schuman, as they both excel at working smoothly from assonant to dissonant and vice versa.
Comment: No MIDI keyboards, sadly. And guitar is too different of an instrument to be used for the purposed, I think. Would you recommend getting one for future composing ease?
I'll study up some counter-point for guidelines and the works both Williams for examples and perhaps inspiration.
Otherwise, I reduced all durations to 8ths and slowly stared working out which harmonies can continue, and which ones should end, still kind of hard to do everything by ear, but it is supposed to be the most complex part. Ah, I'll post the result here whenever it feels finished.

Help with multiple voice harmonization


How to take a screenshot in your App and publish it on facebook?

Question: I'm trying to use facebook within my App by posting a screenshot of my App on my wall.
I already made the functions for taking a screenshot
UIGraphicsBeginImageContext(self.view.bounds.size);
            [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

and for posting stuff on my facebook wall with an icon, title and small description.
- (void)postToWall {

    FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
    dialog.userMessagePrompt = @"Enter your message:";
    dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"%@ share's a photo\",\"href\":\"mywebsite.com/\",\"caption\":\"%@thinks this is a nice photo\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"mywebsite.com/icon.png\",\"href\":\"mywebsite.com/\"}]}",
                         _facebookName, _facebookName];

    dialog.actionLinks = @"[{\"text\":\"Get My App\",\"href\":\"http://itunes.apple.com//\"}]";
}

Any suggestions of how to put my screenshot within the postToWall method? Thanks in advance!
Answer: It seems like you can't do this completely via Facebook. You should look at photo sharing sites for this. First upload your image to that site and get the link. Then share it via this method.
Edit
I am not saying the photo upload isn't possible. It just isn't possible to post a photo to the wall along with a link to your app without uploading it first.
Answer: Using Facebook's SDK for iPhone, it is possible.  You will need to construct and argument block (NSDictionary) and send that to the your validated Facebook session.
In the snippet here, "session"  is of type Facebook * defined in Facebook.h of the SDK.
NSMutableDictionary *args = [[[NSMutableDictionary alloc] init] autorelease];
[args setObject:captionText forKey:@"caption"];
[args setObject:messageText forKey:@"message"];
[args setObject:UIImageJPEGRepresentation(yourImage, 0.7) forKey:@"picture"];

[session requestWithMethodName:@"photos.upload" andParams:args ndHttpMethod:@"POST" andDelegate:self];


Sub-tables no Bootstrap

Question: Estou criando uma table convencional, que quando clicada no no nome do grupo ela mostra uma sub-tabela contendo as mesmas colunas e refatorando os resultados:
ESTADO NORMAL:
 GRUPOS    QUANTIDADE
|  GA   |  |  1000  |
|  GB   |  |  1600  |

QUANDO CLICADA NO TITULO DO GRUPO:
 GRUPOS    QUANTIDADE
|  GA   |  |  1000  |
| CLI01 |  |  500   |
| CLI02 |  |  500   |

|  GB   |  |  1600  |
| CLI01 |  |  800   |
| CLI02 |  |  800   |

A PARTIR DE UMA ESTRUTURA DA TABLE ABAIXO, O QUE É NECESSÁRIO APLICAR PARA QUE APAREÇA AS SUB TABELAS E QUE ELAS TENHAM ESTE EFEITO DE 'SHOW/HIDE'?

        GRUPOS
        QUANTIDADE

        GA
        1000

        GB
        1600

Answer: Nao sei se você quer tipo uma treetable, mas vai seguir o mesmo contexto.

$('ul li span').on('click', function(){
        $('.show').slideToggle();
});
.show{
    display: none;
}

            A

VVVV

Segue esse exemplo, caso nao funcione, ou nao seja isso que queira, poste seu codigo atual, que partimos dele.
Comment: É exatamente o que eu preciso. Eu só não estou conseguindo colocar os trechos que você comentou em uma página que funcione. O que entra dentro de ? Onde eu coloco o ".show{ display: none; }"
Comment: Consegui :) muito obrigado.

Sub-tables no Bootstrap


Bulk create with multi-table inheritance models

Question: I'm using multi-table inheritance models.
from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

class Cinema(Place):
    sells_tickets = models.BooleanField(default=False)
    sells_popcorn = models.BooleanField(default=False)

class Coffee(Place):
    sells_tea = models.BooleanField(default=False)

I have a view that creates several different models:
items = [
    Restaurant(...),
    Restaurant(...),
    Restaurant(...),
    Cinema(...),
    Cinema(...),
    Coffee(...),
    Coffee(...),
    # + 1.000 other items
]
for item in items:
    item.save()

Obviously, this is really inefficient since it creates a lot of queries. Unfortunately, Django doesn't provide a bulk-create method for multi-table inheritance yet (there is an open pull request for it). What is the best way to optimize this code? Do I have to write a raw SQL query or is there another way?
Comment: @harshilsuthar Please read the question in full. OP already stated that he researched his options and that bulk_create does not work for his use case.
Comment: refer this https://docs.djangoproject.com/en/3.1/ref/models/querysets/#bulk-create
Answer: I solved it by inspecting the implementation of bulk_create. Underlying it uses the InsertQuery class to generate the SQL INSERT INTO statement. IMHO this is much cleaner and shorter than writing a raw SQL query.
# Create all concrete models at once
items = Place.objects.bulk_create(items)

# Group items by their model
item_mapping = defaultdict(list)
for item in items:
    item_mapping[type(item)].append(item)

# Create a bulk insert for each model
for model, items in item_mapping.items():
    fields = model._meta.local_concrete_fields
    query = sql.InsertQuery(model)
    query.insert_values(fields, items)
    query.get_compiler(connection=connection).execute_sql()

Comment: Hi. Only works for PostgreSQL, because other database engines do not return objects with generated primary keys as return from bulk_create. It Will only work if you explicitly define a primary key for the parent model and handle primary keys manually.


Android XMPP client does not connect to Openfire server

Question: I have configured openfire server on my laptop running windows7. Pandion and Spark desktop clients are working fine on the localhost. Tested it thoroughly with multiple users.
Laptop is connected to a wifi network.
I am trying to connect to the localhost openfire from Xabber client installed on Samsung galaxy pop running Android OS. Mobile is connected to the same wifi network.
<code>http://localhost:9090/login.jsp?url=%2Findex.jsp

I am able to access this admin url in mobile browser.
</code>
But none of the xmpp clients are able to connect to localhost openfire.
Configuration done-
server- localhost
port- 5222
username and password are exactly same as provided in Spark desktop client.
It would be great to know if someone has the solution.
Thanks.
Answer: You cannot use localhost in the android client to connect to your laptop. And i do not believe that using localhost in an android browser would connect to a server on your laptop. You have to use the local ip address of the server to connect. Often something like 192.168.#.#.


class with a pointer member

Question: class Block
{
    Block *on;
    char *name;
    bool white;
    bool clear;
    bool onTable;
public:
    Block(char *nm);
    Block(const Block &ob);
    void setName(char *nm);
    char *getName() const ;
    bool isClear();
    void setColor(int colour);
    bool isWhite()const;
    bool isOnTable();
    Block *getOn();
    void putOn(Block &block);
    void putOnTable();
    void takeFromTable();
    void makeClear();
    void flipColor();
    void print();
};

I have class like this. Why the declaration of *on pointer like Block *on? Don't we have to write int, float or something like that first? What is the purpose?
Block *getOn() function out of the class declaration is like this;
Block *Block::getOn()
{
    return on;
}

I need to return on pointer in this code. Is there any other way to do that?
Comment: `on` is a pointer to an instance of type `Block`.  I strongly suggest reading a [good introductory book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)...
Comment: If you didn't make it a pointer, it would be infinite recursion to figure out the size of your class.
Answer: Block * on declares on as a pointer to an object of type Block. When you write a class definition (in this case defining class Block), you're really inventing a whole new datatype (in this case Block), describing what kind of data it contains as well as what operations are possible.
Your getOn() code looks correct.
Answer: If you don't want to manage raw pointers (as I do),
prefer smart pointers instead.
Ex:
     // declare type
    typedef std::shared_ptr<Block> BlockPtr;

    class Block
    {
        BlockPtr on; // using smart pointer instead of raw pointer
        char *name;
        bool white;
        bool clear;
        bool onTable;
    public:
        Block(char *nm);
        Block(const Block &ob);
        void setName(char *nm);
        char *getName() const ;
        bool isClear();
        void setColor(int colour);
        bool isWhite()const;
        bool isOnTable();
        BlockPtr getOn(); // returning smart pointer
        void putOn(Block &block);
        void putOnTable();
        void takeFromTable();
        void makeClear();
        void flipColor();
        void print();
    };

    // initializing on
    on = BlockPtr(new Block);

class with a pointer member


Why won't my VS2012 recognize modified files on disk and reload?

Question: I've been away from Windows and Visual Studio for a few years.  Now I have VS2012, and I notice that it fails to recognize that a file has changed on disk (i.e. by a different editor).  In fact, even if I hit the refresh button on the Solution Explorer window, it still doesn't reload the file.  I can close the window and reopen it -- still no luck.  I thought "gosh, I hope I don't have to close and reopen the solution each time!", but it turns out even THAT doesn't do the trick.
Its as if VS is caching old copies of files and cannot imagine that someone might use something other than VS to modify them.
These are just local files, no network issues involved.   I must be missing an understanding of some major new "feature", yes?
--- Edit: -----
Ok, here's some progress.   I've been using the VsVim extension to have a vim-compatible keymap.   On a hunch, I disabled it, restarted VS, and found the problem solved.  Then, I re-enabled it, and the problem is still solved.    So the mystery remains, but not the problem.
Comment: Interesting.  I've never used that plugin, but traditionally editors like Vim do retain a separate version of the file for persistent auto-save without overwriting the actual file until explicitly told to do so, long undo chains, things like that.  Similar to the system file that Office apps make when opening a document.  So technically it probably *was* a "different file" but one that was being obscured by the plugin and probably hidden by Windows Explorer.
Comment: Are you sure that file is being modified?  The feature to detect an external modification and reload the file is still there.  And if you close and re-open the file or even the entire IDE, it would definitely load whatever is the current content of the file.  It really sounds like the external editor either isn't saving or is modifying a different file.
Comment: Well I thought of that, so I removed the file entirely from the VS solution, and added it back in.  When I do that, it _does_ show the new content.  I've also loaded the file with several other editors, and they all agree with the new content.  Only VS seems stuck on keeping old versions somewhere.
Comment: Ok, here's some progress.   I've been using the VsVim extension to have a vim-compatible keymap.   On a hunch, I disabled it, restarted VS, and found the problem solved.  Then, I re-enabled it, and the problem is still solved.    So the mystery remains, but not the problem.  Thanks for responding!
Comment: Yeah, I'm thinking maybe the VsVim plugin's state got into a strange twist.  I have very little experience with it.
Answer: I don't have VS2012 (I went up to 2005), but from what I remember, this is configurable from the IDE. In VS2005 go to the menu, choose Tools, then Options, then Documents, then you'll see the options to detect when files are changed externally, and to auto-load files changed externally. I think in VS2012 it'll be similar.
Comment: Ok, here's some progress.   I've been using the VsVim extension to have a vim-compatible keymap.   On a hunch, I disabled it, restarted VS, and found the problem solved.  Then, I re-enabled it, and the problem is still solved.    So the mystery remains, but not the problem.  Thanks for responding!
Comment: Now that the core problem is solved, your suggestion did indeed take me to the next stage: having it auto-reload.  That option in 2012 is apparently the same in the version you recall.
Comment: In VS 2012 it's the same: Tools > Options > Environment > Documents -> "Detect when file is changed outside the environment" and "Auto-load changes, if saved" checkboxes.
Comment: Also, according to my experience, you get the warning from visual studio, if the file is actually opened in the IDE at the time when it was changed by an external editor. When it is not open (but part of the solution), then there's no reason for warning: next time you open it, you open up the changed file anyway.


How do I get a print output as a list from a manipulated loop?, Or, get same result without print?

Question: I have ten tables named t1,... t10. I would like to use variables for name of tables . The codes are:
for i in range(1,11):
    print("t",i, sep='', end=', ')

 Output is: t1, t2, t3, t4, t5, t6, t7, t8, t9, t10,
 I will use like this: im.execute("delete from ' + b[1] + '"). So,
 I need a list b=["t1", "t2", ..... "t10"]

How do I get this output as a list?
Answer: You could just use a list comprehension with similar logic to generate the list you are looking for.
For example:
items = [f't{i}' for i in range(1,11)]
print(items)
# OUTPUT
# ['t1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9', 't10']

# You could also do ['t{}'.format(i) for i in range(1,11)] if you are pre python 3.6

Answer: ts = []
for i in range(1, 11):
    ts.append('t{}'.format(i))

Or, in one line:
ts = ['t{}'.format(i) for i in range(1, 11)]


Centos 8 in AWS - PHP install error

Question: When i try to install PHP with Remi repository i get the below error
<code>         dnf module list php
        Remi's Modular repository for Enterprise Linux 8 - aarch64
        Errors during downloading metadata for repository 'remi-modular':
          - Status code: 403 for http://cdn.remirepo.net/enterprise/8/modular/aarch64/mirror (IP: 188.8.131.52)
          - Status code: 403 for http://cdn.remirepo.net/enterprise/8/modular/aarch64/mirror (IP: 184.108.40.206)
        Error: Failed to download metadata for repo 'remi-modular':
    Cannot prepare internal mirrorlist: Status code: 403 for
http://cdn.remirepo.net/enterprise/8/modular/aarch64/mirror (IP: 188.8.131.52)
</code>
If visit the page not found i get an error called
Only mirrorlist are served.
Use https://rpms.remirepo.net/ for content.
Below is how i installed the Remi
<code>dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
yum update
dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
</code>
Answer: The Remi repository packages are currently built only for the x86_64 architecture, and not for aarch64. You will not be able to use remi packages on AWS Graviton instances until Remi chooses to build the packages for the aarch64 architecture.
Comment: DrPixel rebuild some of my RPMs for aarch64, but only for 7, but 8 will probably come later: https://repo.drpixel.fr/
Comment: @RemiCollet You could probably do it yourself without much trouble. I even have a F32 builder on a Raspberry Pi 4 as I only build a few packages.
Comment: See https://github.com/remicollet/remirepo/issues/214 aarch64 is now available for EL-9

Centos 8 in AWS - PHP install error


Does Axios perform SSL verification by default in a React Native/NodeJS environment?

Question: I noticed that while having SSL verification enabled in Postman, endpoints served under certificates issued by R3 fail with the error "SSL verification failed", whereas in a React Native environment if the same call was made using axios the call went through successfully.
Some more digging and landed at the http.Agent and https.Agent options in axios:
https.Agent options image
The default options do not seem to be disabling anything related to SSL verification. But this issue (along with many others) suggest having a problem with SSL verification and having to set rejectUnauthorized param as false while creating a custom https.Agent so that their API calls go through.
From the https.request docs for nodejs, under the examples we can see most of them are pinning certs and there is no option or param to enable a generic SSL verification (like in Postman for example).
In summary,

Is SSL verification disabled by default in axios even when using an HTTPS endpoint? Or is this only applicable in browser environments and driven by the browser's inherent CA verification process?
Do we need to perform certificate pinning to get any kind of SSL verification in a React Native environment?
Answer: As far as I know, Axios does SSL verification by default, but Agent overwrites this. However, in most environments I would not disable it. R3 should not be rejected by postman, sounds like maybe you're using a certificate store that for some reason doesn't include R3.


can't create pull request from bitbucket pipelines

Question: I want to set up a step in my pipelines where I can automatically raise a pull request from develop branch to master branch (as part of the release process). However, I cannot seem to find the solution when using with this REST API pull request . The problem, is because the curl command is running in pipelines environment with bitbucket-pipelines user, and I have no idea what is the password for this user. is this something even possible? like does bitbucket provide its pipelines user password ? I couldn't find anywhere.
Answer: You will need to create an App password for the user that is supposed to raise the pull request. (https://confluence.atlassian.com/bitbucket/app-passwords-828781300.html)
You can then inject username and password as a variable into pipelines. https://confluence.atlassian.com/bitbucket/variables-in-pipelines-794502608.html Make sure to make that variable a secured variable so the password can't be viewed!


Method for finding the number of matrices in $M_2(\mathbb{Z}_3)$ whose determinant is $1$

Question: I just came across a question which asks to find all the $2 \times 2$ matrices in $\mathbb{Z}_3$ whose determinant is $1$. I know that since there are only three elements in $\mathbb{Z}_3$, it is feasible to work out the problem by counting the number of correct combinations of elements. (And, though I'm not sure about my calculations, I think the answer is $20$.)
But what if there were more elements to be looked into? Then surely this pathological process wouldn't come very handy. So my question is...

Is there any shorter method for finding out the answer of this question which also works well in other (general) cases?

Thanks and regards.
Answer: First count the number of matrices with non-zero determinant. Do it column by column: the first column can be any non-zero vector, so that gives you $3^2-1$ possibilities. The second column can be any vector that does not lie in the span of the first (the determinant is 0 if and only if the two columns are linearly dependent), so you have $3^2-3$ possibilities for the second column. So that's 8*6=48 matrices with non-zero determinant.
Now, the determinant function is a surjective group homomorphism from the group of all invertible matrices to $(\mathbb{Z}/3\mathbb{Z})^\times$, so its kernel has size equal to the size of the domain / size of the image, i.e. 48/2=24.
This works in complete generality: the number of invertible matrices in $M_k(\mathbb{Z}/p\mathbb{Z})$ ($p$ a prime number) is
$$
(p^k-1)(p^k-p)(p^k-p^2)\cdots (p^k-p^{k-1}),
$$
and the number of matrices with determinant 1 is therefore that divided by $p-1$.
Comment: That's a brilliant way of doing it. Thanks a lot for helping me out. :-)
Answer: Hint: Let $A_i$ be the set of matrices with determinant $i$.

Show that $|A_i| = |A_j|$ for $i,j \neq 0$
Show that $|A_0| = 3^3+3^2 - 3$.
Show that $\sum |A_i| = 3^4$.

This works for all primes, and becomes a faster way to count the number of matrices.


Ansible `where` clause for "Is those host in that group?"

Question: I'm writing an ansible (v2.9.6) task which should only be run for hosts in a specific group. How do I write a where clause to match that?
when: "'my_group_name' in {{ group_names }}"

gives me the following error
fatal: [hostname1.example.com]: FAILED! => {"msg": "The conditional check ''my_group_name' in {{ group_names }}' failed. The error was: template error while templating string: expected token ',', got 'string'. String: {% if 'my_group_name' in [u'apache_webservers', u'my_group_name', u'webservers', u'ubuntu_servers'] %} True {% else %} False {% endif %}\n\nThe error appears to be in ...

Answer: - name: test playbook
  hosts: all
  vars:
    my_group: openvpn

  tasks:
  - name: debug
    debug:
      msg: 'my_group is: {{my_group}} , group_names are: {{group_names}}'

  - debug:
      msg: 'condition passed'
    when: my_group in group_names

result:
PLAY [test playbook] ************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************************************************************************
ok: [host1]
ok: [host2]

TASK [debug] ********************************************************************************************************************************************************************************************************************************
ok: [host2] => {
    "msg": "my_group is: openvpn , group_names are: ['openvpn']"
}
ok: [host1] => {
    "msg": "my_group is: openvpn , group_names are: ['openvpn']"
}

TASK [debug] ********************************************************************************************************************************************************************************************************************************
ok: [host2] => {
    "msg": "condition passed"
}
ok: [host1] => {
    "msg": "condition passed"
}

tested on ansible 2.9.6
Answer: Start a new play, which can be in the same playbook file.
- name: Deploy thing
  hosts: my_group_name

  tasks:
  - name: Do thing
    debug:
      msg: thing

Not the when condition you asked for. However, more clear as to what is going on, as the play only runs hosts matching the pattern.

Ansible `where` clause for “Is those host in that group?”


Register form breaks after changing submit button value with jQuery

Question: I need to change the submit button value (text) based on the selection made in a certain register form field. I accomplished this by using jQuery:
<code>(function ($) {
$(function() {
$("#edit-field-registrierung-als-und").change(function() {
if ( this.value == "2") {
$("#registersubmit").val("Kostenpflichtig registrieren");
}
else {
$("#registersubmit").val("Jetzt registrieren");
}
});
});
}(jQuery));
</code>
The submit button value changes as expected. But the form is not sent anymore after submitting. The page refreshes and the entered data is still in there. I don't get any error in the console or error log.
I think drupal expects the very term and is 'confused' to get a different one. Does somebody know how to resolve this?
This is my register page: https://my-business-location.com/registrierung
The first field on the page influences the submit button value (option 2).
Comment: That's correct, the action to take on submit is determined by the submit button value. You'll have to change it with Drupal's AJAX API, or the backend won't know how to process the changes you've made
Comment: Ok. Can you explain how this is done with Ajax API? I am no professional coder but try my best. Does it mean that I need to write Ajax code to change the submit button value? Where does this code go, custom module?
Answer: Based on what Clive said and your response regarding the Ajax stuff, I edited your code. I am assuming you only want to change the text of the button for display purposes.
<code>(function ($) {
  $(function() {

    // Create a copy of the button
    $('#registersubmit').after('<input id="new-submit" class="form-submit" value="Jetzt registrieren">');
    // Hide original
    $('#registersubmit').hide();
    // When copy  is clicked, "click" the original
    $('#new-submit').click(function(){
      $('#registersubmit').click();
    });
    // Your code with changed IDs
    $("#edit-field-registrierung-als-und").change(function() {
      if ( this.value == "2") {
        $("#new-submit").val("Kostenpflichtig registrieren");
      }
      else {
        $("#new-submit").val("Jetzt registrieren");
      }
    });
  });
}(jQuery));
</code>
Can't test it as you appear to have the code active right now, but it should work fine in this scenario.
Comment: Awesome, this is exactely what I needed! Many thanks!


Angular fade animation happening at wrong time during load

Question: We have a popup modal in our Angular application which contains, among other things, a  element which should appear, and then fade, when a certain button is clicked.  This all works as expected.  But there is one problem.  When the modal first loads, the  momentarily appears, then fades out.  The behavior is consistent with the  having ng-show set to true, but then set to false at the time the modal is loaded, triggering the fade out transition.
Here is the :
file copied to clipboard

But the varible $scope.copyLinkClicked is set to false when the controller loads, and hence we would expect to never even seen the  being rendered at load time.
Here is the relevant CSS:
.text-fade {
    transition: all linear 500ms;
    opacity: 1;
}

.text-fade.ng-hide {
    opacity: 0;
}

This problem was discussed in this SO question, but no definitive solution was given.  We have pondered turning off the animation for this element, but this may have problems as well.
Any solution which gets the job done within normative usage of Angular would be greatly appreciated.
Comment: try setting default `display:none` and/or use `ng-cloak`
Comment: @charlietfl Of course I will test this, but would hard-coding `display: none` interfere with Angular's ability to show or hide the element later on?
Answer: One quick workaround would be to add another span tag as the parent of your span element. You can then add an ng-if condition to the parent element and use a variable that is set to false initially in the if condition. This would make sure that the child span is not rendered when the page loads and therefore you wouldn't see the animation. You can then set the value of that variable to true on document ready event.
Here is the :
file copied to clipboard

In your controller add the following:
$scope.firstLoad = false;
angular.element(document).ready(function () {
    $scope.firstLoad = true;
});


Externally visible Kubernetes Service on Azure

Question: I am deploying an ELK stack on a Kubernetes(v1.4.5) cluster on Azure. This is the configuration that creates the Kibana Service and Deployment.
# deployment.yml
---
apiVersion: v1
kind: Namespace
metadata:
  name: logging
---
# elasticsearch deployment and Service
---
# logstash Deployment and Service
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: kibana
  namespace: logging
spec:
  replicas: 1
  template:
    metadata:
      labels:
        component: kibana
    spec:
      containers:
      - name: kibana
        image: sebp/elk:521
        env:
          - name: "LOGSTASH_START"
            value: "0"
          - name: "ELASTICSEARCH_START"
            value: "0"
        ports:
        - containerPort: 5601
          name: ui
          protocol: TCP
        volumeMounts:
          - name: config-volume
            mountPath: '/opt/kibana/config/'
      volumes:
      - name: config-volume
        configMap:
          name: kibana-config
---
apiVersion: v1
kind: Service
metadata:
  name: kibana
  namespace: logging
  labels:
    component: kibana
spec:
  type: LoadBalancer
  ports:
  - port: 5601
    protocol: TCP
    targetPort: ui
    nodePort: 30257
  selector:
    component: kibana

I deploy via kubectl apply -f deployment.yml. I clear out the whole ELK stack via kubectl delete namespace logging.
There's a load balancer on Azure, with backend pool the k8s agents. When I deploy, a public ip and a rule are added to the load balancer. And I can access kibana in my browser by using its IP address from the Front end pool of addresses of the load balancer.
And here's the problem 1) and want I want to achieve 2):

Every time I kubect apply, a new IP address and rule are added to the
front end pool of the Load balancer. Strangely enough, the previous
IP addresses and rules are still there (even though I run kubectl delete namespace logging before deploying, which would suggest that the previously used IP addresses and rules should be released. I checked the code here
and as far as I can see there are functions that ensure there are no
stale public IP addresses and load balancing rules). IP addresses added from previous deployments can't access the currently deployed Kibana service.
I want to have a DNS name that the clients (e.g. my browser<->kibana, log emitting server<->logstash) of the ELK stack can use to refer to the ELK services without needing to hardcode IP addresses in the clients (so re-deployments of the ELK stack are transparent to the clients).

What I've tried so far: I  created manually a Public IP address with a dns name via Azure's Dashboard. I added load balancing rules to the Load balancer that look like the ones created automatically on kubectl apply. I tried to use this manually created Public IP in the kibana Service spec under externalIPs and then under loadBalancerIP (k8s docs).
When the externalIPs is set to the public IP, kubectl describe service --namespace=logging returns
Name:           kibana
Namespace:      logging
Labels:         component=kibana
Selector:       component=kibana
Type:           LoadBalancer
IP:         10.x.xxx.xx
External IPs:       52.xxx.xxx.xxx   <- this is the IP I manually created
LoadBalancer Ingress:   52.xxx.xxx.xxx
Port:           <unset> 5601/TCP
NodePort:       <unset> 30257/TCP
Endpoints:      10.xxx.x.xxx:5601
Session Affinity:   None
Events:
  FirstSeen LastSeen    Count   From            SubobjectPath   Type        Reason          Message
  --------- --------    -----   ----            -------------   --------    ------          -------
  15m       15m     1   {service-controller }           Normal      CreatingLoadBalancer    Creating load balancer
  14m       14m     1   {service-controller }           Normal      CreatedLoadBalancer Created load balancer

However requests to the dns name or directly to the external IP time out.
When I set the loadBalancerIP in the Service spec, kubectl describe service returns similar output, but without the External IPs row, and again, a new public ip address + rules are created on the loadbalancer. It's again not possible to use the dns name/ip of the Public ip I created manually.
Any help would be super appreciated :)
Answer: Ah. The easiest thing to do would be to avoid deleting the service before every deployment. In my experience, services tend to be very long lived; they provide a nice, fixed way to refer to things without having to worry about dynamic values for ports, ips, dns, etc.
In the Kibana service spec, remove the nodePort entry from the port configuration, so that the service can do its own thing; one less thing to think about. Don't set values for loadBalancerIP or externalIPs. Same rules apply to the other services.
For the ELK stack config files (I don't recall off the top of my head what they look like), refer to other components by their service names: no need to use hardcoded IPs or anything. (No idea if you were doing this, but just in case.)
Allow the services to be created; get the loadbalancer external IP and plug it into your DNS config.
You can continue using namespaces if that's how you prefer to do things, but don't delete the whole namespace to clear out the Deployments for ELK components.
Split your ELK stack spec into separate files for Deployments and Services (technically, I'm not sure if this is required; you might be able to get away with ), so that you can use:
kubectl delete -f logging-deployments.yaml
kubectl apply -f logging-deployments.yaml

or a similar command to update the deployments without bothering the services.
If you need (or prefer) to delete the ELK stack in another manner before creating a new one, you can also use:
kubectl -n logging delete deployments --all

to delete all of the deployments within the logging namespace. To me, this option seems a little more dangerous than it needs to be.
A second option would be:
kubectl delete deployments kibana
kubectl delete deployments elasticsearch
kubectl delete deployments logstash

If you don't mind the extra typing
Another option would be to add a new label, something like:
role: application

or
stack: ELK

to each of the Deployment specs. Than you can use:
kubectl delete deployments -l stack=ELK

to limit the scope of the deletion... but again, this seems dangerous.

My preference would be, unless there is some overriding reason not to, to split the config into >2 files and use:
kubectl create -f svc-logging.yaml
kubectl create -f deploy-logging.yaml
kubectl delete -f deploy-logging.yaml
kubectl apply -f deploy-logging.yaml
...
etc

in order to help prevent any nasty typo-induced accidents.
I break things down a little bit further, with a separate folder for each component that contains a deployment and service, nested together as makes sense (easier to keep in a repo, easier if more than one person need to make changes to related but separate components), and usually with bash create/destroy scripts to provide something like documentation... but you get the idea.
Set up this way, you should be able to update any or all deployment components without breaking your DNS/loadbalancing configuration.
(Of course, this all sort of assumes that having everything in one file is not some kind of hard requirement... in that case, I don't have a good answer for you off the top of my head...)
Comment: Thanks a lot for the detailed advice. One of the problems turned out to be that I installed kubectl via `az acs kubernetes install-cli` which for some reason installed an older version of kubectl than this of the cluster.
Comment: @JoroTenev ah can you perhaps elaborate on that - do you mean updating `kubectl` now allows you to use Azure static IPs through setting `loadBalancerIP`? Thanks.


Error while trying to install tomcat?

Question: While trying to install server in eclipse, it shows an error. Does anyone know how to enable server? Please help me in fixing the issue.
Comment: What errors do u get? How did you tried to install it? We dont even know what you tried yet so how should we be able to say what you did wrong?
Comment: @JavaBanana1993 ERROR:  SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Dservlet]]
Comment: WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Dservlet' did not find a matching property.
Comment: i think there are two possible reasons..

1. wrong path (check for a tutorial to set it)
2. problem in your web.xml descriptor (check for the "/" in your /...
Answer: Have you set the path to the tomcat??
Set the path it will go.
Comment: @praveen i downloaded tomcat 7.0.42 and jdk 7 eclipse juno. I have doubt in setting path..

Error while trying to install tomcat?


In a Random Forest model, are all possible variable combinations accounted for?

Question: To preface this question, I am building a Random Forest model using the randomForest package in R. I am not sure if this question is dependent upon my program, or if it can be answered based on the inherent properties of the algorithm. I felt this question was more appropriate for "Cross Validated" versus "Overflow", please let me know if you think otherwise.
A Random Forest model creates many decision trees which contain a subset of variables and data. Is there any guarantee that every possible combination of variables are accounted for across all of the decision trees?
For example, I have 4 variables that I am feeding into the RF model. Three of those variables are binary (X1, X2, Y1, Y2, Z1, Z2). The other variable (of ordinal type) contains 8 unique values.(A1...A8).
This leaves me with 56 possible variable combinations.
How can I guarantee that all possible unique combinations of variables are accounted for across trees? I understand that simply increasing the number of trees would increase the likelihood of this. I also realize that my example contains a relatively small number of variables, however consider a situation with many variables and unique combinations.
Comment: No, there's no such garanty. The total number of combinations get very big, very fast.
Comment: @Fernando I would suggest that you expand this comment to an answer, otherwise this question will stay unanswered
Answer: No, there's no such garanty. The total number of combinations gets very big, very fast.
The additional questions is: is that even necessary? Given that real data has noise and can present high correlation, forcing all combinations doesn't seem to help much.
If you know (by field experience) that all your variables are important, then maybe a deep neural net could work better.
Comment: For my purposes, it would be necessary because I have determined my variables to all be relevant. As you suggest, I will take a look at deep neural networks Thank you for the information. I see how the number of combinations could be very, very large and how it would not be possible to account for all combinations in those situations.
Comment: Deep nets may work well if you have a lot of variables with complex patterns and iterations.
Answer:
A Random Forest model creates many decision trees which contain a
  subset of variables and data. Is there any guarantee that every
  possible combination of variables are accounted for across all of the
  decision trees?

No. Consider the extreme example where your forest consists of a single tree with depth one.

How can I guarantee that all possible unique combinations of variables
  are accounted for across trees? I understand that simply increasing
  the number of trees would increase the likelihood of this. I also
  realize that my example contains a relatively small number of
  variables, however consider a situation with many variables and unique
  combinations.

You can't. And, perhaps more importantly, you probably don't want that as well. Doing that would decrease the variance of the models.

Having said that, you could try bagged trees (without attribute bagging, i.e. random selection of features) instead of Random Forests ensuring that all combinations are visited at least once, but I'm not sure this model would perform any better than a full Random Forest.
Comment: That makes sense. I was thinking that the process of actually "guaranteeing" each combination was covered would result in a loss in the true randomness of selecting variables/data. I will take a look at bagged trees, thank you for the information.


expr. tree: Static method requires null instance, non-static method requires non-null instance

Question: I searched the questions and found some topics and I suspect the error cause, but I can't figure it out.
I would like to build this expression part:
Function(row) groupedindexes.Select(
    Function(grpindex) row(grpindex))

I already build the part Function(grpindex) row(grpindex) with this:
Dim fieldselector As Expressions.LambdaExpression
fieldselector = Expression.Lambda(Expression.ArrayAccess(rowParameter, indexParameter), indexParameter)

The declarations are:
Dim rowParameter = Expression.Parameter(GetType(Object()), "Row")
Dim indexParameter = Expression.Parameter(GetType(Integer), "grpindex")

Now, I would like to build the Select part like this:
Dim outerfieldselector As Expressions.LambdaExpression
outerfieldselector = Expression.Lambda(Expression.Call(grpindexes, selectMethod, fieldselector), rowParameter)

The declarations are:
Dim grpindexes As Expression = Expression.Constant(groupedindexes, GetType(System.Collections.Generic.List(Of Integer)))
Dim selectMethod = GetType(Queryable).GetMethods(BindingFlags.Public Or BindingFlags.Static).First(Function(m) m.Name = "Select").MakeGenericMethod(GetType(Object), GetType(System.Func(Of Integer, Object)))

groupedindexes is a normal List(Of Integer).
In runtime, I get the above error at the line outerfieldselector=...
In my opinion, it should work. I call the Select method on grpindexes with one argument (fieldselector).
What could be the problem?
Thanks.
EDIT: a sample project can be downloaded at this link: http://www.filedropper.com/exptree
EDIT II:
here a simple, short console application project:
Imports System.Reflection
Imports System.Linq.Expressions
Module Module1
    Dim rowParameter = Expression.Parameter(GetType(Object()), "Row")
    Dim indexParameter = Expression.Parameter(GetType(Integer), "grpindex")
    Dim expr As Expression = Nothing
    Dim groupedindexes As New List(Of Integer)
    Dim grpindexes As Expression = Expression.Constant(groupedindexes, GetType(System.Collections.Generic.List(Of Integer)))
    Dim selectMethod = GetType(Queryable).GetMethods(BindingFlags.Public Or BindingFlags.Static).First(
        Function(m) m.Name = "Select").MakeGenericMethod(GetType(Object), GetType(System.Func(Of Integer, Object)))
    Dim fieldselector As Expressions.LambdaExpression
    Dim outerfieldselector As Expressions.LambdaExpression

    Sub Main()
        groupedindexes.Add(0)
        groupedindexes.Add(1)
        groupedindexes.Add(2)
        fieldselector = Expression.Lambda(Expression.ArrayAccess(rowParameter, indexParameter), indexParameter)
        outerfieldselector = Expression.Lambda(Expression.Call(grpindexes, selectMethod, fieldselector), rowParameter)
    End Sub
End Module

EDIT 3:
I think, I got it with the help of svick.
Dim selectMethod = GetType(Enumerable).GetMethods(BindingFlags.Public Or BindingFlags.Static).First(Function(m) m.Name = "Select").MakeGenericMethod(GetType(Integer), GetType(Object))

Comment: What is `grpindexes`? It would be easier to help you if you'd provide a short but complete program demonstrating the problem. (Just a minimal console app.)
Comment: I have added a simple project, because to copy all the code here would be too long. grpindexes represents the groupedindexes in the LINQ query.
Comment: It doesn't have to be your actual code. Just a short but representative program demonstrating the problem.
Comment: This is a sample small project. It is too mach connected to each other, therefore I uploaded it. It is exactly what you described: a short but representative program demonstraging the problem. Or uploads are here not allowed? Just run the project and hit the button.
Comment: It would be much better if you could make it short enough to include in your post. And if you have a button, that suggests it's a GUI - which is almost certainly adding pointless code. Console apps tend to be the simplest way of demonstrating problems.
Answer: The problem is that Queryable.Select() is not an instance method. You call it as if it was one in VB, but it's not, and that's reflected in expression trees.
So, the line should look like this:
outerfieldselector = Expression.Lambda(Expression.Call(Nothing, selectMethod, grpindexes, fieldselector), rowParameter)

Even if you fix that, your code still won't work. Some of the issues are:

MakeGenericMethod() expects the types of the type parameters. Here those are TSource and TResult, which should be Integer and Object.
List(Of Integer) does not implement IQueryable.
Comment: And how should I modify the code? I changed the types in the MakeGenericMethod, but I get an error. Even if List(Of Integer) does not implement IQueryable, it is possible to call Select, because in a LINQ query, it is possible.
Comment: I changed the types in the MakeGenericMethod and changed the Queryable to Enumerable.
Comment: @derstauner Yeah, LINQ on normal collections works because they implement `IEnumerable`, not `IQueryable`, which means you want `Enumerable.Select()`, not `Queryable.Select()`.


Trigonometry equation simplification

Question: So, I've been given the trig equation: $$\csc^2x - \cot 2x = 1$$ Using the identity and rearranging $$\cot^22x + 1 = \csc^22x$$ the equation simplifies to $$\cot^22x - \cot2x = 0$$ factoring out $\cot 2x$ $$ \cot 2x (\cot 2x -1) = 0$$ I've bee told to solve $\forall x | 0\leq x\leq180$
So... $$ \cot 2x = 0 $$or$$ \cot 2x = 1 $$
$$ \frac{1}{\tan2x} = 0 \Rightarrow 1 = 0 \times \tan 2x $$ therefore no solutions.
$$ \cot 2x = 1 \Rightarrow \tan 2x = 1 $$ $$ x\in\{22.5,112.5\}$$
Both of my solutions were correct, but I lost marks since apparently there are two extra solutions! 45 & 135 degrees. I don't know where I went wrong in my workings and was wondering if someone could tell me what I did wrong.
-Thanks
Comment: Notice that $$\cot(x)=0 \iff \frac{\cos(x)}{\sin(x)}=0\iff \cos(x)=0\iff x=90+180k$$
Answer: cot 2x = 0
cot 2x = cot 90
As cot 90 = 0
2x = 90
x = 45
So $ x\in\{45,135\}$

Trigonometry equation simplification


How can I change configuration parameters of jQuery "easy pie chart" plugin?

Question: I am using jQuery easy pie chart plugin for making pie charts. Initially I pass default configuration parameters. After that I want to change configuration parameters like bar-color, size of pie chart.
Default configuration parameters:
$('.chart').easyPieChart({
    easing: 'easeOutCirc',
    barColor: '#1abc9c  ',
    trackColor: '#f9f9f9  ',
    scaleColor:false,
    scaleLength: 5,
    percent: 67,
    lineCap: 'round',
    lineWidth: 15, //12
    size: 150, //110
    animate: {duration: 2000, enabled: true},
    onStep: function (from, to, percent) {
        $(this.el).find('.percent').text(Math.round(percent));
    }
});

I know how to set the percentage value of pie-chart dynamically, just like in the following way:
$('#'+domId).data('easyPieChart').update(value);

Except percentage, I want to set configuration parameters dynamically like:
I want to set size, bar-color of pie chart dynamically. For this I tried a lot of things but I didn't find the right way.
For this,I made JSFIddle for understanding.Initially size should be 110 after click on redraw button needs to change the size of pie chart.But it's not working.
Tell me, does the plugin I am using fulfill my requirements? If it does, how can I fix this?
Answer: We must destroy the existing data and then recreate the graph
var $chart = $(".easy-pie-chart");
        $chart.data('easy-pie-chart', null);
        $chart.easyPieChart({
           // my new settings here
        });

Answer: It seems that, as of now, the "easy pie chart" does not support dynamic options.
See https://github.com/rendro/easy-pie-chart/issues/65
If you want to stick with the plugin, you might want to recreate the chart completely on modifications (i.e. destroy the previous chart and create a new one).
Answer: You can set these values for each chart on the page, for each id, not only for the class.
var chart = window.chart = $('#easypiechart1').data('easyPieChart');
$('.chart')#easyPieChart({
barColor: '#333',
}

});
Also, you can change these values from CSS.
.easypiechart {
    position: relative;
    display: block;
    width: 100px;
    height: 100px;
}

Another option is to add an extra class on click (update).
Answer: The solution is to .remove .chart and to .append it again in the parent. For example:
Here is the HTML:

JS:
$('.chart-holder').find('.chart').remove();
$('.chart-holder').append('');

And after that:
$('.chart').easyPieChart({ .... });

It can be on click event or everything you want.
That's it. Simple solution.


Find a chain complex $C_*$ such that $H_i(C_*)=0$ but $H_i(C_*\otimes \mathbb Z_3)\neq 0$

Question: Find a chain complex $C_*$ such that $H_i(C_*)=0$ for all $i$, but $H_i(C_*\otimes \mathbb Z_3)\neq 0$ for some $i$.
Recall that if $C_*$ is a chain complex with differential $\partial$, $C_*\otimes A$ is a chain complex such that $(C_*\otimes A)_n=C_n\otimes A$ and the differential is given $\partial_n(c\otimes a)=
\partial_n(c)\otimes a$.
The first part of this question asked to find an example of a space $X$ such that:
$H_i(X,\mathbb Z)$ was non trivial for some $i>0$ and $H_i(X,\mathbb Z_3)=0$ for all $i>0$. I found that $X=\mathbb RP^4$ satisfies that condition.
It seems like there should be an easy way to this part of the question givent he first part but it almost seems backwards.
My idea so far was to let our chain be something like $\mathbb Z \rightarrow \mathbb Z \rightarrow \mathbb Z $ where the first map is the identity and the second map is multiplication by 3. Since these are isomorphism we should get trivial homology?
Then when we tensor with $\mathbb Z_3$ we get the identity and then a zero map, which gives non trival homology. But I'm not sure how to make $H_i(C_*)=0$ for all $i$.
Answer: $\dots \rightarrow 0 \rightarrow \mathbb{Z} \xrightarrow{3} \mathbb{Z} \rightarrow \mathbb{Z}/3  \rightarrow 0 \rightarrow \dots$ is exact, and so this has 0 homology. As you said, tensoring by $\mathbb{Z}/3$ will cause the new complex to not be exact, and so it has nontrivial homology. It is worth noting that no space's singular, simplicial, or cellular chain complex will give a counterexample by the universal coefficient theorem.


What is the definition of $\bigcup_{i}^{\infty}A_i$ and $\sum_{i}^{\infty}a_i$?

Question: What is the definition of $\bigcup_{i}^{\infty}A_i$ and $\sum_{i}^{\infty}a_i$?
My assumption until now was $$\bigcup_{i}^{\infty}A_i=\lim_{n\rightarrow\infty}\bigcup_{i}^{n}A_i$$ and $$\sum_{i}^{\infty}a_i=\lim_{n\rightarrow\infty}\sum_{i}^{n}a_i$$
However, I don't recall seeing it anywhere, and I want to verify if my implicit assumptions are correct or not. Thank you for taking the time.
PS: help me find proper tags for this question please.
Comment: For $\sum$ you are correct. But for $\bigcup$, a limit of sets doesn't make any more sense than just $\bigcup_i^\infty$ a priori. Read [this section](https://en.wikipedia.org/wiki/Union_(set_theory)#Arbitrary_unions) for the definition.
Answer: An element $x$ is in the union iff $x$ is in at least one of the $A_i$. The sum definition is correct.
Answer: Most of the time, you're right about the infinite sum.  There are alternate definitions of infinite sum (like the ones that lead to $\sum_{i=1}^\infty i = -\frac{1}{12}$), but that's probably not of use to you.
As for the union, you don't really need a limit.  $\bigcup_{i=1}^\infty A_i$ is the set of all $x$ such that $x \in A_i$ for some $i$.


Structure of $\Bbb N$ in $\Bbb R$ and substraction in $\Bbb N$.

Question: I'm working with the definition of $\Bbb N$ as the intersection of all inductive susbsets of $\Bbb R$, being a subset $I$ inductive iff $1\in I$ and $\forall n(n\in I\to n+1\in I)$.
By the way, $\Bbb R$ is defined by its axioms: that is, as a complete, ordered field. Then, $\Bbb N$ is defined inside of $\Bbb R$ as described above.
I'm trying to prove that if $x$ is a positive real number then $[x,x+1)$ has exactly one natural number. Intuitively, I'm trying to get the 'spacing' between natural numbers from the fact that they are in every inductive set.
My try:

I started stating that if $x,y\in\Bbb N$ and $y<x$ then $x-y\in\Bbb N$, but I don't know how to prove it. I have defined the set $A=\{z\in \Bbb R:z\le x\vee z-x\in\Bbb N\}$ to see that it is inductive, but I couldn't prove that $z\in A\to z+1\in A$ when $z\le x$ and $z+1>x$.

If I manage to prove this, it is done, because if $x-y\in \Bbb N$ then $x-y\ge 1$.
Comment: What are yo allowed to use if $\mathbb N$ is not defined ?
Comment: I can use the axioms of the real numbers, that is: $\Bbb R$ is a complete, ordered field. $\Bbb N$ is defined inside $\Bbb R$ as described in the question
Answer: You can prove it like this ; Since all reals are bounded by naturals you know that the set of all numbers greater than equal to $x+1$ is non empty by induction you can prove that it also must have a least element so there is a least natural $n$ such that $x+1\le n$ which ismplies that $n-1$ lies in your interval .
Answer: If $A$ is inductive, then so is $A\setminus (-\infty,1)$. Therefore, $\Bbb N\subseteq [1,\infty)$.
Let $$ S=\{\,x\in \Bbb R\mid \#([x,x+1)\cap\Bbb N)\ge 2\,\}$$
and assume $S\ne \emptyset$. Then $0\le \inf S<\infty$. We can pick $s\in S$ with $\inf S\le s<\inf S+1$. Let $n_1,n_2$ be two of the natural numbers $\in [s,s+1)$, where $s\le n_1<n_2<s+1$.
As $n_2-1,n_1\in [n_2-1,n_2)$ and $n_2-1<\inf S$, we conclude that $n_2-1\notin \Bbb N$. Also, $n_2>n_1\ge 1$. Then $\Bbb N\setminus \{n_2\}$ is inductive, contradicting $n_2\in \Bbb N$. We conclude that $S=\emptyset$, i.e., each $[x,x+1)$ contains at most one natural number.
A similar argument shows that
$$ T:=\{\,x\in \Bbb R_{>0}\mid [x,x+1)\cap\Bbb N=\emptyset\,\}$$
is empty, whence your desired result.
Comment: I don't see how you conclude that $\Bbb N\setminus\{n_2\}$ is inductive. In fact, this is the crux of the problem.


Using a DL380p Gen8 and D2700 Disk Enclosure

Question: We've got a DL380p Gen8 with 16 slots for 2.5" drives, and we're running out of storage space.
So what I'm looking at doing is replacing all of the current drives (some are 300GB, some 600) with larger capacity drives and also adding a D2700 enclosure for additional capacity.
My question is: If we're using a 6GB/s D2700 and SAS drives in all of the above, does it matter what logical drives and such are in the server as opposed to the enclosure?
It seems to me that the SAS drives in the server will each have their own channel running at the full 6 GB/s, whereas the drives in the enclosure will have to share a connection back to the server at 6GB/s?
Answer: D2700 provides four physical interfaces per SFF port, each 6gb/s, which gives total 24gb/s per one physical port. In multipath configuration it can provide up to 48gb/s when using two HP HBA's and two storage controllers.
So, from the performance point of view - nothing changes to the worse when using D2700, also, you are getting more availability.
Comment: Yes, you are only limited by the possibilities of the storage controller like number of logical volumes, chunk sizes etc. Physical connectivity with D2700 gives more than you can achieve with Smart Array PCI controllers. Even standard FC can't be that fast, it only can give you 8gb/s per port (16gb/s for multipath).
Comment: So if I'm understanding this right, there's no downside to using a disk enclosure or having your OS drive be on those disks rather than the ones on the server itself.
Answer: You'll want to keep the arrays in the external enclosure separate from those inside the server. Just from a fault-domain perspective.
However, you can have boot disks in the enclosure or have the server itself be empty. Up to you. The D2700 enclosure is a rock-solid unit, so the advantage when using SAS disks is dual-porting/dual-pathing, depending on which host RAID controller you're using.
Your SAS connections are multi-lane 6Gbps links on a SFF-8088 connection. That's 24Gbps. You'll probably be doing this with one controller.
Remember that a single (spinning) disk's throughput won't approach 6Gbps, so oversubscription is fine in this case.


How to calculate percentiles from z-scores

Question: We often get reference tables to match z-scores with equivalent percentiles.
Can anyone help me calculate percentiles from z-scores? What's the formula?
Thank you.
Comment: Did you see [this](http://davidmlane.com/hyperstat/A79567.html) page?
Comment: The reason why you get given [tables](http://stats.stackexchange.com/questions/235869/percentile-from-z-score) instead of a formula is that there isn't a closed-form formula. The usual way to calculate it using computers is via [calling functions](http://stats.stackexchange.com/questions/56065/is-there-a-quick-way-to-convert-z-scores-into-percentile-score) that use one of several kinds of approximations, but these tend to be optimized for fast, accurate calculation on a computer, and are not especially suitable for working on a calculator or by hand.
Comment: Thank you that is very helpful, and the links too. I forgot to mention that I can do this in stats software, but a computer-programmer (using Java) had asked me how to implement it using a formula. I didn't know if there were equivalent functions in Java and I didn't know how our stats software did it. The best I could offer him was using an approximation of the curve (using exponentiated polynomial), which I assume can be used as a very simple approximation?
Comment: I think "exact" duplicate is off, but the desired answer is the same.  The primary answer on that page has a lot of useful information for this question.  I was a bit surprised that the state of the art was based on a paper from 1969 because I have seen unexpected changes to these values in the last ten years.
Answer: The following formula can be found in the Handbook of Mathematical Functions
$$\hat{Z}\left ( x \right )=\left ( b_1t+b_2t^2+b_3t^3+b_4t^4+b_5t^5 \right )+\varepsilon \left ( x \right )$$
Where $t={1}/{\left (1+px \right)}$, $\left | \varepsilon (x) \right |< 7.5\times 10^{-8}$, $p=.2316419$, $b_1=.319381530$, $b_2=-.356563782$, $b_3=1.781477937$, $b_4=-1.821255978$, and $b_5=1.330274429$.
Most modern software that allows the user to calculate the percentile from the $Z_{score}$ provide more accurate results than this old approximation.


Particular solution of Schrodinger equation, satisfying time dependent boundary conditions

Question: I am considering the Schrodinger equation on $[0,1]$:
$$iu_t=-u_{xx}$$
I am looking for a particular solution $u(x,t)$ which satisfies the boundary condition $$\cos(t)\cdot u_x(0,t)=\sin(t)\cdot u(0,t)$$
(which is not $u=0$)
I know that this is an undetermined problem (since I am missing a boundary condition at $x=1$ and also an initial condition). But for my case, I only care about finding one particular solution which satisfies the condition above (and not some general solution), so I don't impose any more restrictions.
More generally (perhaps this will be easier), I am interested in an example of a solution to the Schrodinger equation such that its boundary condition at $x=0$ at time $t=0$ is Neumann ($u_x=0$), and at some other time it is Dirichlet ($u=0$), like in the example above, with $t=\pi/2$. My only restriction is that I want the ratio $u_x/u$  at the boundary to be real valued for all $t$ (such that $u\neq0$). If you can set it so that the same boundary condition also holds at $x=1$ - that would be even better.
Does anyone have an idea on how to find such an example?
Thanks in advance.
Comment: Such a solution will be hard to find, because it cannot be separable - see that if $u(t,x)=p(t)q(x)$ that your BC equation would imply $\cos(t)p(t)~q'(x)=\sin(t)p(t)~q(x)$, clearly an impossibility. I think you will have to resort to numerical methods.
Comment: @K.defaoite I agree - this difficulty with nonseparability is exactly why I asked the question. I am hoping that since I did not give too many restrictions on the other boundary and initial condition, then somebody might be able to make a "smart guess" for a solution (even just for the second problem - the sine/cosine is not that important to me). Sadly, for my needs I am looking for an actual solution (not numerical). Also, I am not very familiar with numerical theory for such problems with time dependent boundary conditions.
Comment: The original problem has the trivial solution $u=0$, but that's not what you're looking for.
Comment: @Aruralreader Of course. I'll add that to the post, but I'm naturally looking for a nontrivial solution.
Answer: Here's one solution:
$$u(x,t) = \cos(x)e^{-it} + i \sin(x)e^{-it} + \cosh(x)e^{it} - i\sinh(x)e^{it}$$
Each term is independently a solution to the stated differential equation.
Note that it isn't exactly true that the problem isn't separable (I may be bending the definition here...). The differential equation's separable qualities are unaffected by your boundary condition: you can still use separation of variables to form elementary solutions to the differential equation. Normally before going further, one uses the boundary conditions to discard/constrain most of the elementary solutions, which is the part we can't perform here (at least not through the normal procedure).
By not discarding any elementary solutions, I was able to find the above solution which uses a superposition of both the sinusoid and hyperbolic sinusoid solutions.
Comment: A very nice solution.
Comment: Thanks Patrick, great point about (non)separability too.


Enable / Disable comment form in a module?

Question: I would like to set a given node's comment flag to 1 or 2 (to either show or hide the comment form) via my custom module, depending on certain conditions.
I have tried using hook_node_view, but this approach seems not to have worked:

function custom_node_view($node, $view_mode, $langcode) {
  $node->comment = 1;
}

Even if I explicitly set the comment flag to 1, it will remain 2 for a given node. If I dpm($node); just after setting the flag, the correct value will show in the devel information, but the comment form will still show...
According to comment.module, the values are such:
/**
 * Comments for this node are closed.
 */
define('COMMENT_NODE_CLOSED', 1);

/**
 * Comments for this node are open.
 */
define('COMMENT_NODE_OPEN', 2);

Is there a different hook I should be using to show/hide the comment form programmatically?
Answer: It looks like I can set the comment display correctly within hook_node_load(). I guess that runs a bit earlier in the process, and tells comment.module to not display the form for a given node.
Here's an example of what I ended up implementing:
<?php
/**
 * Implements hook_node_load().
 */
function custom_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->comment = COMMENT_NODE_CLOSED; // to close comments
  }
}
?>

Comment: comment.module adds the comments in comment_node_view(). So I guess you just need to make sure that your module runs before comment.module (set a lower weight) and then doing it in hook_node_view() should work fine. Note that it is possible that the updated flag value will be persisted to the database if someone node_save()'s it (Due to the static cache, all node_load() calls will share the same instance on a single site). Make sure that is not a problem.
Comment: And you could also use hook_entity_prepare_view(), then you don't need to mess with module weights: http://api.drupal.org/api/drupal/includes--common.inc/function/entity_prepare_view/7
Comment: @Berdir That should be an answer.
Comment: Hmm... I really need to read up on hook_entity_ more. I'm still set in my Drupal 6 ways (meaning I have blinders on to many new D7 hooks).
Comment: Has anyone checked if this disabling works on nodes that has NO comments attached with it? Doesnt work for me for some reason...

Moreover, using the above solution apparently executes on the edit page also. So even if the node has open comment status, in the node edit form it will show closed and if user saves the node, it will save the comment status accidentally.