Trying to prove Cantor-Bernstein-Schröder following these steps

Question: I know a proof for this theorem is a recurrent issue but I've checked wikipedia's proof and several posts in this forum about it and even if I found some similarities I couldn' solve my problem.
Let $X$ be a set with an injection $h:X \to X$ and $Y$ a subset such that $h(X) \subset Y \subset X$. The goal is to prove there's a bijection between $Y$ and $X$ following these steps:
$(1)$ Prove there exists a minimal subset $Z \subset X$ such that $(X-Y)\subset Z$ and $h(Z)\subset Z$
$(2)$ Prove that $h(Z)=Z\cap Y$
$(3)$ Using the injective function $h$ and the subset $Z\subset X$ defined in $(1)$ construct a bijective function $h':X\to Y$
$(4)$ Prove, using the steps above, that if $A$ and $B$ are sets such that there exist two injections $f:A\to B$ and $g:B\to A$, then there is a bijection between those sets.
.
This is what I've done:
$(1)$ Let $I=\lbrace V\subset X | (X-Y) \subset V \land h(V) \subset V \rbrace$ and define  $Z=\bigcap_{V\in I} V$ It can be proven that $Z$ satisfies all the conditions required (I omit the details but if someone asks me to I will write them) and in addition $Z$ is not empty.
$(2)$ Here is where I'm stuck. It is clear that $h(Z)\subset Z$ by definition and because of $h(X)\subset Y$ then $h(Z)\subset Y$,so one of the inclusion is obvious but I can't prove the other one. I've tryed assuming there is some $x\in Z\cap Y$ which is not in $h(Z)$ but I didn't find any contradiction under this assumption (which is what I'm needing) Perhaps reductio ad absurdum is not the right way to get it, any advise on this point would be greatly appreciated.
$(3)$ Let $h':X\to Y$ be defined as follows: $$h'(x)=h(x) \ \mbox{if $x \in Z$} \\ h'(x)=x \ \mbox{if $x \not\in Z$}$$ Again I omit the details but it can be proven that $h'$ is a bijection.
$(4)$ Finally, here i tryed to "emulate" what I've done in the steps before. So, if $f:A\to B$ and $g:B\to A$ are injections and I let $I= \lbrace V \subset A| (A-g(B)) \subset V \land f(V) \subset g^{-1}(V) \rbrace$, then I define $Z=\bigcap_{V\in I}V$ but I'm not sure if what I'm doing is useful, it seems to me that I should prove that $Z\in I$ and $f(Z)=g^{-1}(Z)$ and then define some function $t:A\to B$ (hopefully bijective). I tryed defining it this way: $$t(x)=f(x) \ \mbox{if $x \in Z$} \\ t(x)=g^{-1}(x) \ \mbox{if $x \not\in Z$}$$ But I don't feel completly confident with it, I think something is not working with this function I've defined.
.
Any guiding idea, advice or attempts to solve would be very helpful. Thanks
Comment: There are other proofs of this theorem. One in particular (attributed to Julius Konig) that is short and simple. See Schroder- Bernstein Theorem in Wikipedia
Answer: Ad (2). Let $W=(X-Y)\cup h(Z)\subset Z.$ Since $h(W)\subset h(Z)\subset W$ and $X-Y\subset W,$ we have $W\in I,$ whence $W=Z$ and $Z\cap Y=W\cap Y=h(Z).$
Ad (4). Let $X=A,$ $Y=g(B),$ and $h=gf,$ so that $Y\subset X$ and $h:X\to Y$ is an injection. By the previous result there is a bijection from $X$ to $Y,$ i.e., a bijection from $A$ to $g(B);$ compose this with $g^{-1}$ to get a bijection from $A$ to $B.$
Comment: Hi @bof, your approach to prove $h(Z)=Z\cap Y$ is elegant, but I fell that is is not quite intuitive. It is easy to prove $h(Z) \subset (Z\cap Y)$. Is there any intuitive way to prove $h(Z) \supset (Z\cap Y)$?
Comment: @DungLe I'm not sure I agree that the argument I gave is unintuitive, but perhaps you will prefer the following. Note that $$Z=Z_0\cup Z_1\cup Z_2\cup\cdots$$ where $Z_0=X-Y$ and $Z_{n+1}=h(Z_n).$ Then $$h(Z)=Z_1\cup Z_2\cup Z_3\cup\cdots=Z-Z_0=Z-(X-Y)=Z\cap Y.$$
Comment: Hi @bof, I possibly find a way to prove $(Z\cap Y) \subset h(Z)$ as follows. Assume $(Z\cap Y) \not\subset h(Z) \implies \exists p\in (Z\cap Y)$ such that $p \notin h(Z) \implies p \in Y$. Let $W=Z-\{p\}$. First,$p \in Y \wedge X-Y\subset Z \implies X-Y \subset Z-\{p\} \implies X-Y \subset W$. Second, $h(W)=h(Z-\{p\})=h(Z)-h(\{p\})\subset h(Z) \subset h(Z)-\{p\}$ [Since $p \notin h(Z)$] $\subset Z-\{p\}$ [Since $h(Z) \subset Z$]$=W$. So, we have $X-Y \subset W$ and $h(W)\subset W$, then $W \in I$, but $W \subsetneq Z$. This contradicts to the minimality of $Z$. Thus $ (Z \cap Y) \subset h(Z)$.
Comment: Please check my above reasoning @bof!
Comment: @DungLe I answer questions on this site for fun. Checking other people's work is no fun. It's too much like grading test papers.
Comment: Anyway thank you for your previous comment! It gave me new useful insights.


dynamic url for jquery tabpanel

Question: I am using struts2-jquery plugin for tabpanel. Check out below code

      <s:select list="appList" id="appList" name="selectedApp"
          headerKey="-1" onchange="getApplicationValue(this);"/>

      <s:url var="urlVar" value="actionValue">
        <s:param name="calledAction">actionName</s:param>
  </s:url>

      <sj:tabbedpanel id="remotetabs" selectedTab="0" cssStyle="width:100%">

      <sj:tab id="pendingTab" href="%{urlVal}" key="key" target="div1"
    loadingText="Loading..." indicator="indicator">
    <sj:div id="pendingDiv" indicator="indicator" >
    </sj:div>
  </sj:tab>

My requirement is

each tabs calling url, perform database operation and shows data in that tab
changing on value of combo box above tabpanel fires current selected tab with passing the value of current selected value in combobox
on change of combobox, data should appear in current selected tab

problem: req1 and req3 are working fine, but for req2 I am not able to pass the selected combobox value to my action class as current page is already loaded. changing the tab panel doesnt bind my class variable to action class. Please help me figuring out, how would I pass my combo box value to my action class (without loading the whole page/changing tab)
this is what it looks like: http://jsfiddle.net/rohanparekh/ZvtRM/3/
Comment: @cpoDesign: you can't put code with taglibs in jsfiddle...
Comment: this is what it looks like : http://jsfiddle.net/rohanparekh/ZvtRM/ i want to pass selected combo box value to my action class without calling action
Answer: The code is unbalanced.
sj:tabbedpanel is never closed by a closing tag.

dynamic url for jquery tabpanel


Why is identifier "v" undefined?

Question: I'm very new to programming and I'm learning C++. I'm trying to use vectors for this exercise but they are confusing me greatly. I think this code should work but I don't know why my IDE is saying that v is undefined.
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class check_input
{
public:
    void checkInput();
    void getnum();
    void displaynum();

private:
    vector<int> x;
    int sum = 0;
    int n = -1;

};

void check_input::checkInput()
{
    sum = 0;
    n = -1;

}

void check_input::getnum()
{
    int x;
    cout << "Please enter the number of values you want to sum, starting with the first: ";
    cin >> n;
    if (n < 1)
    {
        cout << "the number of elements must be a positive integer" << endl;
    }
    else
    {
        cout << "Please enter some integers (press '|' to stop): ";
        while (cin >> x) v.push_back(x);

        if (v.size() < n)
        {
            cout << "too few numbers; we need " << n << endl;
        }
        else
        {
            for (int i = 0; i < n; ++i) sum += v[i];
        }
    }
}

void check_input::displaynum()
{
    cout << "The sum of the first " << n << " numbers ( ";
    for (int i = 0; i < n; ++i) cout << v[i] << ' ';
    cout << ") is " << sum << '\n';
}

Comment: So where is `v` defined?
Comment: You should ask the programmer, why didn't they define `v`. We can't know why it's not defined.
Answer: Because you didnt defined that varible.
Please try to define that in the right scope, and you will not get the IDE's error. :)
Answer: You did not define the vector v, add vector<int> v; to your code

Why is identifier "v" undefined?


Erro de extenção MYSQL

Question: Montei uma pagina de códigos em meu site que busca informações do banco de dados mas no arquivo que conecta na DB e puxa as informações pertinentes esta dando um suposta erro de extensão. Este erro não aparece no localhost somente quando esta hospedado em um servidor online.O erro gerado é esse:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /CSS/function/conecta.coment.php on line 22

O codigo da pagina:
<?php

//base de dados de teste

$dbhost = 'mysql.hostinger.com.br'; // endereco do servidor de banco de dados

$dbuser = 'u28*******_fraex'; // login do banco de dados

$dbname = 'u28*******_fraex'; // nome do banco de dados a ser usado

$dbpass = '**********'; // senha

$conecta = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);

$seleciona = mysql_select_db($dbname);

// cria a instrução SQL que vai selecionar os dados

$query = sprintf("SELECT user_name, comentario FROM comentario ORDER BY coment_id desc limit 5");

// executa a query

$dados = mysql_query($query, $conecta) or die(mysql_error());

// transforma os dados em um array

$linha = mysql_fetch_assoc($dados);

// calcula quantos dados retornaram

$total = mysql_num_rows($dados);
?>

Como posso resolver isso?
Comment: Esse tipo de conexão não é mais usada e é desencorajada pois é muito insegura para SQL Inject, use PDO no lugar por ser mais seguro.
Comment: e como eu poderia mudar isso para PDO?
Answer: Esta mensagem não é um erro e sim um "aviso".
A função mysql será removida do PHP muito em breve e a mensagem esta sugerindo que você use mysqli_ ou PDO.
Você pode saber mais sobre o mysqli na documentação oficial do PHP, e também pode consultar como usar o PDO que é o mais recomendável.
Comment: ta mais eu precisaria mudar alguns termos ou teria que reestruturar os codigos?
Comment: Só alguns termos, você chegou a abrir o link que coloquei no post? nele tem um exemplo do `mysqli_connect` que você deveria usar no lugar de `mysql_connect` e assim por diante, veja a trecho que você usa com `mysql_` e procure o `mysqli_` que corresponda.

Erro de extenção MYSQL


Nginx duplicate default server error

Question: I have 2 files. The default:
/etc/nginx/sites-enabled/default

server {

        listen   80; ## listen for ipv4
        listen   [::]:80 default ipv6only=on; ## listen for ipv6 << LINE 10

I then have a custom file:
/etc/nginx/nginx.conf

http {
    server {
        server_name mydomain;
        listen 3000;
        root /projects/myproject/public;
    }
}

When I try to restart the service I receive this error:
the duplicate default server in /etc/nginx/sites-enabled/default:10
configuration file /etc/nginx/nginx.conf test failed

I have minimal experience with nginx and was hoping somebody could point out where I might have gone wrong?
Comment: `grep -lr default /etc/nginx`?
Answer: 8 months late, but anyway...
I had the same problem - it turned out that my editor left a default~ backup file behind after I had edited default.  Nginx read both the backup and the edited version and of course found a discrepancy between the two.  Simply deleting the backup allowed Nginx to start.
Answer: In my case I updated both GitLab and the Ubuntu server to 14.04. That apparently made nginx to get a new default config file. Just deleted it keeping the gitlab config made it happy again.

Nginx duplicate default server error


Exchange 2010 SP1 Certificate renewal, the new rule not allowing local intranet domains and will this change mail flow?

Question: I'm in a pickle with the infamous "The Security certificate has Expired or is not yet valid" message and I know it is due to our (multi domain name certificate; or I think that is called a SAN cert? right?) certificate having expired for our local server dns name:
servername.domainname.local
I see that GoDaddy has renewed our certificate automatically and it would normally seem like a cinch to go import it and hope the "The Security certificate has Expired or is not yet valid" message goes away for ALL internet Outlook clients, but the servername.domainname.local dns isn't on the auto-renewed certificate and instead our external dns name is on it: mail.domainname.md
From what I have been reading I now need to change servername.domainname.local to mail.domainname.md and this made me unfortunately realize I'd have to go and change all Outlook clients manually to point to the new external DNS... which also makes me think that this means that all INTERNAL Outlook clients that exist on the same network as the Exchange servers would then be going to the INTERNET to get their mail and come back in whereas I don't want that. I just want them going straight to the Exchange servers locally.
Does this new "no local domain cert registering" rule mean that mail flow is altered from internal to internal to internal to external to internal for traffic flow between the Outlook clients (2007) ?
If YES, does this mean that I have to go manually touch each Outlook 2007 client and change the server name to alleviate the "The Security certificate has Expired or is not yet valid" message?
Could I simply rerun certain certificate self-signing Powershell scripts I have found and generate a new local cert that will work to get rid of the popup message for the users to temporarily avoid registering a cert with an external DNS name?
If I'm right about needing to change the Exchange server name that all outlook clients refer to for their email, can I use this procedure to change it:
Exchange 2010: Outlook clients refusing to update to new CAS server
I really really hope somebody replies with "something" viable. I can't be the only person who's faced this and everything was just fine before the certificate renewal and the cert internal/external rule changed. I have about 60 demanding users and some just won't tolerate the popup at ALL.
Comment: I actual enjoy handling intolerant, demanding users and would be happy to deal with them for a bottle of scotch and 60 .308 rifle rounds... and travel costs, of course.  Regarding the technical aspect of your problem, how (or do) you have autodiscovery configured?  That's the easiest solution to getting your clients pointed at the right place automagically.
Answer: I think you're conflating the issue more than it deserves.  Assuming your cert already has the external name on the certificate and you've imported it and set the proper services for it it's actually fairly simple to tell Outlook clients to look for that cert.
There are three main things you'll want to change, just remember best practices and export these settings first so you can refer to them later if something goes wrong.
More or less you just want to set the InternalURL to be the same as the ExternalURL in the WebServicesVirtualDirectory, OabVirtualDirectory, and ActiveSyncVirtualDirectory.
Also if you haven't already in DNS make sure you have a SVC record for AutoDiscover that points to the external hostname (mainly what causes the warnings for internal clients).
Comment: OK. I have the cert working for the external domains. Thank God and it took me 4 days to learn all this stuff so I'd know what I was doing with the Certs.

ALL OF OUR INTERNAL DOMAIN OUTLOOK CLIENTS ARE POINTING TO THE LOCAL DNS SERVER NAME: EXCHANGE2.DOMAIN.LOCAL

... AND ALL OF THE INTERNAL OUTLOOK CLIENTS ARE GETTING THE SECURITY ALERT POPUP.

DO I NEED TO CHANGE THE EXCHANGE2.DOMAIN.LOCAL URL IN ALL OUTLOOK CLIENTS (WHICH IT DOESN'T LOOK LIKE IT WILL ALLOW) OR ARE YOU TELLING ME IN MY INTERNAL .LOCAL DNS TO POINT AUTODISCOVER TO EXTERNAL MAIL IP SO IT WILL FIX THIS?
Comment: It is best practice to have your internal dns resolve to the external hostname (ie in dns you should have a forward lookup zone for yourexternalname.com and it should have an entry something like mail.yourexternalname.com that resolves to your exchanges server's ip.)  And yes you should have a SVC record for _autodiscover that points to mail.yourexternalname.com.
Answer: As per CA/B forum new guideline for depreciation of local domain names in SSL certificates, no CA will issue SSL for local domain name. Also you can not acquire ssl for netBios names and IP address.
Till date idle set up for exchange server access to local network used .local domain name and for external use public domain names for outlookanywhere and owa. Accessing an exchange server on any network requires secure connection.
What action is required for exchange administrator?
Its required to remove .local domain configuration from exchange server. Before you remove it you should do the below.
Option1: Use public domain names to connect exchange on both networks like mail.exahngedomain.tld.
Option2: Add additional sub-domain on exchange server like local.exchangedomain.com, host on local network IP address. Then add/propagate DNS for this hostname on local network. This way you can keep exchange server local access limited to local network.
Do not escape the ssl certificate warnings in outlook connection, else your users will face issue whenever they start outlook.


Possible growth rates of a matrix entry with respect to exponentiation

Question: Let $A = \begin{pmatrix} 1 & 1 \\ 0 & 1\end{pmatrix}$, so $A^n = \begin{pmatrix}1 & n \\ 0 & 1\end{pmatrix}$. Thus, $(A^n)_{1,1} = 1 = \Theta(1)$, and $(A^n)_{1,2} = n = \Theta(n)$.
Given a constant $c$, if $B = \begin{pmatrix} c/2 & c/2 \\ c/2 & c/2\end{pmatrix}$ then $B^n = \begin{pmatrix} c^n/2 & c^n/2 \\ c^n/2 & c^n/2\end{pmatrix}$. Thus, $(B^n)_{1,1} = c^n/2 = \Theta(c^n)$.
We have observed three possible growth rates of a particular entry with respect to the exponent of a matrix, constant, linear, and exponential. What other growth rates are possible? For example, does there exist an $m\times m$ matrix $C$ and indices $i,j$ such that $(C^n)_{i,j} = \Theta(n^2)$?
Comment: Examples do not fit each other as $B$ depends linearly on a parameter $c$ so it is not surprising that $B^n$ behaves  proportionally to  $c^n.$
Comment: I wasn't claiming there's anything surprising there, just giving an example of exponential growth wrt n (with arbitrary base $c$)
Answer: Consider $A=I+S,$ where $S$ a matrix with entries $s_{i,i+1}=1$ and $0$ otherwise. If the dimension is equal $m,$ then $$A^n=I+ \sum_{k=1}^{m-1} {n\choose k}S^k$$ Thus $$(A^n)_{1,1+j}={n\choose j}\approx {n^j\over j!}\quad \qquad 1\le j\le m-1$$
Answer: Due to the Cayley-Hamilton theorem, matrix elements with respect to exponentiation adhere to the linear recurrence defined by the characteristic polynomial of a matrix. And a linear recurrence $A_0, A_1, \dots$ with the characteristic polynomial
$$
P(x) = \prod\limits_{i=1}^k (x-x_i)^{d_i},
$$
has a generic solution
$$
A_n = \sum\limits_{i=1}^k C_i(n) x_i^n,
$$
where $x_1 < x_2 < \dots < x_k$ are distinct roots of $P(x)$ and $C_i(x)$ are polynomials of degree at most $d_i-1$.
With such characteristic polynomial, the asymptotics of $A_n$ is estimated as $A_n \in O(n^{d_i-1} x_k^n)$.
So, all possible growth rates have a form of $\Theta(n^d c^n)$, the simplest possible example to such growth rate is the Jordan cell that has a size $d+1$ and a characteristic polynomial $(x-c)^{d+1}$.
$$
J_{c,{d+1}} = \begin{pmatrix}
c & 1       & 0      & \cdots  & 0 \\
0       & c & 1      & \cdots  & 0 \\
\vdots  & \vdots  & \vdots & \ddots  & \vdots \\
0       & 0       & 0      & c & 1      \\
0       & 0       & 0      & 0       & c
\end{pmatrix}.
$$
Another common example is the companion matrix of the polynomial $(x-c)^{d+1} = x^{d+1}+\sum\limits_{i=0}^{d} a_i x^i$:
$$
C((x-c)^{d+1})=\begin{pmatrix}
0 & 0 & \dots & 0 & -a_0 \\
1 & 0 & \dots & 0 & -a_1 \\
0 & 1 & \dots & 0 & -a_2 \\
\vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & \dots & 1 & -a_{d}
\end{pmatrix}.
$$


Creating variable names

Question: I'm having trouble with the following function:
private function whichLevelToLoad():void{
    if(levelToLoad == "nothing"){
        currentLevel = null;
    }

    var thisObj:Object = new Object();

    if(levelBtnArray!=null){
        for(var j:int=levelBtnArray.length-1;j>=0;j--) {
            if(levelToLoad == String("level " + (j+1))){
                thisObj["level"+(j+1)] = new ["Level"+(j+1)]();--------------------------->The Problem
                thisObj["level" + (j+1)].x = 0;
                thisObj["level" + (j+1)].y = 0;
                addChildAt(thisObj["level" + (j+1)], 0);
                currentLevel = thisObj["level" + (j+1)];
            }
        }
    }
}

I'm trying to instatiate 75 objects by using a loop. The line would look like this,"thisObj.level1 =  new Level1(); with the numbers going from 1-75. Is this possible? How
do I do it?
Answer: Try
if(levelBtnArray!=null){
    var levelClass:Class;

    for(var j:int=levelBtnArray.length-1;j>=0;j--) {
        if(levelToLoad == String("level " + (j+1))){

            levelClass = getDefinitionByName( "Level"+(j+1) ) as Class;
            thisObj["level"+(j+1)] = new levelClass();

            thisObj["level" + (j+1)].x = 0;
            thisObj["level" + (j+1)].y = 0;
            addChildAt(thisObj["level" + (j+1)], 0);
            currentLevel = thisObj["level" + (j+1)];
        }
    }
}

Creating variable names


Amend complex FILTER to search based on LIKE

Question: In cell E3 of the "Main_ST" sheet, I have this formula:
=QUERY(FILTER(Raw_FullSTBreakdown!A:Y, (C3<>"")*(Raw_FullSTBreakdown!O:O=C3) + (A3<>"")*(Raw_FullSTBreakdown!C:C=A3) + (B3<>"")*(Raw_FullSTBreakdown!G:G=B3)),"SELECT Col1,Col2,Col3,Col4,Col5,Col22,Col6,Col7,Col13,Col15,Col23")

This formula filters raw data from the "Raw_FullSTBreakdown" sheet based on the criteria in cells A3-C3 of the "Main_ST" sheet. The problem I am having however, is that I would like the filter in the formula to work in such a way that it does not filter based on an exact comparison but rather a LIKE logic/REGEXMATCH.
For example, "Raw_FullSTBreakdown!O:O=C3" should not be "=C3" but rather a pattern match. This is because column O in "Raw_FullSTBreakdown" can have a delimiter "_" separating different FBA IDs - in such a case, an exact match FILTER wouldn't work.
For example in, Row 56 (and column G) of the "Raw_FullSTBreakdown" sheet we have "B000VOHH8I_B00ARFFU1M". If I were to enter "B000VOHH8I" in B3 of the "Main_ST" sheet - this would not return this row 56 as "B000VOHH8I" does not match "B000VOHH8I_B00ARFFU1M".
Answer: Change the exact comparison
 Raw_FullSTBreakdown!G:G=B3

part of the formula to
regexmatch(Raw_FullSTBreakdown!G:G,B3)

Comment: Sheets regex(RE2) works with text(and not numbers); so for dealing with columns like EAN (which **ONLY** has numbers) go with `REGEXMATCH(to_text(Raw_FullSTBreakdown!C:C),to_text(A3))`
Comment: Sorry forgot to mention, I have tried this but I get the error:

`FILTER has mismatched range sizes. Expected row count: 33450, column count: 1. Actual row count: 1, column count: 1.`

You can see this now on the sheet. It was working before I made this change.
Comment: the formula you shared above in the post description has one final closing bracket but in the sheet there's two closing brackets?!
Comment: Good point - it should be a single bracket. I have now amended this on the sheet but it shows "no matches" - even though the equivalent exact match formula (without REGEXMATCH) does generate a result.


How Can I prove (a+b) mod m = (a mod m) + (b mod m)) mod m?

Question: modular arithmetic
How Can I prove (a+b) mod m = (a mod m) + (b mod m)) mod m ?
Comment: Before it can be proven, you have to have a definition for $\rm mod$.  What is your definition of it?
Comment: This question is a bit confusing. You seem to have too many (mod m)s. Are you trying to prove equality in Z of least positive representatives or equality in Z/mZ?
Answer: Let $a\mod m= a_1$ and $b\mod m = b_1$.
Then
$$\begin{cases}m\mid a-a_1\\m\mid b-b_1\end{cases}\implies m\mid a+b-(a_1+b_1)$$
$$\iff a+b\equiv a_1+b_1\pmod{m}\iff (a+b)\mod m=(a_1+b_1)\mod m\\\iff (a+b)\mod m =((a\mod m)+(b\mod m))\mod m\ \ \ \square$$
Comment: $m\mid a$ is the notation for "$m$ divides $a$", or "$a$ is divisible by $m$". Formally, $m\mid a\iff \exists k\in\mathbb Z(a=mk)$.
Comment: I am not clear about the notation m|a . please explain.
Comment: You need to be careful here. If you say $a mod m= a_1$ then a is an integer and $a_1$ is a set of integers. This causes some problems.
Comment: @SE318 No. See [this Wikipedia article](http://en.wikipedia.org/wiki/Modular_arithmetic#Remainders). $a\mod m$ is defined to be $r$ such that $a=lm+r$ for some integer $l$, where $r\in\mathbb Z, 0\le r<m$.
Comment: @user314, I see what you're saying. I've never seen it defined in this way in any of my math classes though as this lead to ambiguity as to if you're just finding the remainder, or passing into the quotient space. It's probably just a difference in definitions though, depending on which textbook you use, they can define these things with slight(but important!) differences.
Comment: @SE318 You might have in mind the modular equivalence relation and equivalence of integers there. $a\equiv b\pmod {m}$ just means that $m\mid a-b$, and $b$ can be any integer of the form $b=wm+a, w\in\mathbb Z$.
Comment: Yeah, I just looked at my undergraduate AA book (AA an introduction 2nd edition by Hungerford). In there, they define modular arithmetic solely in terms of arithmetic in Z/mZ. I can definitely see how using it to just define the remainder after the division algorithm could be used as well(especially in a more CS/application based math course rather than a purely abstract math course)
Comment: @user26486. Thank you very much. Can you show how to do it for $ ab \mod m = (a \mod m)(b \mod m) \mod m$
Comment: How we can we conclude that $$(a+b)\mod m=(a\mod m+b)\mod m?$$I try use your idea but I get stuck.
Answer: Using $\,\ c\equiv d\pmod m\color{#c00}\iff \bar c = \bar d,\ $
 where $\,\ \bar n := (n\bmod m)\ $
${\rm mod}\ m\!:\,\ a\color{#c00}\equiv \bar a$
$\qquad\qquad\, b\color{#c00}\equiv \bar b$
$\ \, \Rightarrow\,\ a+b\equiv \bar a + \bar b\,\ $ by the $ $ Congruence Sum Rule
$\color{#c00}\Rightarrow\, (a+b)\ {\rm mod}\ m\, \equiv\, (\bar a + \bar b)\ {\rm mod}\ m,\,\ $ which is the titled claim.
Remark $ $ Generally, as above, to prove an identity about mod as an operator it is usually easiest to first convert it into the more flexible congruence form, prove it using congruences, then convert back to operator form.
Answer: If $\pmod m$ just means that you subtract or add multiples of $m$ until you end up in the range $0,1,2,...,m-1$ then the RHS is easily compared to the LHS by collecting multiples of $m$.


.aspx file help

Question: Thank you for everyone's help so far! Have had some really helpful answers on this site so far so am hoping for one more.
What I want to create is EXACTLY this, but i'm still having problems
http://www.webonweboff.com/widgets/ajax/ajax_linked_selection.aspx
I have copied the html and javascript word for word and saved that file as index.html (but obviously with open and close html and body tags)
The file I have called ajaxServer.aspx.cs has the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/javascript";
        string id = Request.QueryString.Get("id");
        string action = Request.QueryString.Get("action");
        StringBuilder returnString = new StringBuilder();

        /*
            Retrieve the data based on values "id" and "action"
            and build a response string in this format:
                [{text:"...",
         *
         * value:"...",selected:false},
                 {text...}]
            No final ";" is necessary

            For example:
        returnString.Append("[{text:\"California\",value:\"CA\",selected:false}," +
                             "{text:\"OH\",value:\"Ohio\",selected:false}," +
                             "{text:\"NY\",value:\"New York\",selected:true}]");

        */

        Response.Write(returnString.ToString());
    }
}

and the file I have called ajaxServer.aspx has the following code:
<%@ Page Language="C#" AutoEventWireup="true"
    CodeFile="ajaxServer.aspx.cs" Inherits="_Default" %>

The other (.js) files I have downloaded and saved. When I run the .html file i get the following error:
error fetching data!
url:ajaxServer.asp
method:GET
params:action=state,culture=en-us
readyState:4
status:403
headers:Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 19 Jun 2011 20:39:55 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 2126
Connection: Close
--> Any clues anyone? And once again - thank you for all the help in advance!
Comment: Don't delete your question after it has been answered. It may help others in the future
Answer: Rename your class from _Default to widgets_ajax_ajaxServer.
Comment: Too bad there can only be one checked answer. Yours is the same answer tackled from the opposite direction.
Answer: I believe you want to change your ajaxServer.aspx file so that Inherits="_Default" instead of Inherits="widgets_ajax_ajaxServer".
Comment: Hi there - thanks for the help. That error has disappeared and I am now getting another one. It says "The type or namespace 'StringBuilder' could not be found (are you missing a using detective or an assembly reference?)
Comment: add using System.Text; as using statement.
Answer: "(are you missing a using detective or an assembly reference?)" Means exactly what it says.
StringBuilder lives in the System.Text namespace.
So you need a
using System.Text;
declaration at the top of the class.
Comment: Thanks for that - made the change and the error disappears. When I actually open index.html though, my 2nd box has no options in it now - unlike the example in the link I am taking the code from. Any ideas on this one? Thanks again!

.aspx file help


Region where function is negative for integral value of $x$

Question: Find the range of $a$ for which the quadratic expression $ax^2+(a-2)x-2$ is negative for exactly two INTEGRAL values of $x$.
The official answer is $a\in [1,2)$
My approach is as follow
The value $(a-2)^2+8a\ge 0$, hence no complex root.
$a>0$ is other condition
$f(n)=an^2+(a-2)n-2>0$
$f(n+1)=a(n+1)^2+(a-2)(n+1)-2<0$
$f(n+2)=a(n+2)^2+(a-2)(n+2)-2<0$
$f(n+3)=a(n+3)^2+(a-2)(n+3)-2>0$
Not able to approach from here
Comment: The value of $n$ is an integer
Answer: I don't see any particularly easy way to use your approach. Instead, note we can factor the quadratic expression to get that we're looking for where there's exactly $2$ integral values of $x$ satisfying
$$f(x) = ax^2 + ax - 2x - 2 = ax(x+1)-2(x+1) = (ax-2)(x+1) \lt 0 \tag{1}\label{eq1A}$$
As you've already stated, $a \gt 0$ so the parabola is concave up (otherwise, for $a = 0$, it's a straight, non-horizontal line, and for $a \lt 0$ it's concave down, with there being infinitely many integral values of $x$ where $f(x)$ is negative in both cases). One of the factors in \eqref{eq1A} must be negative while the other one is positive. If $x + 1 \lt 0 \;\to\; x \lt -1$ then, since $a \gt 0$, we have $ax - 2 \lt 0$ as well, so this is not allowed. Thus, we must have
$$x + 1 \gt 0 \;\to\; x \gt -1, \;\;\; ax - 2 \lt 0 \tag{2}\label{eq2A}$$
The first condition means that the integral values of $x$ we're looking for must be $0$ and $1$, so the second condition must hold for those $2$ values, but with $x = 2$ not working, so the second condition must not be true then. For $x = 0$, we have $-2 \lt 0$, while for $x = 1$ we require $a - 2 \lt 0 \;\to\; a \lt 2$. Finally, for $x = 2$, we need $2a - 2 \ge 0 \;\to\; a \ge 1$. Putting these together gives the official answer you provided, i.e.,
$$1 \le a \lt 2 \;\to\; a \in [1,2) \tag{3}\label{eq3A}$$

Alternatively, from \eqref{eq1A}, $f(0) = -2$ means $0$ is one of the integral values of interest. Since $f(x)$ must have $2$ roots, and $f(-1) = 0$, the other root is $1 \lt x \le 2$. Thus, then $f(1) = 2a - 4 \lt 0$, and $f(2) = 6a - 6 \ge 0$. This becomes
$$2a - 4 \lt 0 \;\to\; a \lt 2, \;\;\; 6a - 6 \ge 0 \;\to\; a \ge 1 \tag{4}\label{eq4A}$$
These $2$ conditions together then also leads to \eqref{eq3A}.


Trying to compare the numbers in 2 arrays PHP

Question: I am attempting to create one array with user entered numbers and then another array with random numbers between 0 and 9. I then want to compare the 2 arrays and when they match, echo out a result.
At the moment I'm receiving a fatal error:
Maximum execution time of 30 seconds exceeded
I know the elements are entered in the array correctly after using var_dump.
$i = 0;
while(!in_array($lotArray, $userArray)) {
   $i ++;
}

echo "YOU WON it took".$i."times";
?>

Comment: If `in_array()` returns `false` once, what makes you think that adding `1` to `$i` will change the result? `in_array` is still false. Consider this: "*Go to the store and buy dinner. 'Okay, I bought some ice cream'. 'No, go to the store and buy dinner'. 'Okay, I bought another ice cream'. 'Go to the store..'*"
Comment: which parameter of in_array() is the value you want to search for? it seems both of them are array.
Comment: if you can write down var_dump output examples for both arrays it would be easier for us to give an help
Comment: Ok I realised that was wrong. After everytime its false I want the array of random numbers to be reconstructed again and then checked with my user entered array.
Comment: Say if i have 1,1,1,1,1 in my first array, i only want it to work if the array with random numbers has 1,1,1,1,1 in as well
Comment: True, I'm sorry, I misunderstood the question!
Answer: Using an iterative approach to compare each number is Oh(n²) because you have to compare X times X numbers.
Instead, take a simple approach:

Sort both arrays in the same way. (Oh(n log n) each)
create a string out of them (Oh(n))
compare the strings. (Oh(n))

like
$arr1 = array(1,2,3);
$arr2 = array(2,3,1);

asort($arr1);
asort($arr2);

$string1 = implode($arr1, "_"); // "1_2_3"
$string2 = implode($arr2, "_"); // "1_2_3"

if ($string1 == $string2){
  echo "You've won!";

}
Answer: this works fine
$count     =   //your wish of getting random numbers.
$randarr   =   range('0','9');

$randarr   =   array_rand($randarr,$count);

$difference=   array_diff($randarr,$arr);   //let $arr be your array

if(count($difference)==0)
{
    //your display code
}

this enables you to create as many random numbers as the user selects.
Answer: If you wan to compare two arrays (all numbers must be the same, in the same order) :
$a1 = array(1, 9, 4);
$a2 = array(1, 9, 4);

if (count(array_diff($a1,$a2)) == 0)
    echo "Both array match";


F-Test for Equality of Variances as Likelihood Ratio Test

Question: Consider two normally distributed populations with unknown means $\mu_1$ and $\mu_2$ respectively and unknown variances $\sigma_1^2$ and $\sigma_2^2$ respectively. Let $X_1,X_2,\ldots,X_{n_1}$ and $Y_1,Y_2,\ldots,Y_{n_2}$ be i.i.d. random samples drawn independently from these respective populations. Show that a likelihood ratio test of hypotheses $\mathrm{H}_0: \sigma_1^2=\sigma_2^2$ vs. $\mathrm{H}_1: \sigma_1^2 \ne \sigma_2^2$ is equivalent to the usual $F$-Test, i.e. with critical region $\displaystyle\frac{s_1^2}{s_2^2} \ge f_{1-\alpha/2,n_1-1,n_2-1}$ if $s_1^2 \ge s_2^2$ and $\displaystyle\frac{s_2^2}{s_1^2} \ge f_{1-\alpha/2,n_2-1,n_1-1}$ if $s_1^2 < s_2^2$ (where $s_1^2=\displaystyle\frac{1}{n_1-1}\displaystyle\sum_{i=1}^{n_1} (x_i - \bar{x})^2$, $s_2^2=\displaystyle\frac{1}{n_2-1}\displaystyle\sum_{i=1}^{n_2} (y_i - \bar{y})^2$, and $f_{1-\alpha/2,n_1-1,n_2-1}$ is the upper $1-\frac{\alpha}{2}$ quantile of the $F$ distribution with $n_1-1$ and $n_2-1$ degrees of freedom).
For brevity, let $SS_x=\sum_{i=1}^{n_1} (x_i-\bar{x})^2$ and $SS_y=\sum_{j=1}^{n_2} (y_j-\bar{y})^2$.
I proceeded as follows: Under $\mathrm{H}_0$, the parameter space is $\{-\infty<\mu_1<\infty,-\infty<\mu_2<\infty,\sigma_1=\sigma_2>0\}$. Thus
\begin{align*}
L_0 &= (2\pi \sigma_1^2)^{-n_1/2} e^{-\frac{1}{2\sigma_1^2}\sum_{i=1}^{n_1}(x_i-\mu_1)^2}(2\pi \sigma_1^2)^{-n_2/2} e^{-\frac{1}{2\sigma_1^2}\sum_{j=1}^{n_2}(y_j-\mu_2)^2}\\
&=(2\pi\sigma_1^2)^{-(n_1+n_2)/2} e^{-\frac{1}{2\sigma_1^2}\left[\sum_{i=1}^{n_1}(x_i-\mu_1)^2 + \sum_{j=1}^{n_2} (y_j-\mu_2)^2\right]}\\
\log L_0 &= -\displaystyle\frac{n_1+n_2}{2} \log(2\pi \sigma_1^2) - \displaystyle\frac{1}{2\sigma_1^2}\left[\sum_{i=1}^{n_1}(x_i-\mu_1)^2 + \sum_{j=1}^{n_2} (y_j-\mu_2)^2\right] \\
\displaystyle\frac{\partial L_0}{\partial \mu_1}&=\displaystyle\frac{1}{\sigma_1^2}\sum_{i=1}^{n_1}(x_i-\mu_1)=0 \implies \hat{\mu}_1=\displaystyle\frac{1}{n}\sum_{i=1}^{n_1} x_i = \bar{x} \text{; similarly } \hat{\mu}_2=\bar{y}\\
\displaystyle\frac{\partial L_0}{\partial \sigma_1^2}&=-\frac{n_1+n_2}{2} \left(\frac{2\pi}{2\pi \sigma_1^2}\right)+\frac{1}{2}\left[\sigma_1^2\right]^{-2}\left[\sum_{i=1}^{n_1}(x_i-\mu_1)^2 + \sum_{j=1}^{n_2} (y_j-\mu_2)^2\right]=0\\
&\left[\sigma_1^2\right]^{-2}\left[\sum_{i=1}^{n_1}(x_i-\mu_1)^2 + \sum_{j=1}^{n_2} (y_j-\mu_2)^2\right]=(n_1+n_2)\left[\sigma_1^2\right]^{-1}\\
\hat{\sigma}_1^2&=\frac{1}{n_1+n_2}\left[\sum_{i=1}^{n_1}(x_i-\hat{\mu}_1)^2 + \sum_{j=1}^{n_2} (y_j-\hat{\mu}_2)^2\right]=\frac{1}{n_1+n_2}\left[SS_x+SS_y\right]\\
\therefore \max L_0 &= (2\pi\hat{\sigma}_1^2)^{-(n_1+n_2)/2} e^{-\frac{1}{2\hat{\sigma}_1^2}\left[SS_x+SS_y\right]}\\
&=(2\pi e)^{-(n_1+n_2)/2} \left(\frac{1}{n_1+n_2}\left[SS_x+SS_y\right]\right)^{-(n_1+n_2)/2}\\
L &= (2\pi \sigma_1^2)^{-n_1/2} e^{-\frac{1}{2\sigma_1^2}\left[\sum_{i=1}^{n_1}(x_i-\mu_1)^2\right]} (2\pi \sigma_2^2)^{-n_2/2} e^{-\frac{1}{2\sigma_2^2}\left[\sum_{j=1}^{n_2}(y_j-\mu_2)^2\right]}\\
&\text{M.L.E.'s are $\hat{\mu}_1=\bar{x},\hat{\mu}_2=\bar{y},\hat{\sigma}_1^2=\frac{1}{n_1}SS_x,\hat{\sigma}_2^2=\frac{1}{n_2}SS_y$}\\
\max L &= (2\pi \hat{\sigma}_1^2)^{-n_1/2} e^{-\frac{1}{2\hat{\sigma}_1^2}SS_x} (2\pi \hat{\sigma}_2^2)^{-n_2/2} e^{-\frac{1}{2\hat{\sigma}_2^2}SS_y}\\
&=(2\pi e)^{-(n_1+n_2)/2} \left(\frac{1}{n_1}SS_x\right)^{-n_1/2} \left(\frac{1}{n_2}SS_y\right)^{-n_2/2}
\end{align*}
Now, the critical region is of the form $\lambda =\frac{\max L_0}{\max L} \le k$ where $k$ is some constant.
\begin{align*}
\lambda =\frac{\max L_0}{\max L}=\frac{(2\pi e)^{-(n_1+n_2)/2} \left(\frac{1}{n_1+n_2}\left[SS_x+SS_y\right]\right)^{-(n_1+n_2)/2}}{(2\pi e)^{-(n_1+n_2)/2} \left(\frac{1}{n_1}SS_x\right)^{-n_1/2} \left(\frac{1}{n_2}SS_y\right)^{-n_2/2}} &\le k\\
\text{Taking both sides to power of -2, }\frac{\left(\frac{1}{n_1+n_2}\left[SS_x+SS_y\right]\right)^{n_1}\left(\frac{1}{n_1+n_2}\left[SS_x+SS_y\right]\right)^{n_2}}{\left(\frac{1}{n_1}SS_x\right)^{n_1} \left(\frac{1}{n_2}SS_y\right)^{n_2}} &\ge k^\prime\\
\left(\frac{n_1}{n_1+n_2}\left[1+\frac{SS_y}{SS_x}\right]\right)^{n_1}\left(\frac{n_2}{n_1+n_2}\left[1+\frac{SS_x}{SS_y}\right]\right)^{n_2} \ge k^\prime\\
\left(1+\frac{SS_y}{SS_x}\right)^{n_1}\left(1+\frac{SS_x}{SS_y}\right)^{n_2} \ge k^{\prime\prime}\\
\end{align*}
This is as far as I could simplify it; I am close to expressing the critical region in terms of a ratio of sample variances but cannot see how to get rid of the powers of $n_1$ and $n_2$.
Answer: Taking the critical region
$\left(1+\frac{SS_y}{SS_x}\right)^{n_1}\left(1+\frac{SS_x}{SS_y}\right)^{n_2} \ge k^{\prime \prime}$, let $r=\displaystyle\frac{SS_x}{SS_y}$ and write the left side of the expression as a function of $r$, i.e. $g(r)=(1+r^{-1})^{n_1}(1+r)^{n_2}$. We can show using calculus that this function has a minimum at $r=\frac{n_1}{n_2}$. Thus, $g(r)$ increases as we move left or right from this point, and so the inequality $g(r) \ge k^{\prime \prime}$ will be satisfied for very small $r$ or very large $r$. Thus we can rewrite the critical region as
$\displaystyle\frac{SS_x}{SS_y} \le k_1 \cup \displaystyle\frac{SS_x}{SS_y} \ge k_2$ where $k_1,k_2$ are constants. Equivalently,
$\frac{SS_x/(n_1-1)}{SS_y/(n_2-1)}=\frac{s_1^2}{s_2^2} \le k_1^\prime \cup \frac{SS_x/(n_1-1)}{SS_y/(n_2-1)}=\frac{s_1^2}{s_2^2} \ge k_2^\prime$
Under $\mathrm{H}_0$, since $\sigma_1^2=\sigma_2^2$, $S_1^2/S_2^2$ has an $F(n_1-1,n_2-1)$ distribution. Thus, a critical region of size $\alpha$ is constructed as follows:
        \begin{align*}
   &\Pr\left(\displaystyle\frac{S_1^2}{S_2^2} \le k_1^\prime \cup \displaystyle\frac{S_1^2}{S_2^2} \ge k_2^\prime\right)=\alpha\\
   &\Pr\left(\displaystyle\frac{S_1^2}{S_2^2} \le k_1^\prime\right) +  \Pr\left(\displaystyle\frac{S_1^2}{S_2^2} \ge k_2^\prime\right)=\alpha\\
   &\text{If we divide the type I error prob. equally between the two,}\\
   k_1^\prime&= f_{\alpha/2,n_1-1,n_2-1} \text{ and } k_2^\prime=f_{1-\alpha/2,n_1-1,n_2-1}
  \end{align*}
        And therefore we can write the critical region as $\displaystyle\frac{s_1^2}{s_2^2} \le f_{\alpha/2,n_1-1,n_2-1} \cup \displaystyle\frac{s_1^2}{s_2^2} \ge f_{1-\alpha/2,n_1-1,n_2-1}$.
Finally, if we prefer, we can rewrite $\displaystyle\frac{s_1^2}{s_2^2} \le f_{\alpha/2,n_1-1,n_2-1}$ as $\displaystyle\frac{s_2^2}{s_1^2} \ge \displaystyle\frac{1}{f_{\alpha/2,n_1-1,n_2-1}}$ and therefore, making use of a property of the $F$ distribution, as
        $\displaystyle\frac{s_2^2}{s_1^2} \ge f_{1-\alpha/2,n_2-1,n_1-1}$


Finding fixed points of an equation when the derivative is not defined

Question:
For a dynamical system governed by the equation $f(x) = \mathrm{d}y/\mathrm{d}x = 2(1-x^2)^{1/2}$. Find stable and unstable fixed points.

The fixed points for the above equation are $+1$ and $-1$. I took the derivative of given equation and set it equal to zero.
If $f'(x)<0$, it's a stable point and if $f'(x)>0$, it's an unstable point.
The derivative is
$$\frac{-2x}{(1-x^2)^{1/2}}$$
Now if I plug $x=1$ or $x=-1$, it's not defined. How do I find the stability of fixed points in this case?
Comment: It's unclear exactly what you're looking for. Is the unknown function $y(x)$? Then what does $f(x)$ have to do with anything? Or is the system $\dot x = f(x)$? Then what does $y$ have to do with it? (Or is it a discrete system $x_{n+1}=f(x_n)$? Not likely, since $f(0)=2$ goes outside the interval where $f$ is defined.)
Answer: If what you mean is that the system is $dx/dt=f(x)$, then just draw the phase portrait on the interval $[-1,1]$, using that $dx/dt > 0$ for $-1<x<1$.
Comment: I am not able to understand how we conclude about the stability of the fixed points by obtaining $dx/dt>0$?
Comment: @BAYMAX: Well, what happens if you perturb one of the equilibria $\pm 1$ a little, by moving into the open interval $(-1,1)$? Where does the point go, as $t \to +\infty$, if it can only move to the right? (Since the system is only defined on $[-1,1]$, it's not meaningful to talk about perturbing the equilibria out of this interval.)
Comment: Yes, thanks but that is exactly what i want to see, I want to write $x(1-\epsilon)$ but how could i?, i dont know the analytical solution? how should i proceed?
Comment: but how could i?, i dont know the analytical solution? how should i proceed?, but since $dx/dt>0$ so perturbation from 1 on the right side will definitely push the trajectory to the right, so I think the trajectory moves away from $x=-1$ hinting me unstable but now if we similar analysis to $x=1$, it will push the trajectory to the left since $dx/dt>0$, so $x$ value must increase as $t$ increases, that is it pushes the x to left so kind of repelling from $x=1$, so I think both $x=1,-1$ are unstable???
Comment: @BAYMAX: You don't need the analytical solution, that's the whole point of looking at the phase portrait instead. Anyway, your resoning is on the right track, except that when you perturb $x=+1$ towards the left, into the interval $(-1,1)$, the point will be pushed *back* towards the right, back to the equilibrium where you started. So $x=+1$ is stable.
Comment: nice! but if we start near to $x=1$ on the left(since it cannot be on the right of 1, violating domain), then if the next iterate will rightwards then $x$ value is decreasing (evident from the curve here - downward parabola), now $x$ cannot decrease as $dx/dt>0$, please help?
Comment: here - https://www.desmos.com/calculator/q5xhecndvy
Comment: Sorry, I don't understand what you mean... If you're talking about iterates, then you're referring to a discrete-time dynamical system $x_{n+1}=f(x_n)$. But I clearly stated in my answer that I'm talking about the continuous-time case $dx/dt=f(x)$. (It's far from clear what was meant in the original question, but as my comment there said, it's not likely to be a discrete-time system since $f(0)$ goes outside of the domain.)
Comment: And $f(x)$ being decreasing is not a problem, it just means that $x(t)$ will increase more slowly (but it will still increase, since $f(x)>0$).
Comment: Chat extended, sorry, can Iinvite you to [Dynamical Systems chatroom](https://chat.stackexchange.com/rooms/55403/dynamical-systems-and-chaos-theory), to discuss a bit about the analysis near $x=1$?
Comment: I'm not a chat person, keep the comments here please.
Comment: Sorry, when we are near $x=1$, and we check how the dynamics is evolving after this perturbation? we say suppose $x$ goes towards right side of the Initial condition, then due to the downward parabola, $x$ value decreased, so my question is how here still $dx/dt>0$ ?
Comment: @BAYMAX: No no no, it's not $x$ that's decreasing. What's decreasing is the value $f(x)$ which describes the **velocity** $dx/dt$. The $x$ value is still increasing, only more slowly (as I already wrote in a previous comment). Just to be clear, do you understand that I'm talking about a differential equation $dx/dt=f(x)$ and **not** a discrete-time system?
Comment: Got it!!, thanks!! i was a bit confused
Comment: @BAYMAX: Great!


Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\aula\exercicio\update.php on line 11

Question: Galera estou com um problema com essa mensagem de erro,verifiquei a conexão com o banco de dados e esta certo eu consigo cadastrar mas na hora de dar update ele da esse erro e não consigo descobrir
Segue o código do update:
    ?php
    include "conexao.php";
    if(!empty($_POST)){
        $id = (isset($_POST['id'])) ? $id = $_POST['id'] : mysqli_close($conect);
        $cpf = (isset($_POST['cpf'])) ? $cpf = $_POST['cpf'] : mysqli_close($conect);
        $nome = (isset($_POST['nome'])) ? $nome = $_POST['nome'] : mysqli_close($conect);
        $email = (isset($_POST['email'])) ? $email = $_POST['email'] : mysqli_close($conect);
        $telefone = (isset($_POST['telefone'])) ? $telefone = $_POST['telefone'] : mysqli_close($conect);
        $sql = "UPDATE cadastro SET cpf = '$cpf',nome = '$nome',email = '$email',telefone = '$telefone'
        WHERE id = '$id' ";
        $query = mysqli_query($conect,$sql);

        var_dump($id);
        var_dump($cpf);
        var_dump($nome);
        var_dump($email);
        var_dump($telefone);
    }
    else{

        header("Location:cadastro.php");
    }

?>

Segue a conexão:
<?php
$host = "localhost";
$user = "root";
$psw= "";
$db = "exercicio";
$conect = mysqli_connect($host,$user,$psw,$db);
$charset = mysqli_set_charset($conect,"utf8");
 ?>

Comment: Você está usando o operador ternário como se fosse um `if/else. Ele funciona como um if. Ele testa uma condição (o primeiro operando), se ela for verdadeira, o resultado da operação é o primeiro valor (após o ?, o segundo operando), se ela for falsa, então o resultado é o segundo valor (depois do :, o terceiro operando). Leia essa resposta: https://pt.stackoverflow.com/a/56814/137387
Answer: Você esta executando o mysqli_close antes da query, nem faz sentido executar ali, o correto é executa-lo após o mysqli_query, ou melhor após tudo necessário.
Na verdade tem uma série de erros no seu código, até a maneira que setou as variáveis não tem sentido, não esqueça de escapar as variáveis com mysqli_real_escape_string, deveria ser assim:
$id = (isset($_POST['id'])) ? mysqli_real_escape_string($_POST['id']) : '';
$cpf = (isset($_POST['cpf'])) ? mysqli_real_escape_string($_POST['cpf']) : '';
$nome = (isset($_POST['nome'])) ? mysqli_real_escape_string($_POST['nome']) : '';
$email = (isset($_POST['email'])) ? mysqli_real_escape_string($_POST['email']) : '';
$telefone = (isset($_POST['telefone'])) ? mysqli_real_escape_string($_POST['telefone']) : '';

$sql = "UPDATE cadastro SET cpf = '$cpf',nome = '$nome',email = '$email',telefone = '$telefone'
    WHERE id = '$id' ";

$query = mysqli_query($conect,$sql);

mysqli_close($conect);

Comment: obrigado corrigi esta tudo normal agora


como mostrar e esconder uma div

Question: boas tenho este codigo que supostamente devia dar para mostrar e esconder uma div mas não me esta funcionado. `

                        <input id="circular" type="radio" class="form-control" name="circular"  value="0"   checked="checked"  />

                        <input  id="barras" type="radio" class="form-control"  name="barras" value="1"    />

$("#barrasgrafico").on("change", function () {
                   $("#bar_div").show();
                   $("#chart_div").hide();
               });
               $("#circulargrafico").on("change", function () {
                   $("#bar_div").hide();
                   $("#chart_div").show();
               });`

Comment: Seu código javascript está fora da tag ``?
Comment: Onde estão as `divs` correspondentes aos **ID's** `bar_div` e `chart_div` ?
Comment: as div estão a seguir a primeira div sim o codigo ta dentro do javascript
Answer: Você tem vários problemas no seu código se é esse mesmo seu código completo,
pra começar você  não esta separando o seu javascript do html, você deve utilizar um
é já que você utiliza código jquery deve incluir a biblioteca antes.
se ja foi feito, veja que você esta querendo esconder/mostrar objetos que não existem, por exemplo: não existe o circulargrafico.
Vou deixar um exemplo desse processo funcionando:

$('input[type=radio]').change(function() {
  $("#div1,#div2").hide(); // seletores que serão escondidos
  var div = $(this).val(); // pega o valor do input radio que é o nome da div a ser mostrada.
  $('#' + div).show(); // mostra a div
});

    <input type="radio" name="optionsRadios" value="div1" checked>Mostra div 1

    <input type="radio" name="optionsRadios" value="div2">Mostra div 2

Conteúdo da Div 1

Conteúdo da Div 2

como mostrar e esconder uma div


Understand wireshark capture for ssh key exchange

Question: I need to understand SSH key exchange, I have tried to read RFC document but it seems very difficult to understand so I have captured packets using wireshark ,I found various packets for ssh keyexchange
SSHv2 Client: Key Exchange Init
SSHv2 Server: Key Exchange Init
SSHv2 Client: Diffie-Hellman Key Exchange Init
SSHv2 Server: Diffie-Hellman Key Exchange Reply
SSHv2 Client: Diffie-Hellman GEX Init
SSHv2 Server: Diffie-Hellman GEX Reply
SSHv2 Client: New Keys

Can any one explain me each packet in detail or sequence of ssh key exchange ??
Comment: Do you actually have a problem you are trying to solve?
Comment: It's not clear what information you are looking for. However have you tries initiating an SHH session while uning the verbose switch a few times? ie `ssh -vvvv firstname.lastname@example.com`
Comment: It's typical "Anybody! Read aloud Wikipedia for me" question.
Answer: First of all you should understand the concept of a Diffie-Hellman exchange. It allow to establish a channel between 2 endpoints with these features:

Protects against eavesdropping. Someone sniffing on the channel cannot decrypt it.
Diffie-Hellman Does NOT protect against man-in-the middle attacks. This kind of attacks are prevented through verification of host key. This is done after DH exchange, so it is encrypted and cannot be analyzed with wireshark at this time.
It generates random number that cannot be determined by neither of the peers alone, but the two together. This is an interesting concept to me.
From the wikipedia article here is a simplified structure of the exchange:

Let g be a known public number from a finite cyclic group.
Alice picks a random natural number a and sends ga to Bob.
Bob picks a random natural number b and sends gb to Alice.
Alice computes (gb)a = gab
Bob computes (ga)b = gab

As a result they have generated a safe random secret gab.
AND NOW FOR THE WIRESHARK CAPTURE!

SSHv2 Client: Key Exchange Init
Several parameters negotiation, like compression and some crypto algorithms.
SSHv2 Server: Key Exchange Init
Reply to above
SSHv2 Client: Diffie-Hellman Key Exchange Init
Negotiation of the DH parameters about mathematical group. (See RFC4419 section 3 for more details).
SSHv2 Server: Diffie-Hellman Key Exchange Reply
Reply to above.
SSHv2 Client: Diffie-Hellman GEX Init
First actual exchange of DH. Following wikipedia notation this would be step 2 (Alice sends ga).
SSHv2 Server: Diffie-Hellman GEX Reply
The exchange finishes (Bob sends gb).
After receiving this packet both peers know the secret key (gab) and establish a pseudo-secure channel with it (secure against casual eavesdropping, but not against man-in-the-middle-attacks).
SSHv2 Client: New Keys
This looks like a simple acknowlegding message to me. It is small and contains no significative data.
Ok, I suppose there's a lot going on after this (server public key verification, user authentication, establishment of data channels for shell/sftp/scp/tunnels, etc). I don't know the exact details and (un)fortunately all this is encrypted.

Useful references:

http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
http://www.ietf.org/rfc/rfc4251.txt
Comment: Excellent point and rarely outlined for MITM prevention done after DH exchange.
Answer: The client and the server begin by sending to each other the protocol and software versions they are using.
SSHv2 Client: Key Exchange Init

Here, the client tells the server the algorithms it supports for each function (encryption, MAC, key exchange, host authentication, compression), in order of preference.
SSHv2 Server: Key Exchange Init

The server does the same.  Note that it can send this message before it has received the one from the client.
From the two lists of algorithms, the client and the server compute independently the same cipher suite.  For instance, they choose the same kex exchange algorithm (and it takes place right after that).
SSHv2 Client: Diffie-Hellman Key Exchange Init
SSHv2 Server: Diffie-Hellman Key Exchange Reply
SSHv2 Client: Diffie-Hellman GEX Init
SSHv2 Server: Diffie-Hellman GEX Reply

The Diffie-Hellman key exchange enables the client and the server to end up with a shared secret that an observer on the network cannot feasibly guess.  For example, they will derive a key for the encryption algorithm from this secret.
Note that the reply of the server also contains its public host key (or certificates).  If it is a public key and the client has never seen it, the client usually asks the user if it should trust it:

The authenticity of host 'debian.org (220.127.116.11)' can't be established.
ED25519 key fingerprint is SHA256:bNnjFMvzsNhkwzRHwGRbTIUM4XzUjlLrBl/7MzCbndw.

SSHv2 Client: New Keys

With the New Keys message, the client means:

Hey server!  All the following messages from me will use the ciphers we just negotiated.

The server must also send a New Keys message to the client.
My main reference is the RFC for the SSH Transport Protocol: https://www.rfc-editor.org/rfc/rfc4253.  This is the lowest layer of SSH, on which all other SSH services (user authentication, shell, X11 forwarding, etc) are based.


How to print login form on page

Question: How to print login form with destination url on a page using code in drupal 7  ?
Comment: have you searched the web? what did you try? http://stackoverflow.com/questions/11995551/drupal-render-login-form-programatically
Comment: right now i am using it, but i cant change destination url with it
Answer: You can use below code to print login form block
<code><?php
print(drupal_render(drupal_get_form('user_login_block')));
?>
</code>
For login redirect to destination you can use Login Destination module
Project page says

The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.
Comment: with `print(drupal_render(drupal_get_form('user_login_block')));` i can't change destination url
Comment: You can use rules module to redirect user to custom url on login...
Comment: by using rules all users will be redirected to a page after login, but i want them to redirect only if they are logged in with form on a specific page and the page is not static page as well , it will be a referenced node.
Comment: To avoid PHP Strict errors, use $form = drupal_get_form('user_login_block');
                                print(drupal_render($form));
Answer: Outputting the form:
https://stackoverflow.com/questions/11995551/drupal-render-login-form-programatically
Redirecting after submit:
https://drupal.org/node/290462
Comment: by using above all users will be redirected, i want them redirected if they login from a specific page with login form.
Comment: I am sure you can set a session variable when your particular page has been hit and then check it in your hook.

How to print login form on page


$X$ is Hausdorff, $G$ is a finite group prove that $X/G$ is Hausdorff.

Question: I want to start this off by saying I've seen the other questions that are identical to this one, but I didn't really understand the suggestions given in those.
So the question states: Let $G$ act continuously on $X$ i.e the map $G\times X\to X$ sending $(g,x)\mapsto gx$ is continuous. Then define an equivalence relation $x\sim y$ if and only if there exists a $g\in G$ such that $gx=y$. Then give $X/\sim :=X/G$ the quotient topology. Show that if $X$ is Hausdorff and $G$ is finite then $X/G$ is Hausdorff.
I have my attempt bellow, however I am stuck on the last part where I want to show $U$ and $V$ are disjoint. I'm not really sure how to come to a conclusion.

Choose two orbits, $Gx\neq Gy$, then we have
$x\neq y$. Define $U_g$ and $V_g$ to be open neighbourhoods of $gx$
and $gy$ respectively, such that $U_g\cap V_h=\emptyset$ for all
$h,g\in G$, which we can do as $X$ is Hausdorff and $gx\neq hy$ as
they are in different orbits. Now consider all the sets $p(U_g)$ and
$p(V_g)$, I claim that $U=~\bigcap_{g\in G}p(U_g)$ and
$V=\bigcap_{g\in G}p(V_g)$ are disjoint neighbourhoods of
$\overline{x}$ and $\overline{y}$ (The equivalence classes of $x$ and $y$ respectively).
Since each $p(U_g)$ and $p(V_g)$ are open by Lemma 2 (Lemma 2 just
says $p$ is an open map), furthermore $U$ and $V$ are finite
intersections of these open sets, as $G$ is finite, we have that they
are open in $X/G$. $U$ certainly contains $\overline{x}$ as each $U_g$
contains $gx$ for some $g\in G$ which is equivalent to $x$, and with
an identical argument $V$ contains $\overline{y}$. Suppose for a
contradiction that $U\cap V$ is non-empty, take an element
$z\in~U\cap~V$ then $z\in p(U_g)$ and $z\in p(V_g)$ for each $g\in G$.

Thanks in advance.
Comment: Hint: $X/G$ is Hausdorff iff the diagonal $\Delta$ of $X/G \times X/G$ is closed. Since $p$ is an open quotient map, $p\times p$ is also a quotient map, so it suffices to prove that $(p\times p)^{-1}(\Delta)$ is closed in $X\times X$.
Comment: So just checking your first comment is an alternative proof? Then for the second one is $g\cdot A\cap B$ the same as $(g\cdot A)\cap(g\cdot B)$ so $A$ and $B$ contain no elements that are in the same orbit, something like this?
Comment: Ah I see, thanks so much for the answer by the way it really helped!
Comment: The trick for concluding your argument is to make a more "explicit" construction of $U_{g}$ and $V_{h}$. As a matter of fact, you can choose open subsets $A$ and $B$ such that $x\in A$, $y\in B$ and $g\cdot A \cap B=\emptyset$ for every $g$. Your desired open sets are $p(A)$ and $p(B)$.
Comment: I think that they are not the same. But yes, it'd be an alternative proof (the method is pretty much the same).
Comment: The reason for the first comment is that the "closedness" argument is valid for a more general type of actions, called "proper actions". This is the finite version, and the discrete version is sometimes named "properly discontinous" (even though the action is by definition continuous...)
Comment: No problem! I find that group actions are always very helpful in topology and geometry, so it's always nice to see people studying them!
Answer: Let $Gx\neq Gy$. The argument is very similar to what you have done so far!
Take $g\in G$. Since $g\cdot x \neq y$, there are open sets $U_{g},V_{g}$ such that $g\cdot x\in U_{g}$, $y\in V_{g}$ and $U_{g}\cap V_{g}=\emptyset$. Now choose the following open subsets:
$$
U=\bigcap_{g\in G}g^{-1}U_{g}, V=\bigcap_{g\in G}V_{g}.
$$
Since $G$ is finite and left translations are homeomorphisms, $U$ and $V$ are open neighbourhoods of $x$ and $y$. Notice that, for every $g$, $gU\cap V=\emptyset$.
Now, choose $p(U)$ and $p(V)$. We only need to prove that $p(U)\cap p(V)=\emptyset$.
Let $p(z)\in p(U)\cap p(V)$, so that $p(z)=p(a)=p(b)$ for some $a\in U$, $b\in V$. Therefore, for some $h\in G$, $b=ha\in V\cap hU$, which is a contradiction.
Hope this helps!


how to allow characters, space and dot in regular expression?

Question: ValidationExpression="^[a-zA-Z ]+$"

this is my current regular expression but it does not accept .(dot). I need to use it for names. like "Reynante A. Capco"
Comment: What have you tried? What don't you understand? Do you know the basic syntax for regular expressions?
Comment: prefix `\` backslash for special characters. eg `\.` for dot. `\s` for space.
Answer: The following expression gets all

characters (a-zA-Z)
whitespaces (\s) and
dots (\.)

between the string beginning (^) and end ($):
The '@' is necessary to quote the backslashes inside the string.
ValidationExpression=@"^[a-zA-Z\s\.]+$"

Answer: This should work:
/[a-zA-Z]|\d|\s|\.*/

Any letter a-z
Any digit 0-9
Any whitespace
Any dots
Comment: Try `[a-zA-Z]|\d|\s|\.*`, it's different for C#
Comment: it does not work also  ValidationExpression="[a-zA-Z]|\d|\s|\.*"
Comment: ValidationExpression=@"[a-zA-Z]|\d|\s|\.*"
You need the @ so that the \'s don't need to be escaped in a string. (it tells the compiler to take this string literally).
Answer: Validation for must contain a number, a character and a dot. Sometimes it must include a space.
For example:
version1.1.1-----valid
            version 1.1.1---valid
              v1.1.----------not valid(not end with dot)
             .v1.1--------not valid(not start with dot)
               v1----valid
               version 12.1.1--------valid

It must contain character and number dot and space are necessary
if its dot not start with dot and not end with dot


Sharing an image in LinkedIn integration in iPhone

Question: We can share a message(text) through LinkedIn integration in iPhone Apps.....
But Is there any possibility to share a local image or url image through LinkedIn integration in iPhone Apps......?
Thanks In Advance.....
Comment: http://stackoverflow.com/questions/13410986/how-to-post-an-image-to-a-linkedin-account-using-objective-c-code-on-ios
Comment: If you are able then let me know..
Comment: it is Possible @Rajneesh071 ...But the Limitations are...-->Not supported for local images..-->Not supported for high memory url images.
Comment: I did not implemented it yet,,. just made a search for you..
Comment: so just implement it and let me know..i will make it answer of your question..L)
Answer: Any how i got a relative solution...
Sharing an image in LinkedIn integration in iPhone---->
<code>NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
                                consumer:oAuthLoginView.consumer
                                   token:oAuthLoginView.accessToken
                                callback:nil
                       signatureProvider:nil];

NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [[NSDictionary alloc]
                         initWithObjectsAndKeys:
                         @"anyone",@"code",nil], @"visibility",
                        statusTextView.text, @"comment",[[NSDictionary alloc]
                                                         initWithObjectsAndKeys:
                                                         @"description goes here",@"description",
                                                         @"www.google.com",@"submittedUrl",
                                                         @"title goes here",@"title",
                                                         @"http://economy.blog.ocregister.com/files/2009/01/linkedin-logo.jpg",@"submittedImageUrl",nil],@"content", nil];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSString *updateString = [update JSONString];

[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:@"POST"];

OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
                     delegate:self
            didFinishSelector:@selector(postUpdateApiCallResult:didFinish:)
              didFailSelector:@selector(postUpdateApiCallResult:didFail:)];
</code>
Comment: But the Limitations are...-->Not supported for local images..-->Not supported for high memory url images.
Comment: @AshokKumarIOS...I know this method...& also its limitation.That's why I am not suggested you by this way...& simple advice you that it is not possible dude.
Comment: @AshokKumarS, I used your code but Image is not shown when I open my account in the browser.
Answer: I think no.I was able to send text to LinkedIn via share kit . But I was not unable to upload
image to LinkedIn.
So, I think it is not possible.
Comment: @Vishal.. is it possible to Share an Image in Google+ integration..   See My Another Question in [link](http://stackoverflow.com/questions/14872759/sharing-images-in-google-using-iphone-app)


Why are violin string so expensive?

Question: What exactly is about violin strings that make them so expensive in comparison to guitar strings? Is there something about the manufacturing process that is just more expensive?
Does it have something to do with bowed strings vs plucked strings?
Comment: Probably has far more to do with market forces. Thousands more guitar strings must be sold than violin strings. At very least, I think guitar strings are more sacrificial.
Comment: @Tim not in the least.  Take a look at guidot's answer.  Guitar strings are cheap throwaways compared with violin, cello, bass, and even elec.bass strings.
Answer: I actually see not much more than the name string they have in common. While I have only superficial knowledge of guitar strings they seem to have simple homogeneous structure like nickel-plated steel, which is easily mass-produced. If you choose the same material for violin, prices don't seem to be significantly different. But nearly no one uses them. Typical violin strings have a core/wrapping structure and the wrapping can easily be something like silver wire. Even if the rosin applied to the bow significantly contributes to the friction necessary for torsion vibration, a somewhat rough surface of the string supports it.
Comment: Just to add in, here is what a string looks like under a microscope http://mdarnton.tumblr.com/post/12184117752/a-dominant-violin-d-string-under-the-microscopic

Why are violin string so expensive?


Detection of screenshot taken?

Question: Is there any way i can detect in my service when user takes screenshot of his android device?
The basic idea is whenever user takes screenshot of his device a popup will be displayed asking user to upload image to facebook, twitter etc.
Comment: I assume that you are the one that make that service. Do you put the screenshot on a `Bitmap` object? Can you please help us by some chunk of codes?
Answer: This is untested, but you may want to try the FileObserver class.
Point it at the screenshots folder and wait for a CREATE event.
https://developer.android.com/reference/android/os/FileObserver.html
Comment: Just FYI I think file observers will work but some versions are buggy with it like android 6.0 https://stackoverflow.com/questions/36237314/fileobserver-and-contentobserver-not-working-in-android-marshmallow

Detection of screenshot taken?


How do you determine if there is a significant relationship between two variables with several factors affecting it, using R?

Question: I want to check if there is a significant relationship between x and y, and then check if this relationship is affected by different stimuli (2 levels), colonies (2 levels), and lightings situation (2 levels).
Which statistical test should I apply?
bellow is my sample dataset:
Colony means that individuals are coming from different mothers.
The hypothesis is that under different lighting conditions (whether light or dark), the result will not change.
In this example x is the number of successes during training _ all subjects (ID) have got a specific amount of time (like 10 hours) to do a task, one individual could do it 100 times during the given time, and the other could do only 60 times for example. For y, which is the number of successes during the memory test, all subjects (ID) got a specific amount of time (like 5 hours) to do the task, again one individual did the task 50 times during the given time while another did it only 20 times. So training (x) was done for 10 hours, but the memory (y) was tested for 5 hours, but the timing was the same for all individuals (ID), the number of successes could be as much as an individual is willing to do the task.
df <- structure(list(ID=c(1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40),
                     colony=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
                     stimulus=c("Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat", "Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold","Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat","Heat", "Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold","Cold"),
                     lighting=c("light","light","light","light","light","dark","dark","dark","dark","dark","light","light","light","light","light","dark","dark","dark","dark","dark","light","light","light","light","light","dark","dark","dark","dark","dark","light","light","light","light","light","dark","dark","dark","dark","dark"),
                     x=c(124,  73,  83,  85,  67, 100,  56,  88,  76,  68, 105,  92,  85, 103, 129,  90, 82,  82,  78,  96,  83,  92,  57,  52,  56,  75,  96,  85,  72,  56,  50,  69, 45,  49,  52,  46,  49,  52,  55,  77),
                     y=c(89, 63, 46, 70, 60, 75, 30, 62, 42, 44, 57, 33, 45, 58, 47, 37, 33, 38, 33, 35, 53, 46, 41, 49, 55, 29, 47, 43, 41, 49, 53, 41, 31, 37, 35, 32, 51, 44, 38, 75)),
                class = "data.frame", row.names = c(NA,-40L))

And the main question is whether the number of successes during memory has any relationship to the number of successes during the training (so does having more success during training leads to more success during memory?)
Comment: btw this isn't so much an R question as a statistics question. if these are not randomized controlled trials you may benefit from causal modelling.
Comment: A problem with your setup is that you have very few data points and you can not get a good insight into the underlying pattern. A linear fit could be used but if you do not control for the other variables (not only have interaction terms for the slope but also have main effects included) then you may get a [yule-simpson effect](https://en.m.wikipedia.org/wiki/Simpson%27s_paradox)....
Comment: ... in addition, your groups are not measured with the same training conditions. If the underlying relationship is not truly linear, then you may also get a wrong idea about the effect of the training variable on the memory test. See: [A misspecification error with linear models that can complete reverse the direction of an effect, has this been described, has this a name?](https://stats.stackexchange.com/questions/575039/).
Comment: Do you intend to do causal analysis? How was the data collected?
Comment: These are randomized control trials
Comment: Are the conditions 'stimulus' and 'lightning' also the same during the memory test?
Comment: Yes they are the same during the training and test
Answer: I presume that you want to know whether the linear relation between $x$ and $y$ is different depending on those additional variables, which I also presume to not be confounders. Thus, you don't want to control for them but you rather want to learn their interaction with the treatment $x$.
If that is all true, use as formula for 'lm':
$$
y \sim x \;+\; \mbox{stimulus}:x \;+\; \mbox{colony}:x \;+\; \mbox{lighting}:x
$$
and the p-values of the coefficients of the interaction terms, given by the model fitted by lm, will then tell you whether those interactions are significant.
To make it more complicated, you could also think about higher-order interactions like $x$:stimulus:colony.

Edit:
And I agree with @dipetkov's point below that, at least in general in those situations, we should also include an offset for the interactions. This was an omission on my side.
Comment: Please don't overload this thread with additional questions, rather create a new question. And yes, you can use glmer this way in this case. However, try not to overcomplexify your model.
Comment: I don't know what your $x$ value actually is, but `colony` and `lightning` are only confounders if they causally affect *both* $x$ and $y$. Also, if `colony` and `lighting` do not affect the result you shouldn't add them to the formula at all. Anyway, if you do want to add them without any interaction just add them as linear terms like this: y ~ x + stimulus:x + colony + lightning.
Comment: OK, then the formula I gave in my last comment is appropriate.
Comment: Thank a lot @frank, here for this experiment I hope that  Colony and lighting do not affect the result, so if I consider them as confounders, how would the formula change? But knowing the effect of the stimulus is very important for me.
Comment: Thanks, @frank, x is the number of successes during training, and y is the number of successes during the memory test. So yes, colony and lighting are affecting both x and y. And the main question is whether the number of successes during memory has any relationship to the number of successes during the training (so does having more success during training leads to more success during memory?)
Comment: if **colony** and **ID** are random effects, can I use glmer?  like this `glmer (y ~ x + stimulus:x  + lighting + (1|colony/ID), data=df, family="poisson")`
Comment: *" x is the number of successes during training, and y is the number of successes during the memory test"* is the total of trials during training and during memory test fixed?
Comment: @SextusEmpiricus Good point. I presumed so. I.e. I understood $x$ and $y$ as measures of the success *rates*.
Comment: No the total trial during the training and during the memory differs
Comment: Please give an exact specification of $x$ and $y$. You said that $x$ and $y$ are the *number* of successes during training and memory resp. But you also say that the total numbers of trials differ. So if you have 10 training trials with 10 successes and 100 memory tests with 10 successes, then you would record $x=10$ and $y=10$, too?
Comment: I add the answer in the main text of the question
Comment: Since you use the word "success" I presume there are also attempts that are failures. Is this correct?
Comment: yes, so I have the same dataset for failures (with different numbers for x and y)
Comment: But the failures are not part of your model?
Comment: No I don't need them for this model
Answer: I disagree with @frank's advice to include interactions (with $x$) but no main effects for the stimulus, lighting and colony variables. But see How do you deal with "nested" variables in a regression model? for an important exception to this rule.

Moreover, a scatterplot of the data reveals that the two colonies are observed under different conditions. The difference is most pronounced when stimulus = "Cold" as there is complete separation in the $x$ values. (This may indicate that $x$ is not really a "treatment" assigned randomly to units as @frank interprets it.) This pattern suggests to interact colony with all the other variables, which leads — visually at least — to a better model fit.

Update: The OP has provided additional context. The experimental design is still unclear but it seems the units were randomized to one of four conditions (stimulus×lighting), given time to train under the assigned condition (x), and then tested "officially" (y). The numerical variables x and y are number of successfully completed tasks in a fixed amount of time (everyone got the same amount of time). The number of attempted but unsuccessful tasks is ignored though it may be important: what if stimulus and lighting affect the number of trials but not the success rate of a trial?
Also unexplained is the concept of a colony. The number of successes x during training under Cold stimulus is markedly different for colonies 1 and 2. On its own, the data cannot explain why this happened and therefore the data cannot point out which is the most scientifically justified model either. Instead the OP should explain/examine the difference between the two colonies. If these two colonies were sampled from a larger population, it would help to do followup experiments to investigate the variability between colonies under "Cold" stimulus. If these two colonies are the only ones of interest, it would help to sample more units from each colony to study the variability within each colony.
To highlight the importance of colony and following comments by @SextusEmpiricus, let's compare two model fits: the full model y ~ x * stimulus * lighting * colony (figure above) and the restricted model y ~ x * stimulus * lighting (figure below). The full model fits better statistically (in terms of an F-test). As it fits a regression line for each stimulus×lighting×colony combination, the full model interpolates well "unusual" points. I've highlighted one such point in each panel without testing formally that these points are outliers or high-leverage. The restricted model fits a line for the four stimulus×lighting combinations (four panels) and — within each panel — it uses the same line for the two colonies. Qualitatively, the fit is not bad and I can come up with a nice story that training is effective (the regression lines have positive slopes) under all conditions except for "dark and cold". Whether this story is meaningful depends on what the colonies actually are.

Here is R code to reproduce the figures and play with different models for this data.
library("broom")
library("tidyverse")

# Cast `colony` and `ID` as categorical (rather than numeric) variables.
df <- as_tibble(df) %>%
  mutate(
    colony = as.character(colony)
  )

outliers <- c(1, 6, 15, 40)

extract_model_formula <- function(model) {
  Reduce(paste, deparse(model$call$formula))
}

plot_model_fit <- function(model, title = "") {
  model %>%
    augment(
      newdata = df
    ) %>%
    ggplot(
      aes(x, .fitted)
    ) +
    geom_line(
      aes(color = colony)
    ) +
    geom_text(
      aes(x, y,
        color = colony,
        label = colony
      ),
      data = df,
      inherit.aes = FALSE
    ) +
    geom_label(
      aes(x, y,
        color = colony,
        label = colony
      ),
      data = df %>% filter(ID %in% outliers),
      inherit.aes = FALSE
    ) +
    facet_grid(
      stimulus ~ lighting
    ) +
    theme(
      plot.title = element_text(
        size = 12
      ),
      legend.position = "none"
    ) +
    ggtitle(
      title, extract_model_formula(model)
    )
}

m0 <- lm(
  y ~ x + x:stimulus + x:lighting + x:colony,
  # y ~ x + x:(stimulus + lighting + colony),
  data = df
)
plot_model_fit(
  m0,
  "Interactions without main effects is often not a great choice."
)

m1 <- lm(
  y ~ x * stimulus * lighting * colony,
  data = df
)
plot_model_fit(
  m1,
  "For each variable interacted with x, include its main effect as well."
)

m2 <- lm(
  y ~ x * stimulus * lighting,
  data = df
)
plot_model_fit(
  m2,
  "What is a colony and should it be included in the model? This is a domain knowledge question."
)

anova(m1, m2)
```

Comment: In the upper two panels the lines still do not match very well the (mini) clouds of points. It might be interesting to also cross the effects of stimulus and lightning. At this point the image will change when the scale on the x-axis is shifted and that might be considered as an undesirable feature (the slope of the lines is currently influenced by the center of the points).
Comment: Now that we know the colonies are honeybee colonies, it seems clear that there is need for more data points *both* from each colony (more than 5 bees per condition as the within-variability is high; otherwise individual points/bees can have a large effect on the regression as in the middle plot for y ~ x * stimulus * lighting * colony) and from more colonies (to understand what's really happening when it's "Cold").
Comment: Would you suggest to not do any significance testing? The visual explorative approach is probably better. The effects on the slopes seem very large but possibly not very significant. Or if significant, then there might by systematic effects that could have caused this (like little errors causing nonperfect randomisation in the experiment) there also not so many points.
Comment: @SextusEmpiricus Now that we have more information about the experimental design I'm not even sure that high-level interactions are the best approach. It seems the units were randomized to one of four conditions (stimulus-x-lighting), then given time to train under the assigned condition, then tested "officially". Seems the idea is to see if training is helpful and under which conditions but surely successes during training $x$ is not really a covariate if it happened after the randomization. Can a two-step procedure work?
Comment: The question is "whether the number of successes during memory has any relationship to the number of successes during the training". To test whether there is a statistical relationship is no problem (although more data would be needed to get a better idea about the relationship), but indeed, if there is any relationship, then this can be very well a non-causal relationship. So yes indeed, to test the effect of training, one should have made the training a controlled variable.
Comment: @SextusEmpiricus Thanks for your comments. You're right both about the model fit and the significance of the coefficients: visually/qualitatively, the fit is better with the saturated model (so I've updated the scatterplot) and most coefficients are not significant as the residual error is high: the only "significant" interaction is x-by-stimulus really.
Comment: I explained what a colony is in the main text of the question. Considering _"what if stimulus and lighting affect the number of trials but not the success rate of a trial?"_ this would be another question that I am interested in, but I need once check the success, then the failure and finally the overall trials for different questions.
Answer: We assume that the question is how to determine whether stimulus is statistically significant in the presence of the other variables. First let us try a mixed model with colony as a random effect.  Unfortunately, using the data in the question, this results in a singular model which can also be seen from the zero random effects.  This is suggestive of overfitting.
library(lmer)
fm1 <- lmer(y ~ x + stimulus + lighting + (1|colony), df)
## boundary (singular) fit: see help('isSingular')

ranef(fm1)
## $colony
##   (Intercept)
## 1           0
## 2           0

Thus we try a fixed effects model.  We can try interactions among all variables
fm2 <- lm(y ~ x * stimulus * lighting * colony, df)
summary(fm2)

giving:
Call:
lm(formula = y ~ x * stimulus * lighting * colony, data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-17.742  -3.199   0.721   4.297  14.172

Coefficients:
                                     Estimate Std. Error t value Pr(>|t|)
(Intercept)                           73.1768   101.9931   0.717   0.4800
x                                     -1.0131     1.2157  -0.833   0.4128
stimulusHeat                        -172.2299   111.4630  -1.545   0.1354
lightinglight                        -45.0352   117.2821  -0.384   0.7044
colony                               -46.2449    53.7372  -0.861   0.3980
x:stimulusHeat                         3.0552     1.3429   2.275   0.0321 *
x:lightinglight                        1.1976     1.3931   0.860   0.3985
stimulusHeat:lightinglight           132.2606   131.0734   1.009   0.3230
x:colony                               1.1097     0.6769   1.639   0.1142
stimulusHeat:colony                  117.2380    61.3083   1.912   0.0678 .
lightinglight:colony                  46.8192    64.6041   0.725   0.4756
x:stimulusHeat:lightinglight          -2.1497     1.5701  -1.369   0.1836
x:stimulusHeat:colony                 -2.1382     0.7744  -2.761   0.0109 *
x:lightinglight:colony                -1.1066     0.8541  -1.296   0.2074
stimulusHeat:lightinglight:colony    -87.6013    74.7980  -1.171   0.2530
x:stimulusHeat:lightinglight:colony    1.5915     0.9806   1.623   0.1176
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.473 on 24 degrees of freedom
Multiple R-squared:  0.767,     Adjusted R-squared:  0.6214
F-statistic: 5.268 on 15 and 24 DF,  p-value: 0.0001652

Looking at which coefficients are significant (marked to the right of the p values) it seems that we can simplify the model by omitting lighting.  Comparing that to the same model without stimulus we have a highly significant difference between the models with stimulus and without (p = 1.839e-05).
fm3 <- lm(y ~ x * stimulus * colony, df)
fm4 <- lm(y ~ x * colony, df)
anova(fm4, fm3)
## Analysis of Variance Table
##
## Model 1: y ~ x * colony
## Model 2: y ~ x * stimulus * colony
##   Res.Df    RSS Df Sum of Sq      F    Pr(>F)
## 1     36 6053.3
## 2     32 2651.9  4    3401.4 10.261 1.839e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here is a plot of x on horizontal axis vs y on vertical axis with separate panels for the colonies.  The colors represent the stimulus.
library(lattice)
xyplot(y ~ x | factor(colony), df, groups = stimulus,
  type = c("p", "r"), auto = TRUE)

Comment: @Sextus, It does not have to be that variances can model the situation. If not then  zero may be the most appropriate value for the random effects.  lmer does have the capability of inserting a different optimization routine if you want to try an alternative but usually it works well. Fixed effects are conditional on the independent variables  One does not necessarily have to model errors in them nor do we even know that is the case.
Comment: It makes no sense why `lmer(y ~ x + stimulus + lighting + (1|colony), df)` would fail, while the other more complex models don't. This seems to be more like a problem with the fitting of the mixed effects model.
Comment: A linear model approach and gazing at significant effects might be tricky here. The underlying model doesn't seem to be related, for instance, there will be measurement/sampling error in the values of $x$ as these are not controlled variables (least squares regression does not take this into account). In addition, the data is very sparse and significance might not be so important. The data is not good for hypothesis testing.


Integral of $b[x]^{l[x]} = p[x]$

Question: First year calculus student here - I am not sure where to turn for an answer despite searching and playing with Wolfram Alpha and Symbolab, and (forgive me) I do not know the technical vocabulary for what I am trying to do.
What is the equation which when differentiated with respect to x yields $b[x]^{l[x]} + C = p[x]$ ?  Note these names were chosen based upon the relationship $base^{logarithm} = power$ (where, to be clear, "power" is NOT the exponent: i.e. $$b^l=p $$ $$\equiv log_b[p] = l$$ $$\equiv \sqrt[l]{p} = b$$ .
Knowing the integrals of $a^x$ (constant a) and $x^n$ (constant n) has not proved helpful so far.
More generally, what would the process of finding this be called?  Is it in some sense an "inverse" of implicit differentiation?
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: Thanks Shaun, didn't even know the name for it.  All a part of learning the professional tools.
Answer: If I understand the question, then for a given $b(x),l(x)$ you are asking for a function $p(x)$ so that $p'(x)=b(x)^{l(x)}$
The answer is, we don't know such expressions in general, in fact, sometimes it is just "impossible" to find an expression for the integral of those functions, for example $e^{-x^2}$ (which is $b(x)^{l(x)}$ for $b(x)=e$ and $l(x)=-x^2$).
check out this question
Is there really no way to integrate $e^{-x^2}$?
Edit: maybe this is a better reference
https://en.wikipedia.org/wiki/Gaussian_function
or this
https://www.quora.com/How-do-I-calculate-indefinite-integral-of-e-x-2

Integral of $b[x]^{l[x]} = p[x]$


Python + sqlite3: executemany with "constructed" values

Question: I'm trying to use executemany in Python to populate some rows.
However, I'm getting:
sqlite3.OperationalError: 3 values for 4 columns

I understand that in general, you use executemany to stuff raw values into the DB as efficiently as possible, and with that in mind, you generally want the number of values inserted to match the number of columns.
But what if one or more of the columns are "constructed" via SQL, and do not have any corresponding input value?
Small example:
#!/usr/bin/env python2.7
import os
import sys
import sqlite3
from contextlib import closing

DB_FILE = 'test.sqlite'

with closing(sqlite3.connect(DB_FILE)) as db:

    # First, some setup...
    cursor = db.cursor()
    cursor.execute('CREATE TABLE test (id TEXT PRIMARY KEY, a TEXT, b TEXT, c TEXT)')

    sql = '''INSERT INTO test (id, a, b, c) VALUES (?, ?, ?, ?)'''

    data = []
    for i in range(5):
        idStr = str(i)
        data.append( (idStr, 'a{}'.format(i), 'b{}'.format(i), 'c{}'.format(i)) )

    cursor.executemany(sql, data)

    # Now, to exercise the problem:
    # This does an 'upsert', but the same problem could occur in
    # other circumstances.

    sql = '''
INSERT OR REPLACE INTO test (id, a, b, c)
VALUES (
    ?,
    (SELECT a,b FROM test WHERE id = ?),
    ?
)'''

    data = []
    for i in range(3,7):
        idStr = str(i)
        data.append( (idStr, idStr, 'c{}'.format(i)) )

    cursor.executemany(sql, data)

    db.commit()

When you run that, you get the error mentioned at the top (3 values for 4 columns).
I suppose I could work around this by breaking the SELECT a,b into separate SELECT a..., SELECT b... parts, but is there a better way?
The example given is small — in reality, it might be 10 columns that I'll now have to verbosely list with their own (SELECT ...) clauses.

UPDATE 1 This is not specific to executemany, as I had originally thought. Even running the plain SQL by hand has the same problem.
UPDATE 2 The answers below suggest using a SELECT rather than VALUES, however, this does no work when a new row is being added (as in my "upsert" case), since the SELECT returns no rows in that case.
Answer: You SQL requires 4 params into VALUES. The Problem is that SQLite is not able to return multiple values into a subquery, you will run into the following error:
sqlite3.OperationalError: only a single result allowed for a SELECT that is part of an expression
What you can do is to use 2 Select statements, one for each of the value you require. Here is what I tried:
sql = '''
INSERT OR REPLACE INTO test (id, a, b, c)
VALUES (
    ?,
    (SELECT a FROM test WHERE id = ?),
    (SELECT b FROM test WHERE id = ?),
    ?
)'''

There is also a more elegant solution for this.
sql = '''
INSERT OR REPLACE INTO test (id, a, b, c)
SELECT
    ?, a, b, ?
FROM test WHERE id = ?
'''

Here is a working example, i made some changes so the database table get populated accordingly:
#!/usr/bin/env python2.7
import os
import sys
import sqlite3
from contextlib import closing

DB_FILE = 'test.sqlite'

with closing(sqlite3.connect(DB_FILE)) as db:

    # First, some setup...
    cursor = db.cursor()
    cursor.execute('CREATE TABLE test (id TEXT PRIMARY KEY, a TEXT, b TEXT, c TEXT)')

    sql = '''INSERT INTO test (id, a, b, c) VALUES (?, ?, ?, ?)'''

    data = []
    for i in range(5):
        idStr = str(i)
        data.append( (idStr, 'a{}'.format(i), 'b{}'.format(i), 'c{}'.format(i)) )

    cursor.executemany(sql, data)

    sql = '''
    INSERT OR REPLACE INTO test (id, a, b, c)
    SELECT
        ?, a, b, ?
    FROM test WHERE id = ?
    '''

    data = []
    for i in range(4, 7):
        data.append((i, 'c{}'.format(i), i - 3))

    cursor.executemany(sql, data)

    db.commit()

Update 1
If you need Default values in case the select returns nothing you can use this:
sql = '''
INSERT OR REPLACE INTO test (id, a, b, c)
VALUES (
    ?,
    (SELECT ifnull((SELECT a FROM test WHERE id = ?), 'Default 1')),
    (SELECT ifnull((SELECT b FROM test WHERE id = ?), 'Default 2')),
    ?
)'''

data = []
for i in range(4, 10):
    data.append((i, i, i, 'c{}'.format(i)))

Comment: Hmm, after trying this more, I am having some trouble… the INSERT-OR-REPLACE is not doing the INSERT in the case where thd `id` does not match.  I wonder - why did you add `i-3` for the final data?
Comment: This is just to match some of the ids of the entries done with the first statement so the new entries are not getting null values on the *a* and *b* columns.
Comment: But if I *do* want NULLs in the a and b columns (or some other placeholder value), it is not achievable like this, right? I mean, that is not just putting some values in place, it's also the reason that the `INSERT` happens at all.
Comment: Using this will allow you to have inserts with null values where the select is not returning anything:
Comment: `
sql = '''
    INSERT OR REPLACE INTO test (id, a, b, c)
    VALUES (
        ?,
        (SELECT a FROM test WHERE id = ?),
        (SELECT b FROM test WHERE id = ?),
        ?
    )'''

    data = []
    for i in range(4, 10):
        data.append((i, i, i, 'c{}'.format(i)))
`
Comment: Exactly — this is the `VALUES` version that I was trying to avoid in the first place. See the "I suppose I could work around this …" bit in the original question.  It seems like maybe the ultimate answer is "No, there is not a better way."  Though I'd love to be proven wrong (:
Comment: I made an update in my original answer, so you can also set defaults. I don't think you will get around with this another way.
Answer: Yes! There is a better way!  Replace your VALUES clause with a SELECT statement!
The query will look like:
INSERT OR REPLACE INTO test (id, a, b, c)
    SELECT ?, a, b, ? FROM test WHERE id = ?

Remember to change your data list because the parameters are in a different order now.
Comment: Note: I removed parens around the SELECT since it seems to be invalid syntax.
Comment: It looks like this doesn't actually work, in the case where it is a new ID (the `INSERT` side of `INSERT OR REPLACE`. Is that right? If so, it doesn't work for my case.


How to randomly distribute a continuosly growing database?

Question: There is a set $T_k$ with a finite amount of elements. At a given time, I know only a subset $S_k$, where $n = |S_k|$, and $n < |T_k|$. Now, a new element $e \notin T_k$ is inserted into $T_k$ to form $T_{k+1} = T_k \cup \{e\}$. I now have to decide how to build  $S_{k+1}$ considering new element $e$. I may either:

Throw away $e$, and make $S_{k+1} = S_k$;
Decide to replace a random element $r \in S_k$ with $e$ in order to form $S_{k+1} = (S_k -\{r\}) \cup \{e\}$, so that $|S_{k+1}| = n$.

If I have the same probability of finding any element of $T_k$ in $S_k$, how can I decide how to build $S_{k+1}$, in order to maintain the same probability of finding any element of $T_{k+1}$ in $S_{k+1}$?
Background information: I am trying to devise a mechanism for distributing Bitcoin's blockchain among the running clients, instead of everyone having to hold a full copy of the database. A node must have the same probability of finding any given block stored locally, and at every new block a client must decide if it is going to be stored (replacing an old block) or not.
Answer: You want the probability of having stored any given element in $T_{k+1}$ to be $n/|T_{k+1}|$. That includes $e$! So with probability $n/|T_{k+1}|$, accept $e$; otherwise, throw it away.
Comment: Is it correct that I choose $r$ randomly, so that probability of finding any other elements is $n/|T_{k+1}|$, too?
Comment: Yes, that's right!