openpyxl select dynamic range until last non-empty row within range

Question: I need to select dynamic ranges in my workbooks. I know the starting position of the range (ex:C2), however, the number of rows might change every day.
Here is my sample xlsx. I want to select from c2:g4.
  A         B       C       D       E       F       G
1 head1     head2   head3   head4   head5   head6   head7
2 Data1.1   Data2.1 Data3.1 Data4.1 Data5.1 Data6.1 Data7.1
3 Data1.2   Data2.2 Data3.2 Data4.2 Data5.2 Data6.2 Data7.2
4 Data1.3   Data2.3 Data3.3 Data4.3 Data5.3 Data6.3 Data7.3
5 Data1.4   Data2.4
6 Data1.5   Data2.5
7 Data1.6   Data2.6
8 Data1.7   Data2.7

This is my code:
from openpyxl import load_workbook
workbook = load_workbook(filename="example.xlsx")
sheet = workbook.active
for value in sheet.iter_rows(min_row=2,
                             min_col=3,
                             values_only=bool):
        print(value)

And here is the output:
('Data3.1', 'Data4.1', 'Data5.1', 'Data6.1', 'Data7.1')
('Data3.2', 'Data4.2', 'Data5.2', 'Data6.2', 'Data7.2')
('Data3.3', 'Data4.3', 'Data5.3', 'Data6.3', 'Data7.3')
(None, None, None, None, None)
(None, None, None, None, None)
(None, None, None, None, None)
(None, None, None, None, None)

How can I limit my search to the desired range and eliminate the 'None' values?
Thanks!
Comment: How should we know which column is *"C2"*? Please edit your sample and make this clear.
Comment: `for row in rows: if not(any(row)): break` will stop at the first empty row.
Answer: Here is how:
from openpyxl import load_workbook
workbook = load_workbook(filename="example.xlsx")
sheet = workbook.active
for value in sheet.iter_rows(min_row=2,
                             min_col=3,
                             values_only=bool):
        if None in value:
            continue
        print(value)


Determine run-time of an algorithm

Question: Probably a stupid question but I don't get it right now. I have an algorithm with an input n. It needs n + (n-1) + (n-2) + ... + 1 steps to finish. Is it possible to give a runtime estimation in Big-O notation?
Answer: Indeed, it is. Since we have $$n+(n-1)+(n-2)+\cdots+1=\frac{n(n+1)}2,$$ then you should be able to show rather readily that the runtime will be $\mathcal{O}(n^2)$.
Comment: *face palm* Thanks!!!
Comment: Maybe it's because I'm slow, but I don't understand how you got $\frac{n(n+1)}{2}$ from that sequence. I also don't get how you knew it was `O(n^2)`.
Comment: @David: That's a well-known closed form for the sum of the first $n$ positive integers. A quick geometric proof is to imagine stacking squares: first a stack of one square, next to a stack of two, next to a stack of three, and so on, until we have $n$ stacks, forming a jagged triangle. If we did that again, we'd need twice as many squares, and rotating the second arrangement a half turn and placing it on top of the first, we have an $n$ by $n+1$ rectangle. As for the other bit, what do you know about big-O notation?
Comment: @CameronBuie I'm just starting to learn big-O. From what I've read, it's an approximation of how an algorithm scales in proportion to its input size. I haven't gotten as far such that I would understand how you knew the algorithm was `O(n^2)` though.
Comment: @David: I happened to know that a polynomial's "big-O" is always its highest order exponent. So, for example, here we have $\frac12n^2+\frac12n.$ The quadratic term has the highest degree, so the polynomial is $\mathcal O(n^2).$ To prove it, we need only find a positive constant $M$ such that for large enough $n,$ we always have $$\left|\frac{n(n+1)}2\right|\le M\left| n^2\right|.$$ It turns out that $M=1$ works for all $n\ge 1.$
Answer: There are $n$ terms in your series, and each term is of the order $n$ at maximum.  Therefore the operation takes on the order of $O(n^2)$ steps.
Comment: *face palm* Thanks!!!

Determine run-time of an algorithm


how I create this form dynamically

Question: I am going to create a HTML form dynamically with php. Using that form users can select subjects under different category. A category and Its subjects have broken to one logical section and have applied jquery accordion.  In my form I need to create more logical section like that.
// Check SESSION fromm category page
if ( isset ( $_SESSION['category']) && is_array( $_SESSION['category'])) {

    $categoryIds = implode(',', $_SESSION['category']);

    $q = "SELECT  c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si
            FROM    category AS c
            INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id
            INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
          WHERE   c.category_id IN ($categoryIds)";

    $r = mysqli_query( $dbc, $q) ;

    $catID = false;
    $max_columns = 2;

    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
    {
        $categoryId = $row['ci'];
        $category = $row['cn'];

        $subjects = array();

        $subjects[] = $row['sn'];

        echo '
';

        //Detect change in category
        if($catID != $categoryId)
        {
            echo "
Category 01: {$category}
";
            echo "
";

            echo '
';

            $j = 0;

            foreach ( $subjects AS $sub ) {
                if($j%2 == 0 && $j == 0)
                {
                    echo '
';
                    echo '<input type="checkbox" value="1" name="subjects[]">'.$sub.'	';
                }
                else if($j%2 == 0)
                {
                    echo '

';
                    echo '<input type="checkbox" value="1" name="subjects[]">'.$sub.'	';
                }
                echo '<input type="checkbox" value="1" name="subjects[]">'.$sub.'	';
                $j++;
            }
            echo '
';
            echo '
';
            echo "
 \n";
        }
        $catID = $categoryId;
        echo '
';
   }
}

Answer: You will have to have 2 loops for that as below.
foreach/for loop to create the categories
{
 foreach/for another loop inside above loop to create levels
 here you can have a table with two columns`<td>`

  Apply below logic to create a row with two columns`<td>`
  //$i is the counter, when you loop through once you increase the $i by one.
  if($i%2 == 0)
  //add new `<tr>`. If it's $i != 0 close the
 before opening one.
}

If you have any issues let me know.
Let's assume is as below. Create the arrays as below from SQL
    levels_array[1][] = "pre school" //cat 1 levels
    levels_array[1][] = "pre school 1" //cat 1 levels
    levels_array[1][] = "pre school 2"  //cat 1 levels
    levels_array[2][] = "school 2"  //cat 2 levels
    levels_array[2][] = "school 2"  //cat 2 levels
    levels_array[3][] = "college" //cat 3 levels

    cat_array[1] = "catgeory 1"
    cat_array[2] = "catgeory 2"
    cat_array[3] = "catgeory 3"

for($i = 1; < count($cat_array); $i++)
{

foreach(levels_array[$i] as $item)
{
//create the table with the above mentioned logic
}

}

According to the updated question
echo '
'; $j = 0;
foreach ( $subjects AS $sub ) {
if($j%2 == 0 && $j == 0)
{
  echo '
';
  echo ''.$sub.'	';
}
else if($j%2 == 0)
 {
  echo '

';
  echo ''.$sub.'	';
 }
echo ''.$sub.'	';
$j++;

}
echo '
';
echo '
';

Comment: then how I use while loop?
Comment: you can choose whatever you like to loop through
Comment: @Dasun.. Its hard to understand for me? can you elaborate your answer with en example? Thank you.
Comment: @Dasun... I tried to this as you mention. But have got stuck in the inner foreach loop.. Check I update my question..
Comment: Then I can get this error..: Invalid argument supplied for foreach()
Comment: it's because you don't have any $subjects.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22668/discussion-between-tharanga-nuwan-and-dasun)
Comment: since I don't have access to your database I can not tell you exactly where you are going wrong. check step by step. line by line

how I create this form dynamically


Verifying an analytical solution to an ODE

Question: I'm having trouble in verifying that $y=\frac{4}{\exp(t)+\exp(-t)}$ is an analytical solution to $\frac{\text{d}y}{\text{d}t}=-\sqrt{y^2-\frac{y^4}{4}}$, where the initial condition is $y(0)=2$.
I have tried with help of substitution, where i end up with the following;
$\frac{\text{d}y}{\text{d}t}+\sqrt{y^2-\frac{y^4}{4}} = -\frac{4(\exp(t)-\exp(-t))}{(\exp(t)+\exp(-t))^2}+\sqrt\frac{16(\exp(t)+\exp(t))-64}{(\exp(t)+\exp(-t))^4}$
With the $-64$ inside the sqrt, I can not see you this can result in $0$.
Comment: Yes, i know. But I dont get it to show that $y'(t) + \sqrt{(y^2-\frac{y^4}{4})}=0$?
Answer: $y = 2 \sech t$
$y' =$$-2 \sech t \tanh t\\- y (\sqrt {1+\sech^2 t}\\ -y\sqrt {1+\frac {y^2}{4}}\\-\sqrt{y^2 - \frac{y^4}{4}}$
I guess that Mathjax doesn't recognize the hyperbolic secant function.
Comment: we can use $y = 2 \sec_h t$ for tiime being?
Answer: Seeing that $y\equiv 0$ is a solution, this IVP has an always positive solution. To reduce the degree you can borrow an idea from Bernoulli equations and substitute $y=\frac2u$, $u(0)=1$,
$$
-\frac{2u'}{u^2}=y'=-\sqrt{\frac{4}{u^2}-\frac{4}{u^4}}
\\
\iff
\\
u'=\sqrt{u^2-1}
$$
which now integrates per separation as $\text{Arcosh}(u)=t+c$.


VXML  tag not working

Question: The  tag in VXML version=2.0 is not working i.e. not able to hear the text in  tag.
 Hell World. Press  1  to repeat the message
I can hear the "Hello world. Press" and then silence and again continues from "to repeat the message." from Sip Client.
Please let me know if any further information required for this.
Answer: Not sure what TTS engine you are using but it could be that it does not like the "1".  Try spelling out the number 1 so the message is "Hello World. Press one to repeat the message."  Also if you are testing in a development environment on a workstation it may be that the system is picking up the audio from the IVR as input and bargein is kicking in and cutting of the prompt. Try setting bargein="false".  If neither of these are the issue then provide the complete VXML and a description of the IVR platform and environment used.

VXML  tag not working


Drupal 7 - Hide certain form fields of a content edit form depending on the content data

Question: In Drupal 7, is there a way to change the standard edit form for a content type based on a certain content?
For example:
I have a content type with a checkbox...once it it checked and the form is saved, I do not want this checkbox to be visible anymore...therefore based on the checkboxes value in the Database I want to hide form fields when showing the form.
I am building a small specific project site, where a company wants to add projects, and their customers are supposed to follow certain steps (upload some content, provide information etc.), and also should be able to check off certain requirements, and once these are checked off, they should not be visible/editable to them.
Also the displayed form fields should depend on an user's role, and then FURTHER be limited depending on the content's database entries.
Is there a module, which could achieve this behaviour? "rules" and "field/permissions" come close to what I need, but are not sufficient. Or did I just miss the option to change a form field's accessibility based on conditions?
What I need is some place to define a logic like "IF (VALUEOF(CHECKBOX_1) == TRUE) THEN DO_NOT_SHOW(CHECKBOX_1)"
Comment: Why not using hook_form_alter? You can get all values there and disable/remove elements.
Comment: By default, Drupal does not offer such feature out of the box. Since your requirements are very specific, hook_form_alter is the only option you can use. You need to check the value in particular field and then make it hidden. Or try with dependent/conditional field module.
Answer: hook_form_alter is the way to do this, as explained by Mihaela, but what options do you have inside that function?

If you want just to disable field (it will be visible, but user can't change it) you can do it like this:
$form['field_myfield']['#disabled'] = TRUE;
And if you want it to be hidden, but to keep value it has before editing the way to do that is:
$form['field_myfield']['#access'] = FALSE;

I.e. hiding it (somewhere I saw someone suggesting that):
hide($form['field_myfield']);

really hides the field, but after that, when form is saved this field has empty value, validation fails, etc, so that's not a good way to do this. Hiding makes sense only if you want to print separately that field later, at some other place.
Answer: function your_module_form_alter(&$form, &$form_state, $form_id){

    switch($form_id) {
    case 'nameOfTheNode_node_form':
        //your code here. check the value from from_state.
    break;
    }
}

Comment: Why use switch and not an if statement? Are there many forms to alter?
Comment: Sorry for the delay, but yes, maybe in the same module you want to alter 2 forms.
Comment: This function is called for every form, when ever it's going to be displayed, so make sure to change the right one, by checking it's id.
Answer: In this case, I use module Conditional Fields https://www.drupal.org/project/conditional_fields
For example: If my Dependees field has a value, Dependent field can be visible/invisible, enabled/disabled, required/optional, checked/unchecked


How to handle my code when different jQuery object names are possible

Question: I have a simple function that I'd like to run on $.ready. The same function should run both on the frontend as well as on the admin pages.
Problem happens on the admin pages because there the jQuery variable is not defined. Instead they define django.jQuery.
How can I make my code fit both cases without polluting global namespace with an additional jQuery name?
This is what I have so far, it works, but leaves the additional jQuery name in global scope:
if(typeof jQuery === 'undefined' && typeof django !== 'undefined') {
   jQuery = django.jQuery;
}
jQuery(function($){...});

Answer: Not sure what the big deal with having jQuery in the global namespace. BUT you can do something like this:
(function (jQuery) {
    jQuery(function($){...});
})(window.jQuery || django.jQuery));

or more confusing
(window.jQuery || django.jQuery)(jQuery(function($){...});


Validação do update no laravel

Question: Eu estou com um problema para fazer validação no update no Laravel.
Meu Controller esta assim:
public function editar(EspecieRequest $request, Especie $esp)
{
    $especie = Especie::find($esp->id_especie);
    $valores = Request::all();
    $especie->fill($valores)->save();

    return redirect()->action('EspecieController@lista');
}

Meu Request esta assim:
    public function messages()
    {
        return [
            'nome_especie.required' => 'O campo nome é necessário'. $this->id_especie,
...
        ];
    }

O erro que o laravel mostra é esse:
"Call to a member function fill() on null"
Comment: De um `var_dump($esp);`, pode ser que `$esp` esteja sem valor, ou a variável `$valores` esteja recebendo nulo.
Comment: tem que verificar `$especie` se retornou algum dado
Comment: `function editar(EspecieRequest $request, Especie $esp)` isso que ta estranho ...!
Comment: O $esp não tinha eu fiz no tentativa e erro, eu fiz o var_dump de $esp e $valores e travou o meu pc, depois eu fiz de uma variável só, não me lembro qual e vi que saiu um lixo de memória nela
Answer: Esse erro é causado quando você usa a função find e a mesma não encontra nenhum resultado correspondente no banco de dados para o ID do Model pesquisado.
Em tais casos, eu costumo usar findOrFail para evitar esse tipo de problema.
Exemplo:
 $especie = Especie::findOrFail($request->id_especie);

Caso o resultado para id_especie não seja encontrado no banco, uma exceção chamada ModelNotFoundException será lançada.
Inclusive é uma boa forma, por sinal, de se evitar que o seu código continue sendo executado de maneira inesperada caso o resultado não seja retornado.
No seu código há algo que parece não fazer muito  sentido: Você está recebendo o Especie $esp como parâmetro, mas está buscando ele novamente no banco de dados através de outra consulta?
Se você estiver fazendo bind do objeto Especie através das rotas, talvez você precise alterar o seu código apenas para isso:
public function editar(EspecieRequest $request, Especie $esp)
{

    $valores = $request->all();

    $esp->fill($valores)->save();

    return redirect()->action('EspecieController@lista');
}

Comment: Não deveria ser `$request::all()` em vez de `Request:all()`, já que `$request` é o que está vindo do parâmetro?
Comment: O meu método original não tinha Especie $esp, fiz na tentativa e erro, o problema é que quando ele passa no request, o request não me volta os valores para update
Comment: @lipesmile, você deu um `dd($request::all())`, pra saber se os dados estão chegado? Caso não der certo, o que acho difícil, mudar o parâmetro da função para `Request $request` para ter certeza que você está mandando caso ainda persista o problema ai o erro provavelmente é como você está mandando...
Comment: Bem notado @RicardoLucas

Validação do update no laravel


No module called found - why?

Question: Still trying to get to grips with VSCode.
Trying to work through this: https://www.youtube.com/watch?v=7aIb6iQZkDw
I've run the first line of code:
from selenium import webdriver
The reply is:
ModuleNotFoundError: No module named 'selenium'

Tried the normal pip install method having thought I'd already installed it:
pip install selenium
Requirement already satisfied: selenium in ./opt/anaconda3/lib/python3.9/site-packages (4.7.2)
Requirement already satisfied: urllib3[socks]~=1.26 in ./opt/anaconda3/lib/python3.9/site-packages (from selenium) (1.26.12)
Requirement already satisfied: certifi>=2021.10.8 in ./opt/anaconda3/lib/python3.9/site-packages (from selenium) (2022.9.24)
Requirement already satisfied: trio~=0.17 in ./opt/anaconda3/lib/python3.9/site-packages (from selenium) (0.22.0)
Requirement already satisfied: trio-websocket~=0.9 in ./opt/anaconda3/lib/python3.9/site-packages (from selenium) (0.9.2)
Requirement already satisfied: sortedcontainers in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (2.4.0)
Requirement already satisfied: attrs>=19.2.0 in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (21.4.0)
Requirement already satisfied: async-generator>=1.9 in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (1.10)
Requirement already satisfied: outcome in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (1.2.0)
Requirement already satisfied: sniffio in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (1.2.0)
Requirement already satisfied: idna in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (3.4)
Requirement already satisfied: exceptiongroup>=1.0.0rc9 in ./opt/anaconda3/lib/python3.9/site-packages (from trio~=0.17->selenium) (1.0.4)
Requirement already satisfied: wsproto>=0.14 in ./opt/anaconda3/lib/python3.9/site-packages (from trio-websocket~=0.9->selenium) (1.2.0)
Requirement already satisfied: PySocks!=1.5.7,<2.0,>=1.5.6 in ./opt/anaconda3/lib/python3.9/site-packages (from urllib3[socks]~=1.26->selenium) (1.7.1)
Requirement already satisfied: h11<1,>=0.9.0 in ./opt/anaconda3/lib/python3.9/site-packages (from wsproto>=0.14->trio-websocket~=0.9->selenium) (0.14.0)

What's going on?
Comment: Few questions, if you could answer - have you created a virtual environment? are you using a jupyter notebook to import selenium? is your notebook's kernel switched to the python interpretor of the new virtual environment? have you updated the kernelspec with this venv?
Comment: No, I'm trying to get to grips with VSCode and there is a jupyter notebook plugin. Not using virtual environment. Trying to just run code.
Comment: are you using a windows system or a mac/linux?
Comment: It looks like you already have selenium installed on your system. You may need to check your python path to make sure the selenium module is being recognized by your interpreter. You can do this by running the following command:

import sys
sys.path
Comment: Mac, I just want to add this comment
Comment: Mohamed Saeed.. Result is
import sys sys.path
               ^^^
SyntaxError: invalid syntax
➜  Personal git:(main) ✗
Answer: For your problem, the most possible reason is that you are in a wrong environment.
You can use shortcuts "Ctrl+Shift+P" and type "Python: Select Interpreter" to choose the correct interpreter if you are using python file.
If you are using jupyter notebook, click the icon in the upper right to choose python kernel.

No module called found - why?


Structure of simple modules of $U_q(\mathfrak{sl}_2)$ at a root of unity.

Question: This is Theorem VI.5.5 in Kassel's Quantum Groups:

Let $q$ be a root of unity. Prove: Any simple $U_q$-module of dimension $e$ is isomorphic to a module of the following list:

$V(\lambda, a, b)$ with $b\neq 0$,
$V(\lambda,a,0)$ where $\lambda\neq \pm q^{j-1}$, $1\leq j\leq e-1$
$\widetilde{V}(\pm q^{1-j},c)$ with $c\neq 0$ and $1\leq j\leq e-1$

Here $e$ is the smallest integer s.t. $q^e=\pm 1$. The $U_q$-module structures are defined on an $e$-dimensional vector space $V$ with basis $\{v_0,\ldots,v_{e-1}\}$ like so.

$V(\lambda\neq0,a,b)$:
$Ev_0=av_{e-1}$, $\,Fv_{e-1}=bv_0$, $Kv_p = \lambda q^{-2p}v_p$, $Fv_p=v_{p+1}$, and $$ Ev_{p+1}=\left([p+1]\frac{q^{-p}\lambda - q^p\lambda^{-1}}{q-q^{-1}}+ab\right)v_p$$
$\widetilde{V}(\mu\neq0,c)$:
$Fv_0=0$, $Ev_{e-1}=cv_0$, $Kv_p = \mu q^{2p}v_p$, $Ev_p=v_{p+1}$, and
  $$Fv_{p+1}=[p+1]\frac{q^{-p}\mu^{-1} - q^p\mu}{q-q^{-1}} v_p $$

My approach to the proof is the following: Take an arbitrary simple $e$-dimensional $U_q$-module $W$. This module has a nonzero element $w$ s.t. $Kw=\alpha w$ for some $\alpha\in\mathbb{C}^x$. Then see if you can find the relations from above in there under some additional assumptions.
I found that if $Fw\neq 0$ and $F^e\neq 0$, then $W\cong V(\lambda, a, b)$ with $b\neq0$.
Next I wanted to look at a module with $Fw\neq0$ but $F^e = 0$, but I cannot see why $Ew_0=aw_{e-1}$ should be true --- here, $w_p \equiv Fw_{p-1}$ with $w_0\equiv w$. In the first case, I proved it using
$$Ew_0 = \frac{1}{b}EFw_{e-1}$$
and then plugging in the Casimir element, but now that first step doesn't work anymore. Is the following possible?
\begin{align*}
Ew_0 \propto E^2 w_1 \propto \ldots\propto E^e w_{e-1},
\end{align*}
 but $E^e$ is in the center so acts by multiplication by a scalar. Thus, $Ew_0 = aw_{e-1}$. [Problem: what if $Ew_i$ vanishes somewhere?]
 Furthermore, assuming that $\alpha=\pm q^{j-1}$ leads to a contradiction: If $j=p+1$, then the form of $\alpha$ implies $$0=Ew_{p+1} = (FE + [E,F])w_p,$$ which is only possible if $\alpha =\pm q^{\frac{3}{2}}$.
For the last one I simply assume $Fw=0$, which implies $Ew\neq 0$, otherwise span of $w$ would be a 1-d submodule. Here we define $w_p = Ew_{p-1}$. It is easy to verify $Fw_{p+1}$, but again I am stuck with $Ew_{e-1}=cw_0$, and in particular I don't see why $c$ is nonzero.
Now, I would greatly appreciate any hint towards solving this. Thanks!

EDIT: To make it clear, my questions are basically:

Where does $Ew_0 = a w_{e-1}$ come from in the second part?
Where does $Ew_{e-1} = c w_0$ come from in the third part?
Why does $c$ have to be nonzero?
Why is the eigenvalue $\alpha$ of the form $\pm q^{j-1}$ in the last part?

These are the things that need to be accounted for, then the proof is finished.

EDIT #2:
I think the answer to  question 1 is as follows. This derivation:
\begin{align*}
Ew_0 \propto E^2 w_1 \propto \ldots\propto E^e w_{e-1},
\end{align*}
of $Ew_0=aw_{e-1}$ is valid iff not $\exists p$ s.t. $Ew_p=0$. And $Ew_p=0$ is equivalent to
\begin{align*}
q^{-(p-1)}\lambda - q^{p-1}\lambda^{-1} = 0.
\end{align*}
The existence of such a $p$ would also violate simplicity, btw.

EDIT #3:
Answers to the other questions: $KEw_{e-1}=\alpha Ew_{e-1}$ implies $Ew_{e-1}=cEw_0$, like before. If $\alpha=\pm q^{1-j}$, then $Fw_{p+1}=0$ for some $p$. The vectors $\{w_{p+1},..., w_{e-1}\}$ then span a $U_q$-submodule unless $c\neq 0$.
The only open question is now: Why is $\alpha$ of that form? Or rather: Is it true that, if $\alpha$ is not of that form, then the submodule is isomorphic to one of the first two?
Comment: If you don't receive an answer on Math Stack Exchange after a while, you might consider cross-posting this to Math Overflow (with a link to this original post).
Answer: I will summarize my results in this answer.

If we assume $Fw\neq0$ and $F^e=0$, then the derivation of our module being isomorphic to $V(\lambda, a,0)$ is almost the same as the first one, but we need to derive $Ew_0=aw_{e-1}$ differently, since now $Fw_{e-1}=0$. We know
\begin{align*}
Ew_0 \propto E^2w_1\propto\ldots\propto E^ew_{e-1},
\end{align*}
and since $E^e$ is in the center, this means $Ew_0 = aw_{e-1}$ for some (possibly zero) scalar $a$. Here it is important to note that we cannot have $Ew_p=0$ for some $w_p$, since then the subspace spanned by $\{w_p,...,w_{e-1}\}$ would be closed under $U_q$-action, contradicting simplicity.
But $Ew_p=0$ is equivalent to $\lambda = \pm q^{p-1}$ -- you should convince yourself of this if you don't see it. Thus we're done for this part.
For the last part, we of course assume the only possible case left: $Fw=0$. Necessarily, $Ew\neq 0$, otherwise $W$ would not be simple. And now I leave it as an easy exercise to verify that
\begin{align*}
\widetilde{V}(\pm q^{1-j},c) \cong V(\pm q^{j-1},0,c)
\end{align*} via the Cartan automorphism, that is, the map
\begin{align*}uv\mapsto \omega(u)v
\end{align*}
where $u\in U_q$, $v\in W$, and
\begin{align*}
\omega(E) = F, \quad \omega(F) = E \quad \omega(K) = K^{-1},
\end{align*}
is an isomorphism of $U_q$-modules. Simplicity then implies $c\neq 0$


How do we translate between Logic and Mathematical English?

Question: Take the statement "Let $a \in \mathbb{R}$ and let $z=ai.$" $(1)$
In English, this means "Let's choose any real $a$ then define $z$ such that $z=ai$ for that particular $a$ we have just chosen". All good there. We might use terms like "arbitrary constant" or "parameter" to describe $a$ too.
How do we write $(1)$ in formal logic?
I know that $\forall a \exists z (z=ai)$ is one option, but is that correct/the only one?
I know that $\forall a \forall z (z=ai)$ is wrong, and that so is $\exists z \forall a (z=ai).$
I know that "let" means to consider a specific real $a$ such that we can assume only that it's a member of $\mathbb{R},$ and $z$ if well-defined for this $a$ is defined for all $a \in \mathbb{R}.$ But then this implies $\forall a (z=ai),$ and it seems that each $a$ requires a different $z$ to make the statement true, i.e., $z$ depends on $a,$ yet $\forall a (z=ai)$ doesn't allow that.
Comment: Usually you would use this construction in a proof or similar place, where it would write as $\forall_a ((z=ai) \implies p(a,z,..))$ where $p$ is the statement you finally have at the end. Without such general context it does not make much sense because "let" itself is not introducing a proposition.
Comment: As a definition of $z$ given $a$
Comment: Of course if you want to be very formal then you should actually consider $z$ as a function which assigns to each real $a$ the number $ai$, and consequently call it $z(a)$, but then it would be impossible to read any mathematical text.
Comment: With no further context, how would you interpret "Let $z=ai$ where $a \in \mathbb{R}$?
Comment: But the only thing we know about $a$ is it is real, so $z=ai$ for all real $a$, right? But is that not a contradiction? We can write $\forall a$ ($ai$ is an imaginary number), but we cannot write $\forall a$ ($z=ai$ is an imaginary number) (My choice of $a$ is permitted to be arbitrary)
Comment: You claim "Given an arbitrary real $a$, $z = ai$", from this we cannot conclude $\forall a (z=ai)$ as that is false. In the case of induction once we have proven $P(k) \implies P(k+1)$ for arbitrary $k$ we can justify the $\forall$ quantifier, why can we not do that here? Is it correct to write $\forall a$(Define $z=ai$)?
Comment: A natural language sentence does not necessarily correspond to a complete proposition. It may well be that multiple sentences condense to one proposition. These discrepancies will **always** be there, because if there isn't, why make the effort in learning formal logic, since natural languages are already so close?
Answer: "Let" statements modify the context for subsequent content by introducing symbols and assumptions that can be referenced later. They don't translate to closed formal sentences themselves; the introduced variables are free until some later step produces a closed statement using e.g. universal generalization. In your example this could be something like $\forall a\forall z(z=ai\implies zi=-a).$
Statements of the form "Let $v=\dots$" can also be regarded as introducing notational abbreviations instead of adding any formal content.
Comment: @Mathguy you're describing a *definition*. A definition can be expressed as a natural language sentence but not as a closed formal sentence (unless you use a function symbol $z(a)$ as Michal suggests).
Comment: I just want to write $z$ in terms of $a$, there is no further steps, i,e I wish to be able to write sentences like "In particular, for $a = 1$ we have $z = i$", here $z$ and $i$ are equal only in the sub-context for which $a$ is chosen to be $1$.
Comment: If I wrote "Given $a \in \mathbb{R}$ we define $z = ai$" then I cannot generalise and write $\forall a (z=ai)$ because "$z=ai$" is not some property that I am assessing whether an arbitrary real $a$ has or not, we know to prove $\forall a P(a)$ start with proving $P$ for arbitrary $a$, then generalising, but this isn't possible in my circumstance.
Comment: How do we write the definition in natural language (English) then?
Comment: You mention closed, how do we write an open sentence for the definition?
Comment: The open sentence is just "$z=ai$".
Answer: Since this is only a part of a mathematical text, I suggest to write
$$a \in \mathbb R \land z=ai.$$
Since your text is not a statement, you cannot write it as a closed formula. When you prove the statement $a \in \mathbb R \land z=ai \Rightarrow \phi(a,z)$ for some formula $\phi(a,z)$, you can put quantifiers before: $\forall z \forall a (a \in \mathbb R \land z=ai \Rightarrow \phi(a,z))$; equivalently: $\forall z \, \forall a \in \mathbb R (z=ai \Rightarrow \phi(a,z))$.
I recommend you not to use formulae at places English is better understandable. From my suggestion, it is not clear that $a \in \mathbb R$ is a definition, so your sentence $(1)$ is perfectly fine. Definitions are usually written with colon, i.e., $a:=b+c$ or
$$(a,b,c) \text{ is a pythagorean triple} :\Leftrightarrow a^2+b^2=c^2.$$
For your definitions, this would give $a :\in \mathbb R \land z:=ai$, but I never saw the symbol $:\in$, so it would be difficult to parse.
I think the reason why I did not see the symbol $:\in$ is that this definition is not unique. Picking an arbitrary element of a set usually leads to open formulae as I suggested.
Answer:
Take the statement "Let $a \in \mathbb{R}$ and let $z=ai.$" $(1)$

Here, you are assigning a denotation ($z:=ai$) and a restriction ($a$ belongs to a strict subset of the discourse domain $\mathbb C$).
And in such statements, it is tacit that $a$ is arbitrary.
So, $(1)$ means

Let $a$ be an arbitrary real number and let $z$ denote $ai.$

In English, this means "Let's choose any real $a$ then define $z$ such
that $z=ai$ for that particular $a$ we have just chosen".

Sure, but a key point of $(1)$'s intended meaning is that we are free to vary the value of $a.$

"arbitrary constant" to describe $a$

Yes: in the large, $a$ is variable ("arbitrary"), while within any iteration of what follows $(1),\,$ $a$ has a particular value ("constant").

How do we write $(1)$ in formal logic?
I know that $\forall a \exists z (z=ai)$ is one option, but is that
correct/the only one?

$(1)$ is the beginning fragment of a proof, and isn't really an assertion so isn't really an FOL sentence. After Universal Generalisation has been invoked, you might then end up with, for example,

$\forall a{\in\mathbb R}\;\forall z{\in\mathbb C}\;(z=ai\implies iz=-a)$

or

$\forall a{\in\mathbb R}\;(ai^2=-a).$


Is there a way to nest fixture parametization in pytest?

Question: I have an example where I have essentially a nested list of fixtures i.e fn2 below depends on the value of the fixture fn1 and is not know ahead of time. Each of these two functions needs to call a server to retrieve a list of parameters.
<code>@pytest.fixture(params=generated_list())
def fn1(request):
    return request.param

@pytest.fixture(params=generates_list_2(fn1))
def fn2(request):
    return request.param

def test_fn(fn2):
    assert fn2 == 0
</code>
Answer: While it's not a great answer this will work. It exploits a hook in the test generation procedure to manually generate the combinations of params.
<code>def generated_list():
    return x

def generates_list_2(fn1):
    return x

def pytest_generate_tests(metafunc):
    if 'fn1' in metafunc.fixturenames and 'fn2' in metafunc.fixturenames:
        metafunc.parametrize(
            "fn1, fn2",
            [(i, j) for i in generated_list() for j in generated_list_2(i)]
        )

@pytest.fixture()
def fn1(request):
    return request.param

@pytest.fixture()
def fn2(request):
    return request.param

def test_fn(fn1, fn2):
    assert fn2 == 0
</code>
Answer: Yeah, you can nest fixtures. Just use one fixture as one of the arguments of other fixture as you would use a fixture in a test.
Your code would look like this:
<code>@pytest.fixture(params=generated_list())
def fn1(request):
    return request.param

@pytest.fixture(params=generates_list_2(fn1))
def fn2(request, fn1):
    return request.param

def test_fn(fn2):
    assert fn2 == 0
</code>
Comment: the `fn1` argument to `generates_list_2(fn1)` is not available to the decorator function and raises an error.
Comment: You can convert the generates_list_2(fn1) function into a fixture. Pytest does not initialize the helper function outside of the test function scope.
Comment: I need to paramtrize the fixture in terms of a second fixture both of which are dynamically sized and generated. Simply creating a fixture called generates_list_2 wouldn't work because it would return a list not a single item


Combinatorial interpretation of polynomials

Question: I'm reading a proof for the following identity:
$$\sum_{k}A_{k}(r,t)A_{n-k}(s,t) = A_{n}(r+s, t), \qquad \text{integer} \ n \geq 0 \tag{1}$$
where $A_{n}(x,t)$ is the $n$th degree polynomial in $x$ that satisfies
$$A_{n}(x,t) = \binom{x-nt}{n}\frac{x}{x-nt}, \qquad \text{for} \ x \neq nt. \tag{2}$$
The author starts off by assuming that $r \neq kt \neq s$ for $0 \leq k \leq n$, since both sides of (1) are polynomials in $r, s, t$.
Question: I understand that we need $r \neq kt$ to prevent division by zero in $A_{k}(r,t) = \binom{r-kt}{k}\frac{r}{r-kt}$, but why are we also allowed to assume $kt \neq s$ for $0 \leq k \leq n$?
Writing $A_{n-k}(s,t)$ in terms of (2), we have
$$A_{n-k}(s,t) = \binom{s-(n-k)t}{n-k}\frac{s}{s-(n-k)t}$$
If $s=kt$, then
$$
A_{n-k}(kt,t) = \binom{kt-(n-k)t}{n-k}\frac{kt}{kt-(n-k)t}
= \binom{2kt-nt}{n-k}\frac{kt}{2kt-nt}
$$
...which doesn't result in division by $0$ if $k=0$ or if $k=n$, so why is $s \neq kt$ needed?
Comment: You need $s \ne (n-k)t$ for $0 \le k \le n$, and the set $\{ n-k | 0 \le k \le n \}$ is equal to $\{ k | 0 \le k \le n \}$.
Comment: No division by zero appears since $\,A_{n}(x,t) = \binom{x-nt-1}{n-1}\frac{x}{n}\,$ for $\,n>0.$
Comment: Thanks @Somos, but why do we change to $n > 0$? Eq. (1) is defined for $n \geq 0$.
Comment: $A_0(x,t) = 1\,$ and my alternative definition has division by $\,n\,$ hence $\,n\ne 0\,$ is required there.
Comment: @Somos, I see, but then would we still be able to prove that identity (1) holds even when $n=0$ or $k=0$ (since (1) is defined for all $n \leq 0$ and $0 \leq k \leq n$)? The author actually rules out using the alternative definition since it fails for $k=0$ (see Example 4 on [this page](https://books.google.co.nz/books?id=x9AsAwAAQBAJ&pg=PA48&lpg=PA48&dq=%22since+both+sides+of+(30)+are+polynomials+in+r,s,t%22&source=bl&ots=B-13K7P19H&sig=ACfU3U1YdoPPWQiYqymdm-gRYGMhKRE64A&hl=en&sa=X&ved=2ahUKEwiWuLKqodv2AhXrSWwGHYaTAfgQ6AF6BAgCEAM#v=onepage&q&f=false)).
Comment: @MikeEarnest, PS I've corrected the post and added a link to the original text if it helps with clarity.
Comment: Thank you @Zerox! That's a really neat observation. But I'm not sure I understand how that equivalence works for *given* values of $n$ and $k$. Say $n = 5$ and $k = 3$, then how is $s \neq 2t$ equivalent to $s \neq 3t$?
Comment: Why does the overall sum remain unchanged?
Comment: They are not equivalent. The reason behind the assumption is that you need them **all satisfied** (i.e. for all $0 \le k \le n$ the inequality holds) to make the sum valid.
Comment: @Zerox, I get that, but wouldn't replacing $s \neq (n-k)t$ with $s \neq kt$ at each iteration affect the computation of the overall sum? Like, for $n=2$, wouldn't we end up summing over
$A_{n-0}$ [for $s \neq 0$] +
$A_{n-1}$ [for $s \neq 1$] +
$A_{n-2}$ [for $s \neq 2$]
...instead of
$A_{n-0}$ [for $s \neq (n-0)$] +
$A_{n-1}$ [for $s \neq (n-1)$] +
$A_{n-2}$ [for $s \neq (n-2)$]? These two summations don't seem to be equivalent to me.
Comment: @user51462 The inequalities should be satisfied at the **same time**, i.e. the sum should be $A_{n-0}$ [for $s \ne 0 \cdot t \wedge s \ne 1 \cdot t \wedge ...$] $+A_{n-1}$ [for $s \ne 0 \cdot t \wedge s \ne 1 \cdot t \wedge ...$] $+...$ etc.
Comment: @Zerox, could you please explain why we need to take the intersection of all inequalities? I've never encountered this before. Also, I had asked this question in chat rather than in the comments section yesterday because of the "Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?" message, but the chat seems to have been deleted.
Answer: Since $A_k(r, t)$ appears in $(1)$, in order to use the expression $A_k(r, t)=\binom{r-kt}{n}\frac{r}{r-kt}$, you need to assume $r\neq kt$ for all $k\in \{0,1\dots,n\}$ because this is a restriction given in $(2)$.
Since $A_{n-k}(s, t)$ appears in $(1)$, in order to use the expression $A_{n-k}(s, t)=\binom{s-(n-k)t}{n}\frac{s}{s-(n-k)t}$, you need to assume $s\neq (n-k)t$ for all $k\in \{0,1\dots,n\}$, because this is a restriction given in $(2)$.
That is, the author needs to assume

$r\neq kt$ for all $k\in \{0,\dots,n\}$ and $s\neq (n-k)t$ for all $k\in \{0,\dots,n\}$.

The point is, the above is equivalent to assuming

$r\neq kt$ for all $k\in \{0,\dots,n\}$ and $s\neq \color{red}kt$ for all $k\in \{0,\dots,n\}$.

The reason that the second assumptions are equivalent to the first is that, as $k$ runs through all of $\{0,\dots,n\}$, so does $n-k$, so it is OK to replace $(n-k)$ with $k$.
The second set of assumptions can also be written as $r\neq kt\neq s$ for all $k\in \{0,\dots,n\}$.
Comment: Thank you @MikeEarnest. When you say it is ok to replace $(n-k$ with $k$, I thought that meant replacing $(n-k)$ with $k$ for *each* iteration of the sum, e.g. for n=2, sum over An−0 [for s≠0] + An−1 [for s≠1] + An−2 [for s≠2] ...instead of An−0 [for s≠(n−0)] + An−1 [for s≠(n−1)] + An−2 [for s≠(n−2)]. But Zerox said that the inqualities must be satisfied at the same time, i.e. the sum should be $An−0 [for s≠0⋅t∧s≠1⋅t∧...] +An−1 [for s≠0⋅t∧s≠1⋅t∧...]$ (see second last comment under my post). I don't quite understand why though. Would it please be possible to elaborate on this in your answer?
Comment: @user51462 I have already explained the entire situation the only way I know how, I have nothing else to add.
Answer: In order to prove
$$ \sum_{k}A_{k}(r,t)A_{n-k}(s,t) = A_{n}(r+s, t), \tag{1} $$
it suffices to define the ordinary generating functions
$$ f(z) := \sum_{n=0}^\infty A_n(x,t)z^n \tag{2}$$ and
$$ g(z) := \sum_{n=0}^\infty (-1)^n\binom{(t+1)(n+1)-1}{n}z^n. \tag{3}$$
Using standard properties of generating functions,
equation $(1)$ is equivalent to
$$ x\int_0^z g(z)\,dz = \log(f(z)). \tag{4} $$
It is elementary to show that $\,A_0(x,t) = 1\,$ and that
$$ A_{n}(x,t) = \binom{x-nt-1}{n-1}\frac{x}{n} \tag{5}$$
for $\,n>0\,$ given the original definition of $\,A_n(x,t)\,$
as an $n$th degree polynomial in $\,x.$ This approach avoids
the need for discussing any possible division by zero.
Comment: Thank you @Somos, but I was hoping to understand where the $kt \neq s$ condition in the original proof came from.
Answer: This is a matter of symmetry. Somewhat more detailed the identity is written as
\begin{align*}
\sum_{k=0}^nA_k(r,t)A_{n-k}(s,t)=A_n(r+s,t)\tag{1}
\end{align*}
From the definition
\begin{align*}
A_{n}(x,t) = \binom{x-nt}{n}\frac{x}{x-nt}, \qquad \text{for} \ x \neq nt.\tag{2}
\end{align*}
it follows the term $A_k(r,t)$ has to fulfill the restriction $r\neq kt$ for $0\leq k\leq n$.

On the other hand, changing the order of summation in (1) $k\to n-k$ gives the same identity
\begin{align*}
\sum_{k=0}^nA_{n-k}(r,t)\color{blue}{A_{k}(s,t)}=A_n(r+s,t)\tag{3}
\end{align*}
From the representation (3) we see that also the term $A_{k}(s,t)$ has to fulfill the restriction $s\neq kt$ for $0\leq k\leq n$.

Hint: A thorough introduction in working with sums is given in chapter 2: Sums, especially in section 2.3: Manipulation of Sums in Concrete Mathematics
by R. L. Graham, D. Knuth and O. Patashnik.
Comment: Thank you @epi163sqrt. Just to clarify my understanding, we're not so much replacing $s \neq (n-k)t$ by $s \neq kt$, but rather just using the fact that $\sum_{k=0}^nA_k(r,t)A_{n-k}(s,t)=\sum_{k=0}^nA_{n-k}(r,t)A_{k}(s,t)$ to say that both $s \neq (n-k)t$ and $s \neq kt$ hold *at the same time*, is this correct? Also, is it this symmetry that the author is referring to when they say  "We may assume that $r≠kt≠s$ for $0≤k≤n$, **since both sides of (1) are polynomials in $r,s,t$**"? I wasn't sure how $r≠kt≠s$ for $0≤k≤n$ followed from both sides being polynomials in $r, s, t$.
Comment: @user51462: Yes this is correct. The author addresses the symmetry. We usually don't say that it *follows* that $r\neq kt$ and $s\neq kt$ for $0\leq k\leq n$, but we have *to assure* that $r\neq kt$ and $s\neq kt$ for $0\leq k\leq n$ since otherwise we have division by zero.
Comment: @user51462: Saying $r\neq kt$ for $0\leq k\leq n$ and $r\neq (n-k)t$ for $0\leq k\leq n$ is *in this context* the same. Note, we have due to *commutativity of addition* $\sum_{k=0}^n a_k=a_0+a_1+\cdots+a_{n-1}+a_n=a_n+a_{n-1}+\cdots+a_1+a_0=\sum_{k=0}^n a_{n-k}$, which is just a reordering of the summands.
Comment: @user51462: Many thanks for granting the bounty. :-)


Ajax post with one parameter

Question: How can you pass / as part of a parameter in an Ajax call?
The address is http://studiga.delta-xray.co.uk/delete_favourites/%3Cspan%20class%3D%22remove-favourite%22%3E%26nbsp%3B%3C%2Fspan%3E%3Ca%20class%3D%22title%22%20href%3D%22http%3A%2F%2Fstudiga.delta-xray.co.uk%2Fproperties%2Fliverpool-property%22%3ELiverpool%20property%20Address%20line%201%3C%2Fa%3E%3Cspan%20class%3D%22address%22%3E%20Address%20line%202%20Town%20L2%206RE%3C%2Fspan%3E and I wanted just one parameter, but it is treating %2F as /.
function delete_favourites_permission() {
  return array(
    'access favourites content' => array(
      'title' => t('delete favourites via ajax'),
    )
  );
}

function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function delete_favourites_page($line) {
    echo $line;

    $result = "vvvv";
    drupal_json_output($result);
    exit();
}

echo $line; prints  .
How can I get it to work?
Comment: ideally you would give an id as second parameter, so $line will be $id and the url http://studiga.delta-xray.co.uk/delete_favourites/345 how do you set this second parameter, why do you set it with html ??
Answer: What I think you are trying to do is delete a record from the database, someones 'favorite', like a bookmark on content, perhaps.
Anyway, what you need is an argument in the URL, the best being an ID - even better if it is an entity id that could be provided as a loaded argument for you (like node/%node - the %node argument provides the loaded node instead of just node id).
Assuming the argument is simply an integer of a database record, you could do:
function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites/%'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'delivery callback' => 'ajax_deliver',
  );

  return $items;
}

function delete_favourites_page($favorite_id) {
    // code to delete the favorite_id record
    $commands = array();
    $commands[] = ajax_command_alert('Favorite has been deleted.');
  return array('#type' => 'ajax', '#commands' => $commands);
}

However, your access callback should not be TRUE, that means anyone can hit this URL and there is no upfront access checking. I hope you are handling that in your callback, but ideally you should use permissions or a callback to perform more complex checking.
The ID will always be passed to the page callback function now, and you could perform the delete operation there.
The delivery callback has been set as ajax deliver, which tells Drupal the page will return ajax commands. The above code contains a very simple alert, which will fire when the callback is performed.
There is a decent amount more that can go into this when wanting to implement AJAX interactions via menu items and callbacks. But first you need to figure out / fix your URL structure so you can pass arguments and not strings / query strings, and you'll also want to implement access checking so only the user who owns that record (or admin) can delete it.
Comment: Not quite - a cookie. Ok I will change the TRUE.The rest will have to be split up as separate parameters and then put back together again
Comment: I am a bit confused over access callback. If it  isn't true then can only the page that calls it can access it?

Ajax post with one parameter


Criação de tabelas com cardinalidade 1 : N

Question: Tenho duas tabelas, PRODUTOS e INSUMOS. Para criar um produto preciso de vários insumos, gostaria de saber como devo proceder com essa relação no MySQL.
Devo criar uma tabela chamada COMPOSICAO e nela trabalhar somente com chave estrangeira, essa seria uma forma, existem outras?
Como devo proceder com esse tipo de ralação no Laravel?
Comment: Isso vai depender do contexto ou do escopo. Para você o que seria esta `COMPOSICAO`? Aproveite e faça um [tour] também.
Comment: vou dar um exemplo de como imagino `COMPOSICAO`, digamos que vc vai fabricar um carro, quais os itens que compõe o carro, motor, caixa de marcha, parabrisa etc.
Comment: Dá uma pesquisada sobre formas normais, no seu caso se aplica a 3a forma normal.http://aprendaplsql.com/modelagem-de-dados/normalizacao-banco-de-dados/
Answer: Normalmente precisa de uma tabela auxiliar de associação ou amarração ou intersecção de produtos com insumos (isto é chamado entidade associativa), onde fará a ligação entre eles. Imagino que seja essa composição que está falando, mas não tenho certeza por não ter detalhes.

Em essência terá o código do produto e o código do insumo em cada linha e que já será a chave primária. É comum ter uma chave secundária com o inverso insumo-produto. Não sei se é isso que quer dizer com chave estrangeira.
Especificamente no Laravel não sei o que fazer, mas imagino que deva ter que criar uma tabela assim no modelo dele. Eu sei que alguns tenderão a querer fazer um grafo de objetos em memória. Pra mim isso é um erro, reproduza o modelo do banco de dados e seja mais feliz.
Comment: Caso eu faça como citei acima não estarei fazendo errado??
Comment: Imagino que está tudo ok, se fizer como eu falei.
Answer: Se um insumo não se repetir em mais de um produto, você pode colocar uma chave estrangeira na tabela Insumos,
Insumos (*id*, nome, idproduto)
Produto (*id*, nome)

Assim, você garante que nenhum outro produto terá aquele insumo.
Caso contrário, você está correto. Deve-se ter uma tabela auxiliar do tipo Composição,
Composição (*idproduto, idinsumo*)


Index of image subgroup of $\mathbb{Z}^2$ by a linear transform

Question: The image of $\mathbb{Z}^2$ by a linear transform given in canonical basis by $T = \begin{bmatrix}1&-3\\1&2\end{bmatrix}$ is a subgroup of $\mathbb{Z}^2$ of index:
Answer: 5.
How do I do this? For what I searched, $\rm{ind}(T)=\rm{dimKer}T - \rm{dimCok}T$, but by gaussian elimination I have that $\rm{Ker}T=\{0\}$, so this difference can't be 5.I think index of linear transform is different than index of image as a subgroup. But then I'm really lost, allI know that may help is Lagrange theorem..
Thanks.
Comment: Subtracting the first row from the second gives $\pmatrix{1 & -3\\0&5}$..
Comment: There are several posts on generalizations of this question, such as: [1](https://math.stackexchange.com/questions/317065/question-on-determinants-of-matrices-changing-between-integer-matrices), [2](https://math.stackexchange.com/questions/834431/quotient-group-mathbb-zn-textima), [3](https://math.stackexchange.com/questions/65913/why-is-the-determinant-equal-to-the-index).
Comment: Think about this question: The image of $\mathbb{Z}$ by the linear transform given by $T(n)=5\cdot n$ is a subgroup of $\mathbb{Z}$ of index 5
Comment: @Sheve, that I can see, because there are 5 classes. But how do I analyze Z^2? Do I have to look at the determinant?
Answer: In our case try and look at point not in the image, we have here that a point $(c,d)$ is the image of $(a,b)$ iff $T(a,b)=(c,d)$ this leads us the the equation $c+5b=d$ i.e. $c\sim d$ mod$_5$.
So we obtain that $(c,d)$ is in Im($T$) iff $c\sim d$ mod$_5$.
This leads us to co-sets $(0,i)$ for $i\in \{0,1,2,3,4\}$ obviously $(0,i) \nsim (0,j)$ for $i\ne j$ and any $(a,b)\in \mathbb{Z}^2$ is conjugate to one of then since $(0,b)\sim (i_a,i_b)\sim (0,i_a-i_b)$  where $i_a+5k=a$


Show that $x^2 + 1$ is irreducible over $\Bbb Z_3$ and reducible over $\Bbb Z_5$

Question: Show that $x^2 + 1$ is irreducible over $\Bbb Z_3$ and reducible over $\Bbb Z_5$.
I can't figure any way to express $x^2 + 1$ as a product of two polynomials in either ring.  Each product I try either ends up with a number being off by $1$ or $2$.
Anyone have any ideas?
Comment: More generally, $x^2+1$ is irreducible in $\mathbb Z_p$ (where $p$ is prime) if and only if $p$ is of the form $4k+3$, $k\in\mathbb Z$. See [Quadratic Reciprocity](https://en.wikipedia.org/wiki/Quadratic_reciprocity#.C2.B11_and_the_first_supplement).
Comment: How about you calculate the roots with the quadratic formula, instead of making some blind guess?
Comment: @G.Sassatelli  What do you mean?  I don't see how I would use this for $\Bbb Z_3$
Comment: In $\mathbb{Z}_5$, $x^2+1= (x-3)(x-2)$ (or equivalently $(x+3)(x+2)$), for instance.
Comment: You can use the set of quadratic residues modulo $\{3,5,...\}$ to determine whether there is a factor; in particular, modulo $5$, the residues are $0,1,4,4,1$, showing that $2,3$ are roots.
Comment: If $f(x)g(x)=x^2+1$, then (up to an invertible constant) $f(x)=x-\alpha_1$ and $g(x)=x-\alpha_2$, where $\alpha_1,\alpha_2$ are the roots of $x^2+1$ in $\Bbb Z_3$. These must be given by $2^{-1}\cdot(-0\pm\beta)$, where $\beta$ is any number such that $\beta^2=0^2-4\cdot 1=-1$.
Answer: You can check the roots. Over $\mathbb{Z}_3$ we have $$0^2 + 1 = 1 \qquad 1^2 + 1 = 2 \qquad 2^2 + 1 = 2$$ Hence $x^2 + 1$ is irreducible. Over $\mathbb{Z}_5$ we have $$2^2 + 1 = 0 \qquad 3^3 + 1 = 0$$ Thus $$x^2 + 1 = (x + 2)(x + 3)$$ is reducible.
Comment: Modulo $5$: $x^2+1=x^2-4=(x-2)(x+2)$.
Comment: But how would you write $x^2 + 1$ as a product of two polynomials in $\Bbb Z_3[x]$ with one of them being a unit?
Comment: $1 \cdot (x^2 + 1)$ or $2 \cdot (x^2 + 1)$.
Comment: Ah, I see I was misunderstanding the definition of an irreducible polynomial.  So reducibility for $\Bbb Z_5$ would imply that just there exists a product combination that is not a unit $\times$ un-reducible expression?
Comment: Roughly speaking, an irreducible polynomial is a non-constant polynomial, which cannot be factored as two non-constant polynomials. A non-irreducible polynomial is said to be reducible.
Comment: How does $2 \cdot (x^2 + 1) = x^2 + 1$ in $\Bbb Z_3$?
Comment: I think that was dumb. $2$ is for sure a unit of $\mathbb{Z}_3$, but the product is wrong. It is not $x^2 + 1$. Sorry.
Answer: Here's a proof of the simple result described in the comments: $ x^2 + 1 $ is a quadratic, so it is irreducible over a field $ K $ if and only if it has no roots there. Thus, $ x^2 + 1 $ is irreducible in $ \mathbf F_p $ for an odd prime $ p $ if and only if $ -1 $ is not a quadratic residue in $ \mathbf F_p $. Since the group $ \mathbf F_p^{\times} $ is cyclic, this happens if and only if $ |\mathbf F_p^{\times}| = p-1 $ is not a multiple of $ 4 $, that is, iff $ p \equiv 3 \pmod{4} $.
Answer: $ x^2\equiv \text{ either } 1,0 \pmod 3 $
So adding $1$, you can't get zero remainder.
But that is not so in case of 5.
$ 2^2 + 1 =0$
 (mod $5$)


Intel 8086 Assembly procedure calling from C

Question: I need to develop a procedure for Assembly language and call that procedure from C language (pass a string and return an integer value). My assembly procedure works fine "stand-alone". I need help with connecting them together.
Program is supposed to run on Intel 8086. I need to use MASM or emu8086 as assembler/simulator. Kindly recommend a C compiler and also a way to make the simple C program that is able to call the assembly procedure and get the returned value.
How can I pass a string to this external function?
How can I connect the ASM file and the C file? (How will the compiler know where is the definition/code for this procedure?)
How can I get the string sent from C in Assembly language, also how to return the integer to C?
Comment: Since you didn't upvote or even comment, I deleted my answer.
Answer:
recommend a C compiler

Not enough info, however if your platform is significant enough, chances are that GCC already supports it.

and also a way to make the simple C program that is able to call the assembly procedure and get the returned value.

The way for writing simple C programs is using a text editor. (Oh wait, you're interested in the code? Here it goes:
<code>#include <stdio.h>

extern int foo();

int main()
{
    int i = foo();
    printf("%d\n", i);
    return 0;
}
</code>
Comment: Thank you for the prompt reply. Yes this is exactly what i need. Just a few clarifications/suggestions. Sorry for not providing sufficient information in the first place.

How can i pass a string to this external function?
How can i connect the ASM file and the C file? (How will the compiler know where is the definition/code for this procedure?)
How can i get the string sent from C in Assembly language, also how to return the integer to C?

THANK YOU SO MUCH!
Comment: @user1969973 You read a C tutorial before asking? `foo("HelloWorld");`


Doubling part's staves in LilyPond

Question: I am trying to typeset some music in Lilypond, where there is a player doubling on an auxiliary instrument.  I would like the 2nd flute player to change to 2nd piccolo.  But I also want the staves to be displayed in the right order (i.e. Picc. 1, Picc. 2, Fl. 1, Fl. 2)

A minimal example code is provided below which almost works, however the old staff remains even though it is empty:

I don't want to use \RemoveEmptyStaves, because there are staves (with rests) throughout the score that I do want displayed.

Is there some other way to "kill" the old staff?

Is there another way to write a doubling player's part on different staves?

Another approach that I have tried, is keeping a single staff for the doubling player (by removing/commenting-out the line marked with the asterisks *** in the code below).  This is much like the example on the parts-writing page of the documentation.
I can reset staff's shortInstrumentName, but the alignBelowContext does not seem to work, so the staff doesn't move into the right place:
(resetting the midiInstrument doesn't work either)

Code
    \version "2.21.0"

    piccoloOne = {
        \new Staff = "piccolo-one" {
            \set Staff.instrumentName = "Piccolo 1"
            \set Staff.shortInstrumentName = "Picc. 1"
            \set Staff.midiInstrument = #"piccolo"
            \transposition c''
    % 1
                fis''1~ | fis''1~ |
    % 3
                fis''1 |
        }
    }

    fluteOne = {
        \new Staff {
            \set Staff.instrumentName = "Flute 1"
            \set Staff.shortInstrumentName = "Fl. 1"
            \set Staff.midiInstrument = #"flute"
            \transposition c'
    % 1
                b'1~ | b'1~ |
    % 3
                b'1 |
        }
    }

    fluteTwoDoublingPiccoloTwo = {
        \new Staff {
            \set Staff.instrumentName = "Flute 2"
            \set Staff.shortInstrumentName = "Fl. 2"
            \set Staff.midiInstrument = #"flute"
            \transposition c'
    % 1
                d'1 | R1^\markup{"muta in Picc. 2"} | \break
    % MUTA
        } \new Staff { %  ***
            \set Staff.alignBelowContext = #"piccolo-one"
            \set Staff.shortInstrumentName = "Picc. 2"
            \set Staff.midiInstrument = #"piccolo"
            \transposition c''
            \once\override Staff.TimeSignature #'stencil = ##f
    % 3
                d''1~ |
        }
    }

    \score {
        \new StaffGroup
            <<
                \piccoloOne
                \fluteOne
                \fluteTwoDoublingPiccoloTwo
            >>

        \layout {
            indent = 20
            short-indent = 10
        }

        \midi { }
    }

Update: Solution
Following the accepted answer below, the trick is:

to use VerticalAxisGroup.remove-layer for each of the doubling part's staves,
and the Keep_alive_together_engraver for the staff group:

Updated Code
    \version "2.21.0"

    piccoloOne = {
        \new Staff = "piccolo-one" {
            \set Staff.instrumentName = "Piccolo 1"
            \set Staff.shortInstrumentName = "Picc. 1"
            \set Staff.midiInstrument = #"piccolo"
            \transposition c''
    % 1
                fis''1~ | fis''1~ |
    % 3
                fis''1 |
        }
    }

    fluteOne = {
        \new Staff {
            \set Staff.instrumentName = "Flute 1"
            \set Staff.shortInstrumentName = "Fl. 1"
            \set Staff.midiInstrument = #"flute"
            \transposition c'
    % 1
                b'1~ | b'1~ |
    % 3
                b'1 |
        }
    }

    fluteTwoDoublingPiccoloTwo = {
        \new Staff
        \with { \override VerticalAxisGroup.remove-layer = 2 } {
            \set Staff.instrumentName = "Flute 2"
            \set Staff.shortInstrumentName = "Fl. 2"
            \set Staff.midiInstrument = #"flute"
            \transposition c'
    % 1
                d'1 | R1^\markup{"muta in Picc. 2"} | \break

        }
    % MUTA
        \new Staff
            \with { \override VerticalAxisGroup.remove-layer = 1 } {
            \set Staff.alignBelowContext = #"piccolo-one"
            \set Staff.shortInstrumentName = "Picc. 2"
            \set Staff.midiInstrument = #"piccolo"
            \transposition c''
            \once\override Staff.TimeSignature #'stencil = ##f
    % 3
                d''1~ |
        }
    }

    \score {
        \new StaffGroup
            \with { \consists "Keep_alive_together_engraver" } {
            <<
                \piccoloOne
                \fluteOne
                \fluteTwoDoublingPiccoloTwo
            >>
        }

        \layout {
            indent = 20
            short-indent = 10
        }

        \midi { }
    }

Answer: What you want is the VerticalAxisGroup.remove-layer property. You can find a code example exhibiting similar behavior to what you want at http://lilypond.org/doc/v2.23/Documentation/notation/modifying-single-staves#hiding-staves.
Comment: On the first few readings of the page you link to, I was thinking that the example with violins wasn't the right way to go because it uses `\RemoveAllEmptyStaves`, and it's an example of "divisi" not "muta", so the parts are in parallel not sequential. Which I didn't think would work.

However I was eventually able to just use `VerticalAxisGroup.remove-layer` for each staff, and `Keep_alive_together_engraver` for the staff group to achieve what I want, without changing to parallel structure or even needing the `\RemoveAllEmptyStaves` command at all.
Comment: @Aaron - Since the questioner specified, "I don't want to use `\RemoveEmptyStaves`," and the example that you posted uses `\RemoveAllEmptyStaves` (which I think identical to the former, except that it also affects the first system), is there any way to use `VerticalAxisGroup.remove-layer` apart from those commands? Or is it meant to be used only in conjunction with them?
Comment: @Neal I gathered that the reason OP didn't want `\RemoveAllEmptyStaves` was because it removed staves with only rests. The `remove-layer` property sidesteps that problem. But to the best of my knowledge, they operate together.

Doubling part's staves in LilyPond


Amazon ec2 or Google cloud separate billing

Question: I gave got a software which is installed on multiple ubuntu/ec2 machines.
I need the same setup for multiple clients. Each client should only be given option to

pay the bill,
scale the ec2 machines
start the ec2 machine
stop the ec2 machine

Each clients bill will be paid by the client themselves and I should not interfere. If unpaid his account should be terminated automatically and I cannot be held responsible.
Can this be achieved in aws or google cloud ?
Answer: In GCP for the payments you may give the users permissions of Billing administrator
For the VM's you might create a custom role with individual Compute permissions
(instance.start, instance.stop, instance.start, instance.setmachinetype, etc)


Comparing enumerations on the same infinite set

Question: Given two enumerations $A:S \to \mathbb{N}$, $B:S \to \mathbb{N}$ on the same countably infinite set $S$, are there infinitely many elements $s \in S$ with $A(s) \geq B(s)$?
My feeling is that there must be, i.e. that it cannot be the case that all but a finite number of elements of S appear in B before A, but I can't come up with a proof to support this feeling.
Am I correct? If so, could I have a hint for a proof?
Comment: Somehow I don't think you're using the term "total order" in its standard mathematical sense. Please define what you mean by a "total order".
Comment: You can compare something in A or in B or in some fixed enumeration of the countable set. What you're doing here seems to be comparing apples to gravel.
Comment: Oh, also "total order" is not interchangeable with an injective function from $\Bbb N$ into a set $S$. I don't know where you learned this, but it would be wise to unlearn that. If you want to cast your question in terms of injections from $\Bbb N$, that's fine. But you should be very clear as to what you mean and make sure that you don't misuse existing standard terminology. This is just part of communicating with people.
Comment: What is definition of A-index and B-index?
Comment: I mean the position of the element in the total orders A and B, if we consider the total orders as enumerations of S.
Comment: Is it not clear? Conceiving of $A$, $B$ as functions from $S$ to $\mathbb{N}$, how many elements $s \in S$ have $A(s) \geq B(s)$? Can this number ever be finite? For $S$ countable there must exist functions to $\mathbb{N}$ by definition, and by total order I just mean one such function.
Comment: So you're using "total order" to mean "enumeration"? Or else, where is the comparison taking place? If $S$ carries two linear orders $<_1$ and $<_2$, and also two enumerations $A$ and $B$, what do you even mean by that? And if no, then where do you compare $A$ and $B$? In $\Bbb N$? You just said that the domain is $\Bbb N$ not $S$, so what is $S$? And if you're just asking about functions, why not just ask it like that: given two functions $F,G\colon\Bbb{N\to N}$, is it necessarily the case that infinitely many elements satisfy $F(n)<G(n)$? In which case, no, just take $G(n)=0$.
Comment: Yes I am using those terms interchangeably. A correction to my previous comment, is that $A$ and $B$ are injective functions. I don't believe that I said the domain is $\mathbb{N}$, but of course you can think of $S=\mathbb{N}$ if that helps.
Comment: I beg to differ. The version of the comment that I saw said that they are functions ***from*** $\Bbb N$. That, at least in standard jargon, mean that they are functions whose domain is $\Bbb N$. Please don't try to cast me as misreading your original comment, which was edited 7 times.
Comment: I didn't mean to come across as confrontational. I was honestly kind of intimidated asking this question because I thought I wouldn't phrase it properly, which is why I got flustered and kept making mistakes in my comment, you're probably right and one version did say 'from' $\mathbb{N}$ by mistake. Would the following be clearer: given a countable set $S$ and and two bijections $A: \rightarrow \mathbb{N}, B: \rightarrow \mathbb{N}$, will there always be infinitely many elements $s \in S$ with $A(s) \geq B(s)$?
Comment: In my opinion the formulation in your last comment is much clearer, except that I'd write $A:S\to\mathbb N,B:S\to\mathbb N$ instead of $A:\to\mathbb N,B:\to\mathbb N$ which looks weird.
Comment: Ok thanks. Is it correct to refer to these functions as enumerations?
Answer: Answering the version in your 4th comment, Yes.
Combining the inverse of B with A the question becomes: if $f:\mathbb N \to \mathbb N$ is a bijection, can there be only finitely many n with $f(n) \geq n$. To see not, suppose there is and let $M = max \{f(n) : f(n) \geq n \} $. Now look at the image of $\{1,2,...,M+1 \}$.
Comment: Ah yes, thank you, that's what I was looking for. I edited the question, just in case you want to edit the answer correspondingly at all.


Find limit of a sequence $Y_n$ when $Y_n = X_{2n}$ and limit $X_n=l$

Question: I'm stumped by the following question. Can anyone help me out. Clearly the answer is l but I can't work out how to prove this
Suppose that $\{x_n\}$ is a sequence converging to a limit $l$. Define a new sequence $\{y_n\}$ by setting $y_n := x_{2n}$ for all $n \geq 1$. Determine the limit of $y_n$, giving a rigorous proof.
Thanks
Comment: This is a special case of the fact that [any subsequence of a convergent sequence converges to the same point](https://math.stackexchange.com/questions/213285/prove-if-a-sequence-converges-then-every-subsequence-converges-to-the-same-lim).
Answer: $\{y_n\}$ is converging to $l$ if for every $ \varepsilon > 0$ there exists $N \in \mathbb{N}$ such that $|y_n-l| < \varepsilon$ for all $n \geq N$.
Now let $\varepsilon >0$, then there exists $M \in \mathbb{N}$ such that $|x_{2n}-l| <\varepsilon$ for all $n \geq \frac{M}{2}$ (since $\{x_n\}$ is converging to $l$). So we can choose $N:=\lfloor\frac{M}{2}\rfloor$ and we get $|x_{2n}-l|=|y_n-l| < \varepsilon$ for all $n \geq N$. Hence $\lim_{n \to \infty} y_n=l$.


Probability of an obtuse triangle in a circle.

Question:
Suppose we randomly pick 2 points A, B within a circle centered
at point O. What is the probability that the triangle formed by ABO is
an obtuse one? (Note that A and B are not exclusively on the
circumference).

And what is the conclusion extended to A, B within a ball instead?
Thanks!
PS this is from a Quant interview.
The following is what I have derived during the exam: (Edited, thank you for your corrections!)
consider the joint probability of x, y coordinate for any point in a unit circle, then $f_{XY}(x, y) = \frac{1}{\pi}$, uniformly distributed inside the circular region. The distance between the point and the center, has thus a distribution $f_Z(z) = 2z$ for $z$ in [0, 1] ($z^2 = x^2 + y^2$).
Randomly pick an A, rotate the circle so that A is right on top of the center O. Suppose now A has a distance $z = a$ $(a > 0)$ away from the origin, then B could only be chosen in the region of

$y > a$
$y < 0$
within an inner circle whose diameter is $OA$

Therefore, given that the distance is $z = a$, the probability of ABO being an obtuse triangle is given corresponds to area $\arccos(a) - a\sqrt{1-a^2} +  \frac{a^2\pi}{4} + \frac{\pi}{2}$ (Upper, inner, and lower). By this conditional probability, we could derive the total probability, which is
$$
\int_0^1 \frac{1}{\pi}\left(\arccos(a) - a\sqrt{1-a^2} +  \frac{a^2\pi}{4} + \frac{\pi}{2}\right) \cdot 2a \; da = \frac{3}{4}
$$
But is there an easier way to solve this? This looks like a math competition style of question and I expect some tricks to be at play. Thanks!
Comment: If the obtuse angle was at point O, the possibility depends on the distance between point $A$ and point $B$, to the radius $r$ of the circle
Answer: The probability that point $A$ is at a distance from the center in $[a,a+da]$ is $2\pi a\,da/\pi=2a\,da$.
The probability that, fixed $A$ as above, $\angle ABO>90°$, is the same as the probability that $B$ lies inside a circle of diameter $OA$, that is $\pi(a/2)^2/\pi=a^2/4$.
Hence the overall probability that $\angle ABO>90°$ is:
$$
p(\angle ABO>90°)=\int_0^1 {a^2\over4}\cdot 2a\,da={1\over8}.
$$
The probability that triangle $ABO$ is obtuse is then:
$$
p(\angle ABO>90°)+p(\angle BAO>90°)+p(\angle AOB>90°)
={1\over8}+{1\over8}+{1\over2}={3\over4}.
$$
EDIT.
For a 3D sphere one can repeat the same argument, obtaining:
$$
p(\angle ABO>90°)=\int_0^1 {a^3\over8}\cdot 3a^2\,da={1\over16}.
$$
Comment: Yes, if $z$ is the radial distance, then its probability density is $2z$.
Comment: Thank you! You made me realize that we should not use the marginal w.r.t. $y$ coordinates (feasible but convoluted) but the distance from a given point to the center. And I believe that is $f_Z(z) = 2z$ for $z$ in [0, 1]? This is what you are suggesting right?
Answer: Did you forget about the possibility of $\angle ABO > 90^\circ$? If you know some geometry, this happens when point B is located inside the circle with diameter $AO$, which easily has the area of $\frac{\pi a^2}{4}$. Now, we can easily calculate the value of $P(\angle ABO > 90^\circ)$. Now by symmetry, the value is the same for $P(\angle BAO > 90^\circ)$. The value of $P(\angle ABO > 90^\circ)$ is trivially $0.5$ as you said, and all those probabilities are exclusive and add up to the answer you need.
This answer extends naturally to the 3D case.
Comment: Well I think it's fine. First you set out to calculate the probability $P(\angle ABO > 90^\circ)$ in the general condition, then you may argue to fix the position of $A$. Similarly, you may do identical thing for $B$, but now you fix the position of $B$. Of course fixing $A$ when calculating $P(\angle BAO > 90^\circ)$ will meet the integral you posted in the question.
Comment: Thank you! I miss that situation when $P(\angle ABO > 90^\circ)$. But it looks like two quantities are not symmetric if we were to measure by $a$? One corresponds to the area of the little inner circle whose diameter is $AO$ and the other corresponds to the region inside the unit circle above $y > a$.
Answer: I first compute the probability $p$ that the triangle $\triangle:=OAB$ is acute.
When$|OA|=r$ we may assume $A=(r,0)$. The point $B=(u,v)$ then has to satisfy $0<u<r$, and $B$ must not lie in the small disc with diameter $OA$. The feasible area for $B$ therefore is
$$b(r):=2\int_0^r\sqrt{1-x^2}\>dx-{\pi r^2\over4}\ .$$
Since $|OA|$ is distributed with density $2r$ with respect to $dr$ we therefore obtain
$$p=\int_0^1 {b(r)\over\pi}\>2r\>dr=\ldots={1\over4}\ .$$
It follows that $\triangle$ is obtuse with probability ${3\over4}$.
Comment: This is in agreement with my result: I edited my answer to show that.
Answer: Using $$f(a)=\left(2\pi \arccos(a) - a\sqrt{1-a^2} + \frac{1}{2}\right) \, \frac{4}{\pi}\sqrt{1 - a^2}$$
$$I=\int_0^1 f(a)\, da=\frac{5}{2}-\frac{1}{\pi }+\frac{\pi ^2}{2}$$ is not too difficult provided that we have some time.
For an approximation, write for example
$$I_n=\int_0^{\frac 12} f(a)\, da+\int^1_{\frac 12} f(a)\, da$$ and use Taylor series of $f(a)$ around $a=0$ to $O(a^{n+1})$ and $a=1$ to $O((1-a)^{n+1})$.
$$I_0=\frac{1}{\pi }+2 \pi\qquad \qquad\text{relative error = 7.23 %}$$
$$I_1=1-\frac{7}{6 \pi }+2 \pi\qquad \qquad\text{relative error = 2.88 %}$$
Answer: Wherever A and B are, one of them is going to be at least as far away from O as the other. Which point has this property is even odds and independent of the obtusity of the triangle, so assume WLOG that A is at least as far away as B.
Once you've "rotated" the point A to be directly above O, you know B is somewhere in (or on) the concentric circle passing through A, with a uniform distribution.
You know where A is relative to this configuration, but you aren't sure about where B is. Regardless, scale the configuration so that this new A-circle has a radius of $\frac{1}{\sqrt{\pi}}$ (and thereby an area of $1$). This will preserve the obtusity of ABO and avoids the need to integrate wrt the radius $a$.
Since the interior angle sum of ABO is $180^\circ$, we know there's at most one obtuse angle ($\ge 90^\circ$) in the triangle.
As Bimo points out:

Our first case, $\angle BOA\geq 90^\circ$, corresponds to B in the
lower half of the A-circle.
Our second case, $\angle ABO\geq
   90^\circ$, means B is in a smaller circle, half as tall as the
A-circle and fitting neatly in its upper half (by Thales' theorem).
The third case one might consider, $\angle OAB\geq 90^\circ$, is
impossible, since this would imply that B were above A (not directly
above).
If none of these are true, B must be elsewhere in the circle.

Adding the (almost) disjoint first and second cases gives a probability of $\frac{1}{2}+\frac{1}{4}$ quite simply.
Integration is certainly an appropriate tool here but, as your instincts suggest, should not be used where easier, less mistake-prone solutions can be found.


Regex "does not contain"

Question: I am building some basic log parsing and cannot figure out a way to get this regex right. I want each regex to match only one of the logs below. The first one listed is the one not working, and the others are provided as examples to what is working.
I have provided a sample log, the regex used, and what it is returning. Any help would be greatly appreciated
In these examples:
The first regex to match if the log does not contain a "\" or an "@" before or after the login.
The second regex will match logs with a "\"before the login
The third regex will match logs with an "@" after the login
Log:
04:52:59,1,"bob"theRestOfTheLog

Regex:
[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2},[0-9]{1,3},"(^(?!.*?\\|.*?@)<login>[^"])

No match, Want it to return:
login=bob

Log:
04:52:59,1,"abc\bob"theRestOfTheLog

Regex:
[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2},[0-9]{1,3},"(?<domain>[^\\]+)\\(?<login>[^"]+)

Returns:
domain=abc login=bob

Log:
04:52:59,1,"firstname.lastname@example.com"theRestOfTheLog

Regex:
[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2},[0-9]{1,3},"(?<login>[^@]+)@(?<domain>[^"]+)

Returns:
login=bob domain=xyz.org

Answer: I think for the first regex you could use exclude matching the \ and @ for the login to get that as the only match and not matching the other ones.
[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2},[0-9]{1,3},"(?<login>[^"\\@]+)"

Regex demo
Note that when using a negated character class [^"\\@] it will also match newlines. If you don't want to match those, you could extend it to [^"\\@\r\n]
If you don't want to allow newlines or whitespaces use \s instead of \r\n
Comment: Thank you, that was the solution

Regex "does not contain"


Countably generated sigma-algebras

Question: This question asks whether every family $\mathcal A\subseteq\mathcal P(X)$ is contained in a countably generated
$\sigma$-algebra. (The OP stipulates that $\mathcal A$ is itself a $\sigma$-algebra, but that clearly doesn't matter.) The answers provide counterexamples with either $|\mathcal A|\gt2^{\aleph_0}$ or $|X|=2^{2^{\aleph_0}}.$ I would like to see a counterexample with $|\mathcal A|\le2^{\aleph_0}$ and $|X|\le2^{\aleph_0}.$

Question. Is there a family $\mathcal A\subset\mathcal P(\mathbb R)$ such that $|\mathcal A|\le2^{\aleph_0}$ and $\mathcal A$ is not contained in any countably generated $\sigma$-algebra?
Comment: The tag [descriptive-set-theory] is relevant here. Agree?
Comment: For what it's worth, the free concrete $\sigma$-algebra on $2^{\aleph_0}$ generators (in fact, even the free concrete $\sigma$-algebra on $2^{2^{\aleph_0}}$ generators) embeds in $\mathcal{P}(\mathbb{R})$, by an argument similar to the argument that the free Boolean algebra on $2^{\kappa}$ generators embeds in $\mathcal{P}(\kappa)$.  It seems plausible such an algebra could not be contained in a countably generated $\sigma$-algebra, though I can't see a way to prove it...
Answer: Claim: Under CH, there is no such family.
Proof: Recall that $\mathcal{P}(\omega_1) \otimes \mathcal{P}(\omega_1) = \mathcal{P}(\omega_1 \times \omega_1)$ (a result of B. V. Rao, On discrete Borel spaces and projective sets, Bull Amer. Math. Soc. 75 (1969), 614–617). Given $\{A_i : i < \omega_1\} \in [\omega_1]^{\omega_1}$, choose $\{(X_n, Y_n): n < \omega\}$, $X_n, Y_n \subseteq \omega_1$, such that the sigma algebra generated by $\{X_n \times Y_n : n < \omega \}$ contains $\{(i, x): i < \omega_1, x \in A_i\}$. It follows that the sigma algebra generated by $\{Y_n : n < \omega\}$ contains each $A_i$.
In the other direction, Arnold W. Miller, Generic Souslin sets, Pacific J. Math. 97 (1981), 171–181 showed that it is consistent that there is no countable family $\cal{F} \subseteq \mathcal{P}(\mathbb{R})$ such that the sigma algebra generated by $\mathcal{F}$ contains all analytic sets. So the existence of such a family is independent of ZFC.
Comment: Yes, that's the argument. An interesting followup question is if a negative answer to your question is equivalent to "every subset of plane belongs to the sigma algebra (call it $\Sigma$) generated by abstract rectangles". A natural try would be to take $A \subseteq \mathbb{R}^2$, $A \notin \Sigma$ and show that the sigma algebra generated by $\{A_x : x \in \mathbb{R}\}$ is not countably generated. But I don't see how to do it.
Comment: An equivalent formulation of this would be: Suppose for every $\cal{A} \in [\mathcal{P}(\mathbb{R})]^{\mathfrak{c}}$, there is a countable family $\cal{F}$ such that the sigma algebra generated by $\cal{F}$ contains every member of  $\cal{A}$. Must there exist, for every such $\mathcal{A}$, a countable family $\cal{E}$ such that for some $\alpha < \omega_1$, every member of $\cal{A}$ is $\Sigma^0_{\alpha}(\cal{E})$ (i.e., their Borel ranks are bounded below $\omega_1$)?
Comment: Yes. The reference is B.V.Rao, On discrete Borel spaces and projective sets, Bulletin of the AMS, 75 (1969), 614-617
Comment: Thanks. I had thought of the analytic sets but guessed wrongly that they would be a real rather than a consistent counterexample. Rao's result seemed amazingly counterintuitive at first, but I must have seen it before in the dim past, because I managed to reconstruct the proof. The key ideas seem to be that (1) in $\omega_1\times\omega_1$ every "curve" $y=f(x)$ or $x=f(y)$ is a "Boolean $\sigma$-combination" of "rectangles" $X\times Y$ and (2) $\omega_1\times\omega_1$ is the union of countably many "curves". Right?
Comment: A related [question](https://mathoverflow.net/questions/258842/a-question-about-sigma-algebras-and-rectangles) at MathOverflow.

Countably generated sigma-algebras


Allowing only HTTPS POST requests using .htaccess

Question: I'm trying to block all HTTP POST requests in my root folder but allow HTTPS POST. I'm dealing with a huge volume of POST requests which are decimating my server bandwidth, but they are all HTTP.  When actual customers come to the website POST actions are required (login, etc) but they are all done on HTTPS pages. Can I weed out the offending requests and allow only HTTPS POST actions? Using the following I'm able to block:
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REMOTE_ADDR} !127.0.0.1
RewriteRule ^ / [F]

Then tried this to allow HTTPS:
#if https on
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_METHOD} POST
RewriteRule ^ / [L]

#else
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REMOTE_ADDR} !127.0.0.1
RewriteRule ^ / [F]

Which returns a 500 internal server error. Note that legit POST requests do originate in the root so I can't just add a special .htaccess in a subfolder which allows POST.
Answer: You can block all HTTP POST requests like this:
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_METHOD} POST
# allow localhost
RewriteCond %{REMOTE_ADDR} !127\.0\.0\.1$
RewriteRule ^ - [F]


If two random variables are equal, prove or disprove that they are independent.

Question: Say $X$ and $Y$ are random variables such that $P(X=Y)=1.$ I think they are independent.
Here is how I'm thinking about it. Let $k$ be a point where $X$ and $Y$ would occur. $$P(X=k, Y=k)=P(X=Y)=1=P(X=k)*P(Y=k).$$ Is there something wrong with my proof? Thanks!
Comment: This goes totally against intuition and it can be easily disproved technically.
Comment: I believe the only way where $X$ is independent of itself is when $X$ is almost surely a constant. Indeed, you have for any Borel set $P(X \in B) = P(X \in B)^2$ so $P(X \in B)$ is either zero or one. Now consider $B = B(b) = (-\infty, b]$ for some real $b.$ Let $c$ be the infimum of the $b$ such that $P(X \in B) = 1$ (such set of $b$ is clearly not empty since $X$ is finite with probabiltiy one), it follows easily that $P(X = c) = 1.$
Answer: Counterexample: Take $Y = X$. $X$ is certainly not independent of $X$! (Explanation below)
Flaw in proof: To show $X,Y$ are independent, you need to show that for any $x,y$, $P(X=x,Y=y) = P(X=x)P(Y=y)$.
It is not enough to consider only a point $k$ where $P(X=k) = 1$.
Under your assumption that $P(X=Y) = 1$, we have
$P(X=x,Y=y) = 0$ if $x \neq y$. But $P(X=x)$ and $P(Y = y)$ need not be zero.
Comment: @Paul726 When $X=Y$ then the event of $\{X=x\}$ is the event of $\{X=x,Y=x\}$ then $$\mathsf P(X=x, Y=x)=\mathsf P(X=x)$$.So if $0<\mathsf P(X=x)<1$ clearly $$\mathsf P(X=x,Y=x)\neq \mathsf P(X=x)~\mathsf P(Y=y)$$
Comment: I see. So they are actually not independent because X and Y can always take on the same value? I'm just a little confused because intuitively taking the same values does not convey anything about independence.
Comment: So I guess the correct wording is "X and Y could be independent"?
Answer: The easiest way to think of random variables $X$ and $Y$ being independent is "Does knowing the value of $X$ tell me anything about the value of $Y$?"
If knowing something about $X$ also gives you knowledge about $Y$, or vice versa, then they are not independent since they depend on each other somehow.
So if $P(X = Y) = 1$, then knowing the value of $X$ gives you almost perfect information about the value of $Y$, and hence they are not independent (except for some degenerate cases).
Comment: While I learnt this way of understanding stochastic independence, I grew up and discarded it later. _It is not_ the knowledge of $X$ to infer knowledge of $Y$ but rather that knowing values of $X$ affect the _probabilities_ of $Y.$ This is specially critical in multivariate analyses where many mistakes are done based on this _flawed_ intuition. In multivariate analysis is not uncommon to find $X = g(Z)$ and $Y = h(Z)$ for some random object $Z$ and yet $X$ and $Y$ are independent (for instance, $Z = (Z_1, Z_2)$ is a bivariate standard normal and $X = Z_1-Z_2,$ $Y = Z_1+Z_2$)....
Comment: (continuing the example, if you know $X = 0,$ then you know $Y$ is supported on the diagonal, yet $X$ and $Y$ are independent, meaning that despite you know something of $Y$ you cannot infer anything about its stochastic properties.)
Comment: That's fair, I hope it's ok for a lay explanation though.


Loop for in em getElementsByClassName

Question: Por que quando uso for in para aplicar uma regra a todos os elementos de uma classe html através do javascript até funciona mas sempre aparece este erro no console?
TypeError: document.getElementsByClassName(...)[i].style is undefined

var e = document.getElementsByClassName("minha-classe");

for (var i in e) {
  e[i].style.display = "none";
}

...

...

...

...

...

Answer: O retorno de getElementsByClassName é um objeto do tipo HTMLCollection, não apenas um objeto NodeList. Este objeto possui um atributo de somente leitura chamado length e métodos chamados item e namedItem que são incluídos nas iterações quando utilizado o for. Para verificar, basta exibir o valor de i:

var e = document.getElementsByClassName("minha-classe");

for (let i in e) {
  console.log(i);
}

...

...

...

...

...

O erro é gerado quando o valor length é atribuído à variável i, pois o código tenta definir o estilo de um elemento e[length], mas este não é um elemento HTML. Para contornar o problema, basta alterar a estrutura de repetição:

var e = document.getElementsByClassName("minha-classe");

for (let i = 0; i < e.length; i++) {
  e[i].style.display = "none";
}

...

...

...

...

...

Assim você garante que os valores de i serão sempre válidos e percorrerá todos os elementos da lista.

Utilizando o for ... of
Utilizando ES6 é possível utilizar o for ... of ao invés de for ... in. Veja o exemplo abaixo:

var e = document.getElementsByClassName("minha-classe");

for (let i of e) {
  i.style.display = "none";
}

...

...

...

...

...

Comment: Obrigado pela resposta, ajudou bastante. Fazia um tempo que eu tava tentando entender porque isso acontecia.

Loop for in em getElementsByClassName


Apache-Served CA vs Local Root CA - Which Wins?

Question: I currently have two Apache servers running here and here, both use SSL certs signed by StartSSL. Apache SSL configuration below:
  ## SSL directives
  SSLEngine on
  SSLCertificateFile      "/etc/certificates/thor.vikingserv.net/certificate.crt"
  SSLCertificateKeyFile   "/etc/certificates/thor.vikingserv.net/private.key"
  SSLCertificateChainFile "/etc/certificates/intermediate/startssl-class-1.crt"

Both the server certificate and the intermediate certificate are SHA-256, but the CA cert is SHA-256 on my Linux workstation, but SHA-1 on my MacBook.
I could use the SSLCACertificatePath directive within Apache to force the SHA-256 CA cert, but would this override the root certificate distributed with the OS?
Answer: No, it wouldn't, because if clients would trust a random root certificate presented to them, the whole point of a trust store would be somewhat moot.
Two notes about your question:

The algorithm used to sign a trust anchor certificate is irrelevant -- the signature itself isn't used during validation.
SSLCACertificatePath wouldn't help you anyway, as that directive is only used when validating client certificates, which is not what you're doing.


fractional Sobolev spaces for periodic functions

Question: Let us denote by $L^2([0,2\pi])$ the space of all periodic functions that are square integrable. Usually one defines the $H^s$-space for $s>0$ by
\begin{align} H^s([0,2\pi]) = \left\{ u \in L^2([0,2\pi]) \, \bigg| \, \int_{(0,2\pi)} \int_{(0,2\pi)} \frac{(u(x)-u(y))^2}{|x-y|^{1+2s}}dx\, dy<\infty\right\}. \end{align}
I've come across several references where also the definition
\begin{align} \left\{ u \in L^2([0,2\pi]) \, \bigg| \, \sum_{m\in \mathbb{Z}}(1+m^2)^s |\hat{u}(m)|^2<\infty   \right\} \end{align} is used. Here, $\hat{u}$ is the Fourier transform of $u$.
Now I'm wondering why both definitions give the same space. I know the equivalent definition via the Fourier transform in the case $H^s(\mathbb{R})$. But somehow, the known techniques do not work if I want to show that both norms are equivalent in the case of periodic functions. Is there an easy trick?
Maybe someone also knows some nice references where fractional Sobolev spaces for periodic functions are treated. I only found references for the case when $s$ is an integer.
Comment: In my opinion you should work with mollifiers (https://en.wikipedia.org/wiki/Mollifier): (1) Assume that $u$ satisfies one of the two conditions, then (2) show that also the mollified $u_\epsilon = u*\varphi_\epsilon$ does; (3) Use the characterization on $\mathbb R$ and then (4) let $\epsilon\to 0$ to see that the other condition is satisfied for $u$. For this note that $\hat\varphi(0) = \int\varphi = 1$.
Comment: I think your implicit surmise is correct, that it takes some work to show that equivalence from scratch. As @amsmath suggests, one way to _not_ start from scratch is to reduce to the case of the whole line, as black box. But, also, you could just think of how to repeat the argument for the line on the circle, since both are (abelian) Lie groups, and are _locally_ identical.
Answer: If a function is periodic, then we can use Fourier Series instead of the Fourier Transform to represent it. Then the above result is intuitively similar to Parseval's Theorem.
Comment: I don't see how this helps. I mean, it is clear that $\hat u(m)$ is the $m$-th Fourier coefficient here. Please specify "intuitively similar".
Comment: It isn't "clear" that it is the Fourier coefficient since FT and FS are two different things. Using the alternative definition $H^s = \{u| \int (1+|\xi|^2)^{s}|\hat{u}(\xi)|^2d\xi < \infty \}$, and that the FT of a periodic function will be deltas, it almost looks like the integral becomes a summation, but not really since $\delta^2$ is not a distribution. By intuitively similar I meant that the integral becomes a summation.
Comment: For me, the function wasn't periodic but just defined on $[0,2\pi]$ from the scratch. So for me it was clear that $\hat u(m)$ meant the $m$-th Fourier coefficient. However, I see your point now. But I still don't see how it's supposed to help OP. Maybe it's better to mollify $u|_{[0,2\pi]}$ and use the known characterization on $\mathbb R$.


"one more" ajax call for multiple node add forms on one page

Question: I want a page with an initial node add form (in small size), the title line and body textarea 3x20 size;
And a button "one more" with ajax call to display another form plus another button etc etc.
and of course the submit button always at the bottom.
So the question is ... which module ? :) I hardly cant find the terms for searching!
UPDATE: I want to add , this task seemed to me quite often used and modular, so I thought there would be a module for it; Now as i work through related questions and learn about ajax form api http://randyfay.com/ajax it's okay to code it for me and maybe you can give some starting points.
Answer: I worked on similar case. I wanted to add few nodes at one time without reloading page.
Instead I did multi value field in my content type (mysomething), but I needed to have more elements than one field. So I found field collection module, made collection and put it as multi value field of type collection. Now when I do node/add/mysomething I have collection and [Add more] button below.
Creating collection allows You to add all core field types, so in your case I would add text field working as title and body field to collection.
The other thing is, that if someone add 3 collection at once it will be consider as one mysomething node by D7 core - You should make some views to see whats inside. Another approach is to catch node creation action of type mysomething and try to split it into nodes by rules, but I didn't do that so I'm not sure if it is possible. And finally someone probably can write custom module with ajax form, where submit button will save node for each element...
I think it's nice trick with no coding (UI visual puzzle). I can write step by step config for You, if needed, but it's pretty easy.
Answer: The default Fields API gives you the opportunity to use fields with unlimited number of values, with widgets that already embed the functionality you're talking about, mean an 'Add more' button.
Is there any reason you don't want to use it ?
Comment: if I understand right, the addmore button should be defined as a field?
Comment: No, as a form element. If it doesn't store data, it's not a field right ?
Comment: And store all data in the same node?  Not sure if I want that. I need to try to use views on that.


SWT make impossible to close the org.eclipse.swt.widgets.Dialog window

Question: Tell me, how to make it impossible to close the window which extends "org.eclipse.swt.widgets.Dialog" by Esc key?
my code is here:
Answer: Add a listener to shlTimeDiagramsWindow on SWT.Traverse. If the event is escape key, we set the event for that to false. You can add the below snippet code to method open(int coordX, int coordY).
shlTimeDiagramsWindow.addListener(SWT.Traverse, new Listener() {

    @Override
    public void handleEvent(Event event) {
        if (event.character == SWT.ESC)
        {
            System.out.println("escape key");
            event.doit = false;
        }

    }
});

Comment: Thanks a lot, it works fine! I`ve forget about event.doit option


Eclipse + Subclipse: SVN can't open local repository

Question: I have created initial import of my eclipse project to local file like this:
$svn import /home/miso/workspace/DatabaseManager/ file:///home/miso/svn/dbman -m 'Initial import'

Now I'd like to add this SVN repository to my Eclipse project (inside Eclipse itself). When I try to add new repository via SVN Reposistory Perspective (it came probably with Subclipse plugin) and navigate to file:///home/miso/svn/dbman then I get only this result:

What did I wrong? Thanks
Comment: What version of Subclipse are you using, and also which version of Subversion?
Comment: SVN: 1.6.12. Subclipse: 1.0.7. I am using also some cvsdude servers where my old subclipse plugin works well with other projects.
Comment: Shouldn't that me a `checkout` instead of an `import`?
Answer: This error happens when you use a version of Subclipse that is not compatible with the version of Subversion that created the repository.
This link should shed more light on it, basically just make sure your version of Subclipse can interface with whatever version of SVN you created the repository with.
EDIT I just did a quick read on Subclipse, my understanding is that any 1.x version of Subclipse should work with any 1.x version of Subversion. However, for 1.6 versions of Subversion you will need the 1.6 version of Subclipse.
Source: http://subclipse.tigris.org/servlets/ProjectProcess;jsessionid=AE2D434B8F5AC0C0D416B27808DD90BD?pageID=p4wYuA
Comment: Hmm I have different projects versioned on different servers (different SVN). I guess this means, I'd better use terminal :|
Comment: What are the different versions of SVN you are interacting with? If you give us this, maybe there is another tool out there that can interface with a wider range of Subversion versions?
Comment: 1.6 locally and 1.4 @ remote server (I guess, I am not 100% sure what runs on server).
Comment: I did a quick search which turned up squat, however, I'm thinking this might not be a bad type of tool for myself to develop. Doesn't seem like it would be too hard, anyways.
Comment: Read my edit, it seems like you need to upgrade your version of Subclipse to 1.6 to work with 1.6 repositories.
Comment: That's the problem. Newer subclipse doesn't work with that :/ I'll guess I wait for Eclipse Indigo now and will retry then. Thanks for now.
Comment: ...? We are running Subversion 1.6 in house and Subclipse works with my Repository. What version of Eclipse are you using?
Comment: I can confirm that the latest version of Subclipse works with Helios, I use it on the daily. If you're having issues with it, I can try to give you a hand in my spare time if you'd like.
Comment: Thank you very much, I'll wait. I am using 2 eclipses now and I'll be dealing with this issue when I will be forking my work to Indigo release.