My site fails to show results in ie8 HTML Parsing Error KB927917

Question: The site loads fine in other browsers and IE versions but in IE8 i get this problem.
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)
Timestamp: Thu, 15 May 2014 11:48:37 UTC
Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917)
Line: 0
Char: 0
Code: 0
URI: http://jobuzu.co.uk/?q=sales+assistant&l=
Any idea how i can resolve this issue?
Also this happens on other computers with ie8....
function B(a) {
    return document.getElementById(a)
}

function cf(a) {
    var b = new Date;
    b.setYear(b.getFullYear() + 1);
    Ka("openSections", a, b)
}

function Ga(a) {
    var b = String(document.cookie),
        c = b.indexOf(a + "=");
    if (c == -1) {
        return "";
    }
    var d = b.indexOf(";", c);
    return b.substring(c + a.length + 1, d == -1 ? b.length : d)
}

function Ja(a) {
    return unescape(Ga(a))
}

function Ka(a, b, c) {
    document.cookie = a + "=" + escape(b) + "; path=/" + (c ? "; expires=" + c.toGMTString() : "")
}

function La(a, b) {
    document.cookie = a + "=;expires=" + (new Date(0)).toGMTString() + ";path=/" + (b ? ";domain=" + b : "")
};

function ya(a,b) {
    if (a) {
        return RegExp("(^|\\s)" + b + "(\\s|$)").test(a.className)
    }
}

function xa(a,b) {
    if (a && !ya(a,b)) {
        a.className ? a.className += " " + b : a.className = b
    }
}

window.showAllRefinements = function(a) {
  xa(B(a),"showAll")
}

window.toggleRefineBy = function(a) {
    if (ya(B(a),"rbOpen")) {
        var b = B(a);
        if (b) {
            b.className="rbSection";
        }
    } else if (b = B(a)) {
        b.className="rbSection rbOpen";
    }
    b = Ja("openSections");
    b.match(":" + a + "(:|$)") == m ? b += ":" + a : b = b.replace(":"+a,"");
    cf(b)
};

window.delSearchCookie = function(a, b) {
    a || (a = "RQ");
    $.removeCookie('csrf_token');
    /*
    La(a, b);
    */
    var c = B("recentsearches");
    c && c.parentNode.removeChild(c)
}

jquery.cookie.js:
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    function converted(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        try {
            return config.json ? JSON.parse(s) : s;
        } catch(er) {}
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
                config.raw ? key : encodeURIComponent(key),
                '=',
                config.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? undefined : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = converted(cookie);
                break;
            }

            if (!key) {
                result[name] = converted(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== undefined) {
            // Must not alter options, thus extending a fresh object...
            $.cookie(key, '', $.extend({}, options, { expires: -1 }));
            return true;
        }
        return false;
    };

}));

Comment: Could you post your code, in particular your JavaScript? Perhaps the issue is similar to here: http://stackoverflow.com/questions/8905476/html-parsing-error-in-ie8kb927917
Comment: Here is the main javascript code.
Answer: Try wrapping your code in a window.onload, like so:
window.onload = function() {

    //your code here

}

Alternatively, if you're using jQuery, you could try:
$(document).ready(function() {

    //your code here

}


Merge values into a while loop

Question: below I have values and below that I have a while loop with multiple values that are sorted by $top_list_friends['workouts'], with the highest number at top.
How can a merge the below values into one list?
 echo "
";
 echo "" . $my_rank . "";
 echo "" . $personal['name'] . "";
 echo "" . $personal['workouts'] . "";
 echo "
";

 $i = 0;
 while ($top_list_friends = mysql_fetch_array($query_top_list_friends)) {
 $i++;

 echo "
";
 echo "" . $i . "";
 echo "" . $top_list_friends['name'] . "";
 echo "" . $top_list_friends['workouts'] . "";
 echo "
";
 }

Comment: This library `mysql_` is old stuff. Update
Comment: you want to merge `$top_list_friends['name']` and `$top_list_friends['workouts']`  ?
Answer: Didn't understand question very well, but I would do it in this way:
    $name = $personal['name'];
    $workouts = $personal['workouts'];
    $html = <<<html

        $my_rank
        $name
        $workouts

html;

     $i=0;
     while ($top_list_friends = mysql_fetch_array($query_top_list_friends)) {
     $i++;
     $topName = top_list_friends['name'];
     $topW = $top_list_friends['workouts']
     $html += <<<html

         $i
         $topName
         $topW

html;
    }
    echo $html;

Answer: At the beginning:
$inserted=0;

into the loop:
if(!$inserted && $personal['workouts']> $top_list_friends['workouts'])}
     $inserted=0;
    //first div echoes

}

at the end
if(!$inserted){

  //the same echos

}

Merge values into a while loop


Why is $\phi(pq) \neq pq-4$?

Question: I currently am seeing that if $p$ and $q$ are primes, that $\phi(pq) = pq-4$ and am wondering what I am doing wrong. First, I see that if a number $d$ is greater than $1$ and divides $pq$, then it must be a multiple of either $p$ or $q$- because $pq=dk$ for some integer $k$, and the prime factorization for $pq$ and $dk$ must be equivalent, so at least one of $p$ or $q$ must be in the prime factorization for $d$. Then, I see that if $d=pl$ for some integer $l$, then $k$ must be $q$, because if $k$ isn't $q$, then $pq=kd=kpl$ implies $q=kl$, which is impossible as $q$ is prime. Therefore the only numbers which divide $pq$ are $p,q,pq,1$, so $\phi(pq) = pq-4$. What have I done wrong?
Comment: The definition of Euler totient function $\varphi(n)$ is not $n$ minus the number of divisors of $n$; if it were, the answer would indeed be $pq-4$.
Comment: It helps to look at a concrete case, like $p = 2$, $q = 5$. There are 10 numbers in the list $1, 2, 3, 4, 5, 6, 7, 8, 9, 10$. Some are counted by $\phi$ and some are not. It helps if you start by crossing out all the ones that are *not* counted by $\phi$ and see who  is left. You are right that 2, 5 and 10 should be kicked out. About 1 we can have a small discussion. But then there are others that also don't make the cut...
Answer: As commented, $pq$ takeaway the number of divisors of $pq$ is not the definition of $\phi(pq)$. We care about the number of integers between $1$ and $pq$ coprime to $pq$. It's a reasonable mistake to think this is just about divisors, but this is wrong. Let's take $p=3,q=5$. Now, $10$ does not divide $pq=15$ but it is not coprime to $15$ either; they share a common factor of $5$. Therefore we do not count $10$ in $\phi(15)$. So you need to include such cases in your calculation.
You should get $\phi(pq)=(p-1)(q-1)$.
Comment: In general if $p$ is a prime then $\phi(p) = p-1$
Answer: Being coprime to $pq$ is not the same as not being a divisor of $pq$.
It is true that if $m>1$ is coprime to $pq$, then $m$ cannot be a divisor of $pq$. However, $1$ is both coprime to and a divisor of $pq$. Also, the converse is not true. For $1 < n < q$, $pn$ is neither coprime to nor a divisor of $pq$. Likewise, for $1 < n < p$, $nq$ is again neither coprime to nor a divisor of $pq$.
So, the correct value of $\phi(pq)$ is not $pq-4$ but rather $pq-3-(p-2)-(q-2) = pq-3-p+2-q+2 = pq-p-q+1$.

Why is $\phi(pq) \neq pq-4$?


Importing and exporting to CSV

Question: Trying to import or export from MongoDB command line :
> mongoimport --db denistest --collection things --type csv --file C:/Users/Administrator/Desktop/csv_data.csv

I get :

JavaScript execution failed: SyntaxError: Unexpected identifier

What is wrong here?
Comment: What do a few lines of your CSV file look like?
Comment: "denis","omeri","21","Tirana","1","http:/google.com","m"
"olgert","llojko","20","Prrenjas","2","http:/facebook.com","m"
Comment: If you just try those lines, does it work? Did you happen to try this suggestion: http://stackoverflow.com/questions/4686500/how-to-use-mongoimport-to-import-csv
Comment: I made a new csv file with just those two lines and still not working.

Other commands (like show databases, use, find ect) are successfully executed.
Comment: Do you have a line with the field names?
Comment: I have tried it after adding column names in the first line of csv but still same problem. I thinks problem is in this line:

`> mongoimport --db denistest --collection things --type csv --file C:/Users/Administrator/Desktop/csv_data.csv`
Answer: I finally found the problem. I was executing my command in mongo.exe. ( I opened C:\mongodb\bin>mongo and the executed my command )
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.0
connecting to: test
>
> mongoimport --db denistestcsv --collection things --type csv --fields First,La
st,Visits,Location,Number,Url,Letter --file E:\temp\csv1.csv

But this is wrong. The correct way is going to mongo => bin => and then executing command without entering mongo.exe
C:\mongodb\bin>mongoimport --db denistestcsv --collection things --type csv --fi
elds First,Last,Visits,Location,Number,Url,Letter --file E:\temp\csv1.csv

Answer: Using your sample data, saved into a file called csv1.csv:
"denis","omeri","21","Tirana","1","http:/google.com","m"
"olgert","llojko","20","Prrenjas","2","http:/facebook.com","m"

I ran the following command line (split for readability here, with made-up field names):
mongoimport --db test
    --collection things
    --type csv
    --fields First,Last,Visits,Location,Number,Url,Letter
    --file d:\temp\csv1.csv

And it imports successfully:
connected to: 127.0.0.1
Thu Mar 28 07:43:53.902 imported 2 objects

And in the things DB:
> db.things.find()
{ "_id" : ObjectId("51543b09d39aaa258e7c12ee"),
     "First" : "denis", "Last" : "omeri", "Visits" : 21,
     "Location" : "Tirana",
     "Number" : 1, "Url" : "http:/google.com", "Letter" : "m" }
{ "_id" : ObjectId("51543b09d39aaa258e7c12ef"),
     "First" : "olgert", "Last" : "llojko", "Visits" : 20,
     "Location" : "Prrenjas",
     "Number" : 2, "Url" : "http:/facebook.com", "Letter" : "m" }

(I couldn't get the header row option working in 2.4 for CSV files for some reason, but the option of specifying the fields on the command-line works as well. You can also use a file that contains just the field names by using the fieldFile command line option)
Answer: Building off of Dennis Omeri's answer, I had a similar problem trying to make a remote connection to a mongolab MongoDB instance via the CLI. I had to run the command from the bin folder of MongoDB as well, but it's not as straightforward as his answer makes it seem.
In my case, I installed mongodb via homebrew on OSX (brew install mongodb assuming you have homebrew installed). That put my mongo system files in: /usr/local/cellar/mongodb/3.0.3/bin (sub in your version of mongo and the path should be good).
Then, locate the following items:

mongolab URL (should be something like ds123456-a.mongolab.com)
port number (probably 27799 or 2####)
database user (you will have to set this up in mongolab)
database password (set this up in mongolab as well)

You can then connect to mongolab using the following string
mongo ds123456.mongolab.com:27799/dbname -u dbuser -p dbpassword
Also note: in my case, I had setup mongolab via a Heroku add-on. This means you have to authenticate through the heroku dashboard to gain access to your mongolab db user/pw setup area. None of this is really documented anywhere I could find, so I'm adding this answer in to help the next soul who wanders into this mess.

Importing and exporting to CSV


JavaScript access elements from custom object

Question: This must be a very stupid question, but I just can't get it to work.
I'm creating my own UIKit for iOS. (Website-kit which will allow iPhone-like interfaces).
But, I'm trying to create a JavaScript library, which can be used to change several elements of the document. For instance, set a custom background colour when the document loads.
I'm trying to do that with object-orientated JavaScript. Like this:
var UI = new Interface();
UI.setBackground("#000");

How could I achieve this?
(So the custom "UI" Object, and (an example) on how to change the background color of the document, from INSIDE the object.)
Answer: You can save a reference to the DOM inside the JS object and rewrite it as needed.
function Interface() {
    this.setBackground = function (color) {
        this.pointTo.style.background = color;
    };
    this.pointTo = document.body;
}

You can initialize this by:
var UI = new Interface();
UI.pointTo = document.getElementById('some_id');
UI.setBackground("#000");
// Set another style, on a different element
UI.pointTo = document.getElementById('some_other_id');
UI.setBackground("#FFF");

This is a simple implementation and need to be allot smarter, but it should do the job.
Edit:
Made a mistake in original posting, and fixed erroneous code. Also made an example: http://jsfiddle.net/HpW3E/
Answer: Like silverstrike's code, but you can pass the target object in the interface constructor to don't get trouble in the future.
function Interface(target) {
    target = target || document.body;
    this.setBackground = function (color) {
        target.style.background = color || 'white';
    };
}

Ok now you can do this:
var UI = new Interface(document.body);
UI.setBackground("#000");

or even in somecases that you are applying the interface in global scope !ONLY!:
var UI = new Interface(this.body);
UI.setBackground("#000");

Also will work as this:
var UI = new Interface();
UI.setBackground("#000");

Answer: Here is a very simple approach
// define the object
var Interface = function () {

    var interface = document.getElementById("interface"); // just an example

    // your new methods
    this.setBackground = function (color) {
        interface.style.backgroundColor = color;
    }

    // rest of your code
}

now you can make use of it
var UI = new Interface();
UI.setBackground("#000");

Comment: I already tried something similair to that, but the problem is that the "document" object won't work inside a method...


How to begin reading about data mining?

Question: I'm a novice who is going to start reading about data mining. I have basic knowledge of AI and statistics. Since many say that machine learning also plays an important role in data mining, is it necessary to read about machine learning before I could go on with data mining?
Comment: [Data Mining: Concepts and Techniques](http://www.amazon.com/Data-Mining-Concepts-Techniques-Management/dp/0123814790) By Jiawei Han is a good start
Answer: Being somewhat in this position myself, I'll try to give some insight.
Firstly, download the Elements of Statistical Learning. It presumes calculus and linear algebra, and although it is very technical, it is also extremely well written.
Secondly (or firstly) look at Andrew Ng's tutorials on machine learning.
Thirdly, get some data, and start attempting to analyse data. You'll need to split into training and test sets, and then build models on the training set and test them against the test set.
I found the caret package for R very useful for all of this.
After that its practice, practice practice (like almost everything else).
Comment: you'll scare the poor man away forever!
Comment: Andew Ng's course will be 'offered free and online' to student's world wide during fall 2011 according to http://www.ml-class.org/
Answer: Introduction to Data Mining by Tan, Steinbech, Kumar is the best intro book out there
http://www.amazon.com/Introduction-Data-Mining-Pang-Ning-Tan/dp/0321321367
save EoSL for when you want to dig deeper. It's more of a reference.
Answer: Data mining can be descriptive or predictive.
On the one hand, if you are interested in descriptive data mining, then machine learning won't help.
On the other hand, if you are interested in predictive data mining, then machine learning will help you understand that you try to minimize the unknown risk (expectation of the loss function) when minimizing the empirical risk: you will keep in mind overfitting, generalization error and cross-validation. For instance, for a matter of consistency, the $k$-NN for a training sample of size $n$ should be such that:

$k$ goes to infinity when $n$ goes to infinity,
$\frac{k}{n}$ goes to 0  when $n$ goes to infinity.
Comment: It's worth noting that some authors like to make a distinction between DM and ML depending on the magnitude of $k/n$. I personally like Radford Neale's approach, in his course on [Statistical Methods for Machine Learning and Data Mining](http://www.utstat.utoronto.ca/~radford/sta414/): Many machine learning problems have a large number of variables, Data mining applications often involve very large numbers of cases.
Answer: I only add another very good source of tutorials on data mining/machine learning by Tom Mitchell.
He explains it very clearly and You can also download his presentations from his website (together with watching his lectures there).

How to begin reading about data mining?


Contagem de múltiplos de um inteiro está dando valores muito diferentes do esperado

Question: Ao receber dois números inteiros, tenho que mostrar quantos múltiplos o número n1 (digitado 3) tem até chegar ao n2 (digitado 44).
O resultado correto deveria ser:

O numero 3 tem 14 multiplos menores que 44.

O problema é que meu resultado está dando:

O numero 3 tem 6 multiplos menores que 44

Esse é o código:
n1 = int(input())
n2 = int(input())
soma = 0
count = -1
for c in range(n1, n2, 2):
  if c % 3 == 0:
    soma += c
    count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Imagino que seja isso que deseja:
n1 = int(input())
n2 = int(input())
count = 0
for c in range(n1, n2):
    if c % n1 == 0:
        count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Não entendi o que a soma faz aí, tirei. Não sei porque resolveu pular de 2 em 2. Pode ter algum motivo, pode ser que o enunciado esteja incompleto ou ambíguo. Eu entendi que o primeiro número digitado seria para indicar os múltiplos.
Eu interpretei que ele mesmo seria um último válido por isso comecei a contagem com 0, mas se realmente ele não deva ser contado deveria começar contar com -1, fui no mais lógico. parece que não pelo resultado que está esperando.
E o maior erro do código é que está usando o múltiplo fixo 3, que parece errado, pode ser até que seja o certo e não está claro, sendo o múltiplo do primeiro número digitado então é essa variável que deve usar como divisor.
Uma forma mais idiomática:
n1 = int(input())
n2 = int(input())
count = 0
for c in range(n1, n2, n1):
    count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

Answer: Uma solução alternativa para o problema seria criar uma lista numérica [n1, n2[ e filtrar seus valores deixando passar apenas os múltiplos de n1 e contar a quantidade desses valores aprovados.
Para filtrar uma lista usa-se a função builtin filter(function, iterable) que constrói um iterador a partir dos elementos de iterable para os quais function retorna True.
A função para filtro é uma função anônima criada com a palavra chave lambda:
#Se x for múltiplo de n1 retorna True
lambda x: x % n1 == 0

Para contar os elementos usa-se a função builtin len(s) que devolve o o número de itens de um objeto.
Para facilitar a montagem da string de saída foi usada fstring.
n1 = int(input("número a ser testado: "))
n2 = int(input("limite do teste: "))

count = len(list(filter(lambda x: x % n1 == 0, range(n1, n2))))

print(f'O numero {n1} tem {count} multiplos menores que {n2}.')

Teste no Repl.it: https://repl.it/repls/LumberingEvenDisassembler
Answer: Se a sequência começa com um número n1 e ela deve ter somente os múltiplos desse número, basta iterar de n1 em n1:
count = 0
for _ in range(n1, n2, n1):
    count += 1

O terceiro parâmetro de um range é o step. Se ele não é informado, o valor default é 1 (ou seja, os números da sequência avançam de 1 em 1). Mas eu posso usar qualquer outro número. Por exemplo, se n1 for igual a 3, a sequência começa no 3 e vai pulando de 3 em 3 (ou seja, ela será 3, 6, 9, etc...).

Aliás, é por isso que seu código não funcionou, pois você usou o step igual a 2, então estava gerando a sequência 3, 5, 7, 9, etc (deixando de fora vários múltiplos de 3, como o 6, 12, 18, etc).

E como a sequência começa em n1 e o step também é n1, então com certeza todos os números do range serão múltiplos de n1. Por isso eu nem preciso verificar o resto da divisão (e repare que no loop a variável é _, que é uma convenção do Python para indicar que não vou usar o valor da variável, já que o que importa é só contar a quantidade de elementos).
Mas como agora só precisamos saber a quantidade de números do range, nem precisa de loop, dá para obter isso diretamente com len:
count = len(range(n1, n2, n1))

Eu entendo que por ser um exercício, provavelmente "querem" que você itere de 1 em 1 e use o operador %. Mas para iterar pelos múltiplos de um número, não tem porquê fazer isso, já que você consegue gerar uma sequência que só tem os números que precisa.

Só lembrando que se n2 for múltiplo de n1, ele não é incluso na contagem. Por exemplo, se n1 for 3 e n2 for 9, o resultado será 2, pois só são considerados o 3 e o 6. Mas se quiser considerar também o 9, basta mudar para range(n1, n2 + 1, n1).

Se bem que também dá para resolver só com a boa e velha matemática. Basta dividir n2 por n1, e dependendo do caso, fazer os devidos ajustes.
Se a ideia é não contar n2, mesmo que ele seja múltiplo de n1 (ou seja, equivalente a range(n1, n2, n1)), basta arredondar o resultado da divisão para cima e subtrair 1:
from math import ceil
count = ceil(n2 / n1) - 1

Mas se a ideia é contar n2 caso ele seja múltiplo de n1 (ou seja, equivalente a range(n1, n2 + 1, n1)), basta fazer a divisão inteira, usando o operador //:
count = n2 // n1

Answer: Em Python, você pode solucionar o problema proposto sem qualquer tipo de loop, veja só:
n1 = int(input())
n2 = int(input())

count = len(range(n1, n2, n1))

print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

Veja funcionando no Repl.it
Answer: Pelo que percebi, você pretende contar a quantidade de múltiplos de um determinado valor que se encontra dentro de um range no qual o menor valor é n1 e o maior valor é n2.
Para resolver esta questão, você pode utilizar o seguinte algoritmo...
print('=' * 55)
print(f'\033[34m{f"Contador de Múltiplos":^55}\033[m')
print('=' * 55)

while True:
    try:
        n1 = int(input('Digite o limite inferior: '))
        break
    except:
        print('\033[31mValor INVÁLIDO! Digite apens números inteiros!\033[m')

while True:
    try:
        n2 = int(input('Digite o limite superior: '))
        break
    except:
        print('\033[31mValor INVÁLIDO! Digite apens números inteiros!\033[m')

cont = 0
for c in range(n1, n2 + 1, n1):
    cont += 1
print(f'\033[32mTemos {cont} múltiplos de {n1} no intervalo fechado [{n1}, {n2}]')

Veja aqui o funcionamento do algoritmo.
Observe que este algoritmo possui tratamento de erro e exceção para cada valor digitado.
Answer:     print('-=-'*20)
    print('Multiplos de 3.')
    print('-=-'*20)

    n1 = int(input())
    n2 = int(input())
    cont = 0
    for c in range(n1,n2):
        if c % n1 ==0:
            cont = + 1

   print(f'O numero {n1} tem {count} multiplos menores que {n2}')

Veja sim assim vc consegui resolver seu problema.


Debian apache2 not found

Question: I have a problem with installing apache2 on Debian. When I try to install I get
sudo apt-get install apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package apache2

This is my repo (/etc/apt/sources.list)
#deb http://debian.mirrors.ovh.net/debian/ wheezy main
deb-src http://debian.mirrors.ovh.net/debian/ wheezy main

#deb http://security.debian.org/ wheezy/updates main
deb-src http://security.debian.org/ wheezy/updates main
#deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main
deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main
#deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main
deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main
deb http://security.ubuntu.com/ubuntu maverick-security main restricted
deb-src http://security.ubuntu.com/ubuntu maverick-security main restricted
deb http://security.ubuntu.com/ubuntu maverick-security universe
deb-src http://security.ubuntu.com/ubuntu maverick-security universe
deb http://security.ubuntu.com/ubuntu maverick-security multiverse
deb-src http://security.ubuntu.com/ubuntu maverick-security multiverse

And when I try to type apt-cache search apache2 it return null(empty line)
Comment: You have an error in your search command. It should be: `apt-cache search apach2`. You might want to filter the results as well with: `apt-cache search apache2 | grep ^apache2` (useful when you are fairly certain that the package you are searching for will exist as it's own entry in the Debian repository.)
Answer: do this
sudo apt-get update

sudo apt-get install apache2

Answer: Remove the # character at the beginning of each line.
deb repo are for binary packages
deb-src repo are for source packages
Answer: As @nurza said, you have to enable binary repos, erase the "#" on lines that begins with #deb. Your first line on /etc/apt/sources.list should have:
deb http://debian.mirrors.ovh.net/debian/ wheezy main

Debian apache2 not found


OpenVPN , internet browsing using distant IP?

Question: I'm using OpenVPN to access one of our subsidiaries local apps and network..
i was wondering if it would be possible to browse internet using the distant network public ip ?
my computer (public ip : 126.96.36.199) , is connected thru openVPN to a network (public ip : 126.96.36.199)
I want my computer to browse internet with 220.127.116.11 as public ip address
Is it possible  ?
Thank you
Answer: It's possible, depending on your firewall and VPN setup.  What you want to do is called hairpinning.


Odoo POS receipt need to add address from res.partner city in receipt

Question: I don't know how to add res.partner object in below screen.js
print_xml: function() {
  var env = {
    widget: this,
    pos: this.pos,
    order: this.pos.get_order(),
    receipt: this.pos.get_order().export_for_printing(),
    paymentlines: this.pos.get_order().get_paymentlines()
  };
  render_receipt: function() {
    var order = this.pos.get_order();
    this.$('.pos-receipt-container').html(QWeb.render('PosTicket',{
      widget:this,
      order: order,
      partner:partner,
      receipt: order.export_for_printing(),
      orderlines: order.get_orderlines(),
      paymentlines: order.get_paymentlines(),
    }));
  };
};

I have tried to add the partner object in above javascript but it's not working.
I am new in odoo and i have also not munch knowledge of JavaScript so pls help me to solve this issue.
If i am able to add res.partner object in this javascript file then and then only i m available to access the res.partner objcet in my pos.xml file.
I wan't the address details of company and it's not in res_company so how can i fetch the street and other address from res_partner for company ?
Comment: @julivico yes i was try it but it's not working
Comment: Must you edit the javascript file to add  a address in receipt? Did you try with the Qweb template or Python part?
Answer: You can get it using get_client() method.
You will get full object of the partner of current order then you can use it as like a py file eg. partner.city etc. in the receipt template.
render_receipt: function() {
    var order = this.pos.get_order();
    this.$('.pos-receipt-container').html(QWeb.render('PosTicket',{
      widget:this,
      order: order,
      partner:this.pos.get_order().get_client(),
      receipt: order.export_for_printing(),
      orderlines: order.get_orderlines(),
      paymentlines: order.get_paymentlines(),
    }));
  };

Update:
To add address fields in res.company model in js.
var module = require('point_of_sale.models');
var models = module.PosModel.prototype.models;
for(var i=0; i<models.length; i++){
    var model=models[i];
    if(model.model === 'res.company'){
         model.fields.push('street');
         model.fields.push('city');
         model.fields.push('state_id');
         model.fields.push('country_id');

         // other field you want to pull from the res.company table.

    }
}

Then you will get it in the company:this.pos.company.
Now you can use it in template eg. company.street, company.city etc.
For country and state use company.state_id[1] and company.country_id[1] in template.
Comment: I updated my answer. you need to add address fields in to the models to access it in pos.
Comment: yes this is working for me but actually, i wan't the address details of company and it's not in res_company so how can i fetch the street and other address from res_partner for company ?
Comment: You mean you want address detail of company not partner?
Comment: yes i wan't the address  detail of company. i try to fetch the address using company object but it's doesn't contain address detail for company in res_company table.


Itô Integration by parts on a distribution for defaulted banks

Question: The question is based on the McKean-Vlasov problem formulated in the paper "A McKean-Vlasov equation with positive feedback and blow-ups", namely:
\begin{equation}
\begin{cases}
X_t = X_0 + B_t -\alpha L_t \\
\tau = \inf\{t\geq 0 : X_t\leq 0\} \\
L_t = \mathbb{P}(\tau\leq t)
\end{cases}
\end{equation}
which is in this case supposed to model the distance-to-default of a bank for constant $\alpha$. $\tau$ then is the stopping time for when the distance-to-default hits 0.
Now I'd like to introduce you to the actual problem:
Taking $\nu_t$ with $\nu_t(\phi):=\mathbb{E}[\phi(X_t)\mathbb{1}_{t<\tau}]$ for $\phi \in C^2$ and $\phi(0)=0$, $t\geq 0$. An application of Itô's formula is supposed to give
\begin{equation}
\begin{cases}
\nu_t(\phi)=\nu_0(\phi)+\frac{1}{2}\int_0^t\nu_s(\phi'')ds-\alpha\int_0^t\nu_s(\phi')dL_s\\
L_s = 1-\int_0^\infty\nu_s(dx)
\end{cases}
\end{equation}
I have two questions:
1) Since the dynamics of $X_t$ should be like "$dX_t=dB_t-\alpha dL_t$". I wonder where the $B_t$ dynamics went in the second part.
2) The authors of the paper proved that the density $V_t$ of $\nu_t$ exists and say that by integrating by parts in the above formula for $\nu_t$ one gets:
\begin{equation}
\partial_t V_t(x) = \frac{1}{2}\partial_{xx}V_t(x)+\alpha L'_t\partial_xV_t(x),\; L'_t=\frac{1}{2}\partial_xV_t(0)
\end{equation}
How does one integrate this by parts (I guess in the Itô kind of definition) to get the above equation?
Especially the second question is a concern of mine as I haven't dealt with such problems in a long time and although seeming kind of obvious I lack intuition and try to get it back solving and looking at solutions, respectively.
Thanks in advance for answers and I apologize if any insufficient specifications have been made.
Comment: Try expressing the product rule as a stochastic differential equation?
Comment: @nomen could you please specify?
Answer: So I've got an answer to the first question:
Applying Itô's formula to $\phi(X_t)$ one gets:
\begin{align*}
d\phi(X_t)\textbf{1}_{t<\tau}&=\frac{1}{2}\partial_{xx}\phi(X_t)\textbf{1}_{t<\tau}d\langle X\rangle_t +\partial_x\phi(X_t)\textbf{1}_{t<\tau}dX_t\\
&= \frac{1}{2}\partial_{xx}\phi(X_t)\textbf{1}_{t<\tau}d t + \partial_x\phi(X_t)\textbf{1}_{t<\tau}dB_t-\partial_x\phi(X_t)\textbf{1}_{t<\tau}\alpha dL_t
\end{align*}
Obtaining $\nu_t(\phi)$ by taking expectations, the stochastic integral w.r.t. $B_t$ vanishes as one can interchange the expectation and integrals (under certain circumstances which are fullfilled here) like:
\begin{align*}
\mathbb{E}[\int_0^t\partial_x\phi(X_s)\textbf{1}_{t<\tau}\alpha dL_s]=\int_0^t\mathbb{E}[\partial_x\phi(X_s)\textbf{1}]\alpha dL_s
\end{align*}
and the expected value of a stochastic integral w.r.t. Brownian motions is 0.


Unable to configure SMTP authentication support module

Question: In Drupal v7.36 & 7.37, after installed and enabled SMTP Authentication Support module, I still can't find the menu function under configuration/system to config this module for all related email setting.
Answer: Try to clear cache and go to the following path: admin/config/system/smtp or Home » Administration » Configuration » System » SMTP Authentication Support
Answer: Try clearing the cache either from the terminal using:

drush cc all

or from the UI, going to

Admin -> Configuration -> Development -> Performance

Clear the cache once and you would be able to see the Menu under configuration/system


IE7 getting null or object value in form

Question: I have a form with hidden fields with name.In javascript I am getting the form hidden value using following expression
document.getElementById('form-name').hidden-input-name.value.
In all browsers it is working fine except IE7.In IE7,I am getting value as null or not an object for the above expression.
Can anyone help me please.Thanks
Comment: What's the purpose of ".hidden-input-name" before .value? It should works without it, with a note: your element has id="form-name" not only name="form-name".
Comment: @MuhammadAlvin: He's probably using something like `...`.
Comment: @Zeta oh, i understand now. I think, adding id="something" in the  then retrieve its value by document.getElementById('something').value is easier. And i never encounter any problem personally.
Comment: @MuhammadAlvin:zeta is right.I have the form with hidden fields like that.It is alerting the message as document.getElementByid('form-name').hidden-input-name.value is null or object
Answer: Do you have any other element with attribute name = "form-name" because older versions of IE didn't distinguish b/w id="" and name=""
Comment: Thank you..It was issue of having the same form-name
Answer: The element name is not a valid JavaScript identifier, so you must use such syntax instead:
var value = document.getElementById('form-name').elements("hidden-input-name").value;

Answer: untested but how about trying:
document.getElementById('form-name')["hidden-input-name"].value


Calculating slope of a curve given table of points

Question: I'm trying to find out more about how to calculate the slope of a curve at a point given a table of points (e.g. temperature vs time or whatever it may be).
Mr Google is unfortunately defeating me.  I have found a vague one-liner answer on Quora (https://www.quora.com/How-can-the-slope-of-a-curve-at-a-given-point-be-calculated) that simply says:

If you have something like a table of points, then form the interpolation version and differentiate that.

Which I'm sure is detailed enough if you've got a mathematics degree, but what I really need is more of a layman's answer (preferably something I can do using R or another free tool .. although if its really easier in Mathematica or Matlab then I guess I'll have to consider my options).
My ultimate intended application is looking at slopes relative to another (e.g. differences in slopes of temperature vs time in one year/location/whatever vs another).  I'm sure this bit is easy once the initial stumbling block above is conquered !
Answer: It depends on
how noisy your data is
and whether you
want to interpolate or,
in some sense,
average.
If you data is
not noisy,
the easiest way is
to use the approximation
$f'(x)
=\dfrac{f(x+h)-f(x-h)}{2h}
$
which has an error
$O(h^2)$.
If your data is noisy,
you should probably use
least squares of some form.
Many years ago
(over forty),
I wrote a package
for doing adaptive least squares
cubic spline fitting,
and it proved quite useful.
I no longer have the source.
Answer: I guess you would need some of the "model" of your data point before continuing.  For example, if your data are linear, then you can use technique of linear regression to do so.
What I really mean is that, you need to have some "images" of what your data will be (e.g. quadratic polynomial? exponential?).  For polynomial of certain degree, there are still some tools for approximating with least square error.


DatePicker: combine quarterly picker with submit functionality

Question: How to combine a quarter datePicker
(see: SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters
jsfiddle: http://jsfiddle.net/4mwk0d5L/1/ )
with a submit functionality?
(like: SO: bootstrap-datepicker-how-to-send-value-to-url?)
I tried:
<code>$('#example1').datepicker({
    format: "MM yyyy",
    minViewMode: 1,
    autoclose: true,
    language: "qtrs",
    forceParse: false
}).on("show", function (event) {

    $(".month").each(function (index, element) {
        if (index > 3) $(element).hide();
    });
}).on('changeDate', function () {
    $(this).parent('form').submit();
});
</code>
but it does not seem to work.
Here is the jsFiddle I have used:
http://jsfiddle.net/a1t465c7/
Comment: Hi, content inside changeDate event is executed. I think submit instruction couldn't be ok.
Please, post html code too.
Comment: http://jsfiddle.net/a1t465c7/ added to question
Answer: Yes, It should work.
Content inside changeDate event is executed.
Try this:
<code>$('#example1').datepicker({
    format: "MM yyyy",
    minViewMode: 1,
    autoclose: true,
    language: "qtrs",
    forceParse: false
}).on("show", function (event) {

    $(".month").each(function (index, element) {
        if (index > 3) $(element).hide();
    });
}).on('changeDate', function () {
    alert('test');
});
</code>
See here: http://jsfiddle.net/76Lhvfy0/
May be a problem with the following instruction:
<code>$(this).parent('form').submit();
</code>


Qt - SLL error on Windows

Question: My app is throwing the following errors on windows:
QSslSocket: cannot call unresolved function SSLv3_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function ERR_error_string
I have already installed the VS C++ Redistributables and OpenSSL but I have no idea on how to tell Qt to link against openSSL dynamically.
I'm using the LGPL version of the Qt binaries and Qt Creator all on Windows 7 (the Linux build works just fine)
Answer: For some reason Qt wasn't dealing very well with the dlls downloaded from Win32 OpenSSL Installation Project. As I had observed that the application ran smoothly on machines with Tortoise Svn installed I just copied the dlls provided with Tortoise and this worked very well for me.
I know, it's weird that those dlls worked and those from the Win32 OpenSSL Installation Project didn't but for now copying the dlls from the Tortoise Svn installation folder solved my issue.
Comment: which are those DLL files or you just copy all of them?
Comment: Same problem for me. When I install Ruby22-x64 and Qt finds ssleay32.dll shipped with ruby, mine Qt application starts crashing.
Answer: Download the the latest OpenSSL pre-build binaries from this website.
I used Win32 OpenSSL v0.9.8r Light as there is some debate about the v1 release. [Client tools are fine you don't need the full distribution]
Make sure that you install the dlls so that they are visible in the windows path. Either;

the windows / system32 directory
the application directory
or add the location of the dlls to the path enviroment variable

This works for me with Qt v4.6.2
Comment: Copying system .dlls from 3rd party websites especially those involving secure communications IS NOT a very wise cyber practice.

Qt - SLL error on Windows


Is the set $C = \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4: x_1^2 + x_2^2 + x_3^2 < \ln(1+x_4^2)\}$ open or closed or neither?

Question: I'm using the following definition of closed and open sets:

Set $C \subset \mathbb{R}^n$ is open if $\forall x \in C\ \exists
   \varepsilon > 0: U_{\varepsilon}(x) \subset C$.
Set $C \subset \mathbb{R}^n$ is closed if it contains all its limit
points.

I don't have much idea of how to tackle this exercise. This is what I've done so far (almost nothing):
Let $x_4$ be fixed, such that $x_4 \ll 1$. Then we have that
$$0 < x_1^2 + x_2^2 + x_3^2 < \ln(1+x_4^2) \approx x_4^2$$
it follows that $\forall \varepsilon > 0: U_{\varepsilon}(x_4) \not\subset C$. So $C$ is not open.
I have the feeling that $C$ is not closed either, but I don't know how to prove that or show the opposite.
Comment: I disagree with this statement "it follows that $∀ε>0:U_ε(x_4)⊄C∀ε>0:U_ε(x_4)⊄C.$"  Regarding is C closed.... I say (0,0,0,0) is a limit point of C and it is not in C.  I will leave it to you to prove that statement.
Comment: Your inference that $C$ is not open from your statement$0 < x_1^2 + x_2^2 + x_3^2 < \ln(1+x_4^2) \approx x_4^2$ is wrong.  $C$ must be open as it is the inverse of an open set under a continuous mapping.
Comment: There's a typo at the 2nd bullet point.  Set $C$ is closed.
Comment: @GNUSupporter Ups! I fixed it (:
Answer: Hint: consider the function $f : \mathbb{R}^4 \to \mathbb{R}$ defined by:
$$
f(x_1, x_2, x_3, x_4) = \ln(1+x_4^2) - x_1^2 - x_2^2 - x_3^2.
$$
Show that $f$ is continuous and see what you can conclude about $C = f^{-1}[(0, \infty)]$.
Comment: @Surb I admit that this way is more elegant and time-saving than mine, so I upvoted.  Since this solution pops up while I was struggling with the set equalities, I kept on typing until the end.  IMHO, answers ([tag:general-topology]) problems can assume some basic well-known facts like the one you mentioned.
Answer: $C$ is open
First, make $x_4$ the subject of the inequality in the definition of $C$ (so as to make use of preimage).
\begin{array}{rrl}
& x_1^2 + x_2^2 + x_3^2 <& \ln(1+x_4^2) \\
\iff& \exp(x_1^2 + x_2^2 + x_3^2) <& 1+x_4^2 \\
\iff& \exp(x_1^2 + x_2^2 + x_3^2) - 1 <& x_4^2 \\
\iff& x_4 >& \sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1} \text{ or } \\
&x_4 <& -\sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1} \tag1\label1
\end{array}
Let $f_1:\Bbb R^3 \to \Bbb R$ be defined as $(x_1,x_2,x_3)\mapsto-\sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1}$ and
$f_2:\Bbb R^3 \to \Bbb R$ be defined as $(x_1,x_2,x_3)\mapsto\sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1}$.
They are well-defined since $x_1^2 + x_2^2 + x_3^2 \ge 0$, so $\exp(x_1^2 + x_2^2 + x_3^2) \ge 1$.  This allows us to take square root.
Next, observe that $f_1$ and $f_2$ are continuous on $\Bbb R^3$ since they're composition of elementary functions.
Rewrite the definition of $C$ using these two continuous functions to see the openness.
\begin{align}
C =& \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4 \mid x_1^2 + x_2^2 + x_3^2 < \ln(1+x_4^2)\} \\
\stackrel{\eqref{1}}=& \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4 \mid x_4 > \sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1} \text{ or } \\ & x_4 < -\sqrt{\exp(x_1^2 + x_2^2 + x_3^2) - 1}\} \\
=& \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4 \mid x_4 > f_2(x_1, x_2, x_3) \text{ or } x_4 < f_1(x_1, x_2, x_3)\} \\
=& \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4 \mid x_4 < f_1(x_1, x_2, x_3) \} \cup \{( x_1, x_2, x_3, x_4) \in \mathbb{R}^4 \mid x_4 > f_2(x_1, x_2, x_3) \} \\
=& \bigcup_{x_4 \in \Bbb R} \{( x_1, x_2, x_3) \in \mathbb{R}^3 \mid x_4 < f_1(x_1, x_2, x_3) \} \cup \{( x_1, x_2, x_3) \in \mathbb{R}^3 \mid x_4 > f_2(x_1, x_2, x_3) \} \\
=& \bigcup_{x_4 \in \Bbb R} f_1^{-1}((-\infty,x_4)) \cup f_2^{-1}((x_4,+\infty))
\end{align}
Since $f_1$ and $f_2$ are continuous, for each $x_4 \in \Bbb R$, the first and the second sets in the last equality are open.  Hence $C$ is open.
$C$ is not closed
Expand @DougM's idea.  Consider $c_n = (0,0,0,\frac1n) \in \Bbb R^4, n \in \Bbb N$.  The points $c_n$ are in $C$ since $0^2+0^2+0^2 = 0 < \ln\left(1+\frac{1}{n^2}\right)$.  $(c_n)$ converges to $(0,0,0,0)$ so $(0,0,0,0) \in \overline{C}$, but $(0,0,0,0) \notin C$ since $\ln(1+0^2) = 0$, so the strictly inequality in the definition of $C$ doesn't hold.


Multiple form submit

Question: I have a table of information displayed on a page. Each row of this table has its own submit button. I need to be able to pass information depending on what submit button is pressed.
The form is built like
function numberSubmit_form ($form, &$from_submit){
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

The rows of the table are built like:
$unvalRows[] = array(
            array('data' => '0'.substr($a[0], 2)),
            array('data' => drupal_render(drupal_get_form('numberSubmit_form'))),
        );

How am I able to determine which submit button has been used and pass the applicable phone number?
Answer: Add the phone number as an argument to numberSubmit_form and include it in your form array:
$unvalRows[] = array(
    array('data' => '0'.substr($a[0], 2)),
    array('data' => drupal_render(drupal_get_form('numberSubmit_form', $phone_number))),
);

Then in the form constructor:
function numberSubmit_form ($form, &$from_submit, $phone_number){
    $form['phone_number'] = array(
        '#type' => 'hidden',
        '#value' => $phone_number,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

It will then be available to you in the submit handler:
function numberSubmit_form_submit(&$form, &$form_state) {
    // do something with $form_state['values']['phone_number']
}

Comment: You are right, @dooffas's approach was wrong, as he wanted to get the submit button's data... But I think using radio buttons in a form would be even easier.
Comment: It is working fine. But i want to use '#ajax' instead of normal form submit. IF i have tried '#ajax', but it is not working.
Answer: Same answer as charlie except that #value didn't work for me; I had to put #default_value in the hidden field as follow:
$unvalRows[] = array(
    array('data' => '0'.substr($a[0], 2)),
    array('data' => drupal_render(drupal_get_form('numberSubmit_form', $phone_number))),
);

function numberSubmit_form ($form, &$from_submit, $phone_number){
    $form['phone_number'] = array(
        '#type' => 'hidden',
        '#default_value' => $phone_number,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function numberSubmit_form_submit(&$form, &$form_state) {
    // do something with $form_state['values']['phone_number']
}

Multiple form submit


Apache Solr integration on shared hosting with cpanel

Question: If I do not have any other access to my site's remote server other than file manager via CPanel, is there a way I can get Apache Solr up and running on my Drupal 7 site? The remote host does not provide me with shell access. Does anyone know a tutorial link for this?
Comment: Perhaps you could try [Lucene](http://drupal.org/project/luceneapi)? It doesn't require any shell access and is easy to set up.
Answer: No, in this case, you cannot do put Apache Solr on your server.  I just had a client who had the same problem. You have 2 options:

Setup a second server that has shell access, and will index you site for you
Use someone else's preconfigured Apache Solr already, such as Acquia Search (not free)
Comment: For #1: By *shell access* do you mean SSH? Does that mean I also need to buy another webhosting account as my *second server* instead of using my existing shared hosting account?
Comment: yes SSH.  Yes you'll need a second server,  or find someone that provides Apache Solr service.
Comment: www.opensolr.com is free
Answer: You can transfer your site to such hosting services, which offer Apache Solr Search together with Drupal like http://drupion.com
Answer: Another cheap option is Midwestern Mac's hosted search service (just to throw out another option): there are already many other people using it in tandem with shared hosting to help make search faster and better.
See http://hostedapachesolr.com/
(Disclaimer: I'm the owner of Midwestern Mac).
Answer: Do not get hosted on a cPanel server with SOLR. That is a bad idea.
Host your SOLR index(es) with a solr hosting provider that'll give you the solr hostname, port and path, and use it on your cPanel server using the php-solr-client if you're using php.
Such SOLR host would be: http://www.opensolr.com
Answer: Some shared hosting companies allow you to get access to shell, but you've to send them a special form (e.g. HeartInternet).
Alternatively may try to use PHP Shell (if it's allowed) to download solr sources and set-up on your user account. Which is downloading sources via curl and run java -jar start.jar from your solr example folder.
If this won't work (e.g. they don't have java), you have to either use temporary db search (Search API DB), set-up solr on external host or upgrade your hosting into VPS or dedicated one.
Answer: I'm afraid that you cannot install Apache Solr without shell access. You'll need a vps for this. I would recommend rosehosting. They offer free migration, so they will migrate your website and install Drupal and Solr on your vps.


Entity Framework doesn't get original entity when comparing changes

Question: I am working on History model where I get an entity, change it, then get the same entity again as original and compare it to record changes. But I end up with 0 changes and after some investigating, I have found that Entity Framework doesn't get the original entity. It gives me the same one. Here is my code.
Here I make changes
public async Task<bool> AssignUserAsync(string userId, int ticketId, string changesAuthor)
        {

            var ticket = await GetByIdAsync(ticketId);
            ticket.AssignedUserId = userId;
            ticket.Status = Status.Assigned;
            var result = await Update(ticket, changesAuthor);
            return result;
        }

Here I call the Update History method
 public async Task<bool> Update(Ticket ticket, string user)
            {
            if (ticket == null)
                //throw exception
                return false;

            var ticketChanges = GetTicketChanges(await GetByIdAsync(ticket.Id), ticket, user);

            await UpdateHistory(ticketChanges);
            ticket.DateUpdated = DateTimeOffset.Now;

            var result = await _ticketRepository.UpdateAsync(ticket);
            return result;
        }

This is my GetById
public async Task<Ticket> GetByIdAsync(int id)
    {
        return await _db.Tickets
            .Include(p => p.Project)
            .Include(t => t.Comments)
            .Include(p=>p.AssignedUser)
            .FirstOrDefaultAsync(p => p.Id == id);
    }

Here Original and ticket to compare are the same one. I checked the db and AssignedUserId was different.
  public List<History> GetTicketChanges(Ticket originalTicket, Ticket ticketToCompare, string changesAuthor)
        {
            List<History> ticketChanges = new();

            if (originalTicket == null || ticketToCompare == null)
                //throw exception
                return ticketChanges;

            var history = new History
            {
                DateCreated = DateTimeOffset.Now,
                User = changesAuthor,
                TicketId = ticketToCompare.Id
            };

I removed the long part where I compare the two entities.
What am I doing wrong, or how could I get the original?
Comment: You probably have some long-lived context instance under the hood. Impossible to tell from the code you show. In fact, it doesn't even show any EF code. If you call `GetByIdAsync` it won't overwrite a `Ticket` that's already tracked by the context. Besides, `GetTicketChanges` will never return changes, but you probably removed some code.
Comment: Can you please tell me what code you need to see to help me? The GetById is from my repository.
Comment: You could start by telling more about the type of application and the context's lifecycle.
Answer: This code won't work as you expect because by default the DbContext is tracking the initial instance which you are updating, so telling the DbContext to retrieve the instance again will return the same reference you just updated.
For example:
using (var context = new AppDbContext())
{
    var ticket1 = context.Tickets.Single(ticketId);
    var ticket2 = context.Tickets.Single(ticketId);
    Assert.AreSame(ticket1, ticket2); // NUnit ReferenceEquals
}

This would assert true as the DbContext would return the same reference. Editing ticket1 would result in the changes being seen on ticket2.
Alternatively:
using (var context = new AppDbContext())
{
    var ticket1 = context.Tickets.AsNoTracking().Single(ticketId);
    var ticket2 = context.Tickets.AsNoTracking().Single(ticketId);
    Assert.AreSame(ticket1, ticket2); // NUnit ReferenceEquals
}

This assert would fail as the instance returned would not be tracked so you would receive different instances.
Actions like tracking changes can be done fairly easily by overriding the DbContext OnSaveChanges method and using the ChangeTracker to inspect what entities of interest might have been updated, added, or deleted, then inspecting  their contents to build an audit record. This saves you the hassle of loading entities again to compare. However, the caveat of this approach is that it's only practical to record audit changes at a per-entity basis, not across a related graph of entities. What this means is that the change tracker for a ticket will let you record the deltas for changes made to the Ticket, but not inherently the child references of the ticket. (those would be tracked individually in the change tracker)
Your problem is compounded by the structure you are using, trying to isolate everything into reused methods. I had a stab at what minimal changes might be used to get it working, but honestly it ended up even more tangled as you would have to start detaching and re-attaching references. In general it is not a good idea to design around reloading multiple separate references to the same entity.   Working with detached entities would solve this issue, but I generally don't recommend that approach as it can lead to complexity trying to attach and detach entire object graphs. (entities and their related references) I would recommend looking at doing the change tracking from the DbContext, and allow it to resolve the current user from session state, (if a web app) otherwise the currently logged in user rather than passing variables through various method chains.
Comment: Thank you! It worked. :) I will have a read about tracking changes in the from DbContext.


Use bullets as navigation with Swipe JS

Question: I've been banging my head off a wall for a few hours and I'd really appreciate some help with this. I know it's going to be easy solution but so far it's not going well.
I'm using Swipe Js for a slider and I want to use some bullets as navigation (without the next and prev). I tried to use getPos() a built in swipe function but I keep getting a 'no method' error in my console.
Here's my HTML:

Here's my JS:
I've pulled it back to what's working. I just want to click on a dot and make it go to the corresponding slide.
   var slider = Swipe(document.getElementById('slider'), {
      auto: 6000,
      continuous: true,
      callback: function(pos) {

        var i = bullets.length;
        while (i--) {
          bullets[i].className = ' ';
        }
          bullets[pos].className = 'on';
      }

    });

  var bullets = document.getElementById('position').getElementsByTagName('li');

Any help is really appreciated
Link to my code http://codepen.io/veryrobert/pen/sHjwo
Link to the plugin https://github.com/bradbirdsall/Swipe
Answer: To make bullets clickable, you can use the plugin's pagination module and initialise it as follows:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

In this way, swiper takes care of creating the bullets inside the element that is given as a parameter and set clickable: true
Remember to include/import the paging module with Swiper or include/import the Swipern bundle for navigation to work:
From NPM:
// core version + pagination module:
import Swiper, { Pagination } from 'swiper';

// configure Swiper to use module
Swiper.use([Pagination]);

// init Swiper:
const swiper = new Swiper(...);

From CDN:

Answer: This should work:
$('li').on('click', function(event){
  event.preventDefault();
  var index = $("li").index(event.currentTarget);
  slider.slide(index);
});

Basically, you need to workout the index of corresponding li and pass that to swipes .slide method. This will then slide to the requested slide.
Hope that helps.
Comment: Good idea, find one that works best for you instead of hacking it. Happy to help. I've not really used many others as I really how swipe feels on a touch device. Good luck!
Comment: Perfect, thanks very much for the help. I really really appreciate it. Here's an updated pen if anyone else needs it. http://codepen.io/veryrobert/pen/sHjwo
Comment: One issue I just notice is that now the timer is messed up, would there be a way to reset it? or should I add this into the callback?
Comment: The 'auto' stops working after the user interacts with it. I can't find anything in the docs that mentions how to restart it I'm afraid.
Comment: No worries Gary, I think I might move away from swipe js in this particular case and use something that has the built in functionality I need. Really appreciate your time and help on this. Thanks again.

Use bullets as navigation with Swipe JS


When is $\int^1_0 f=\lim_{\epsilon\to 0} \int^1_{\epsilon} f$?

Question:
Let $f$ be a measurable function defined on $[0,1]$.
(a) Suppose $f$ is nonnegative, show that
$$\int_0^1 f=\lim _{\epsilon \rightarrow 0} \int_\epsilon^1 f .
$$
(b) Does the conclusion in part (a) still hold if the assumption that $f \geq 0$ is replaced by the assumption that $f$ is bounded?
(c) Does the conclusion in part (a) still hold if the assumption that $f \geq 0$ is replaced by the assumption that
$$
\lim _{\epsilon \rightarrow 0} \int_{\boldsymbol{\epsilon}}^1 f
$$
exists and is finite?

I want to know how to prove (a). I used $f_n=f\chi_{[\frac{1}{n}, 1]}$ and LMCT for part (a) and LBCT for part (b). But I cannot determine whether (c) is correct.
Comment: But there is no such thing called $f_n$ here in this question, and how should I notate $f$ if such $f_n$ is defined as yours?
Answer: (c) is essentially the statement "Every convergent series is absolutely convergent."  As hopefully we all learned in our intro calculus classes, this is false.  For instance, if $a_n = (-1)^n/n$, then $\sum_{n=1}^\infty a_n$ converges but $\sum_{n=1}^\infty |a_n|$ diverges.
To see how this connects to (c), fix any $a_n$ so that the series converges conditionally.  We need to turn the series into a integral, so we define $g(x) = a_{\lfloor x\rfloor}$ for $x\in [1,\infty)$.  The fact that the series converges conditionally becomes, in terms of $g$, the fact that $g$ is improperly Riemann integrable, but not Lebesgue integrable, on $[1,\infty)$.  (as mentioned in my hint in the comment, we could also use any such function in place of our $g$ here, so if you wanted it to be continuous, you can use $x \mapsto \sin(x)/x$ instead)
To change the domain from $[1,\infty)$ to $(0,1]$, we apply the substitution $u = 1/x$, giving us the fact that $f(x) = x^{-2}g(x^{-1})$ is improperly Riemann integrable, but not Lebesgue integrable, on $(0,1]$.
Therefore, under the assumptions of (c), we cannot conclude $\int_0^1 f = \lim_{\varepsilon \to 0^+} \int_\varepsilon^1 f.$


Mirroring partition table?

Question: I would like to mirror one drive's partition table, that is, have exactly the same partition on both sda and sdb. I have heard that one of the fdisk utilities can export a partition table into a file, and that file can be read back into another drive, but I can't seem to find this in the manuals.
Can someone help?
To summarize:
I want to have the exact same partitions on both drives, same labels, same filesystem types, and same sizes. The data on the drive does not matter, I just want the partition table.
Answer: sfdisk -d /dev/sda | sfdisk -f /dev/sdb

sfdisk -d dumps the partition table and throws it to stdout. This is being piped to sfdisk /dev/sdb with the --force, and so being written to /dev/sdb.
Comment: +1 For actually providing a - dangerous - solution :)
Comment: hmm. I think it's less dangerous dd'ing the MBR. :) I've used this method lots of times, just made one partition table, copied it and put everything into separate raid1's. :)
Answer: You can use dd to copy the Master Boot Record (MBR) from one device to another (or to a file). For example, copying the MBR from sda to sdb would be done with
dd if=/dev/sda of=/dev/sdb bs=512 count=1

The flags are

if, input file (either device or ordinary file)
of, output file (either device or ordinary file)
bs, block size in bytes
count, number of blocks to copy.

The MBR contains the partition table for the four primary partitions, so this solution alone will not copy the definition for the extended partitions.
Wikipedia has good articles describing master boot records and extended boot records, explaining their relation to each other and their disk format.
Note: This solution is possibly only valid for MS-DOS, Microsoft Windows and Linux on PC compatible systems.

Mirroring partition table?


Bounded holomorphic function on an unbounded region

Question: Let $\Omega\subset\mathbb C$ is an unbounded region, with boundary $\Gamma$. Let $f$ be a function holomorphic in $\Omega$ and continuous on $\Omega\cup\Gamma$. If $f$ is bounded on $\Omega\cup\Gamma$, show that $\forall z\in \Omega$, $|f(z)|\le\max_{w\in\Gamma}|f(w)|$.
This is from W. Rudin's Real and Complex Analysis. And there is a hint: show that without loss of generality, we can assume that $\Omega$ doesn't intersect the (open) unit disk.
Under this assumption, I can complete the proof using maximum modulus principle.
My question is: why can we assume it? If $\mathbb C\setminus\Omega$ has non-empty interior, I can see it is valid. Can anyone give some advice?
Answer: Suppose that the interior of $\mathbb C\setminus\Omega$ is empty. This means that for any $z\in\mathbb C\setminus\Omega$ and any $\varepsilon$, one can find $z'=z'(\varepsilon)\in \Omega$ such that $|z-z'|\lt\delta$. In other words, $\Omega$ is dense in $\mathbb C$. In this case, $\Omega\cup\Gamma$ is the whole complex plane, and by Liouville's theorem, the assumption that $f$ is bounded on this sets implies that $f$ is constant.
Comment: That's not correct, [cf here](http://math.stackexchange.com/a/1261260). $f$ need not be entire if it is holomorphic in $\Omega$ and continuous on $\overline{\Omega} = \mathbb{C}$.
Comment: @DanielFischer Indeed. And unfortunately, I don't see a way to salvage my attempt.


Angular 11 Firebase Server-side rendering infinite loading / pending

Question: I have an angular 11 app that works great normally, i.e. in non-SSR mode.
Here is a sample querying a collection of documents, of type T (get once, not observing the changes).
Version that works in non-SSR, the expected code to query the collection once:
this.firestore.collection<T>('collection', ref => ref.limit(5))
    .get()
    .pipe(
      map((qs: firebase.firestore.QuerySnapshot) => qs.empty ? [] : qs.docs.map(d => d.data() as T)),
    );

When switching to SSR, the above code leads to the express server hanging, and the client see a 'pending' query that never completes, or hits a timeout and leaves the page partially rendered (i.e. without the results of that query).
I am using Angular 11 with Ivy.
The relevant entries in my package.json:
{
  "dependencies": {
    "@angular/cdk": "^11.0.3",
    "@angular/common": "~11.0.5",
    "@angular/compiler": "~11.0.5",
    "@angular/core": "~11.0.5",
    "@angular/fire": "6.1.4",
    "@angular/flex-layout": "^11.0.0-beta.33",
    "@angular/forms": "~11.0.5",
    "@angular/material": "^11.0.3",
    "@angular/platform-browser": "~11.0.5",
    "@angular/platform-browser-dynamic": "~11.0.5",
    "@angular/platform-server": "~11.0.5",
    "@angular/router": "~11.0.5",
    "@nguniversal/express-engine": "^11.0.1",
    "bootstrap": "^4.5.2",
    "express": "^4.17.1",
    "firebase": "^8.2.1",
    "rxjs": "~6.6.3",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^11.0.0-beta.4",
    "@angular-devkit/architect": "~0.1100.5",
    "@angular-devkit/build-angular": "~0.1100.5",
    "@angular/cli": "~11.0.5",
    "@angular/compiler-cli": "~11.0.5",
    "@nguniversal/builders": "^11.0.1",
    "@ngx-builders/analyze": "^2.0.0",
    "@types/express": "^4.17.0",
    "@types/node": "^12.11.1",
    "bufferutil": "^4.0.2",
    "firebase-tools": "^9.0.1",
    "ts-node": "~9.1.1",
    "typescript": "~4.0.5",
    "utf-8-validate": "^5.0.3",
    "ws": "^7.4.1",
    "xhr2": "^0.2.0"
  }
}

In angular.json, in the server.options field, I had to add the following to mitigate the following error ENOENT: no such file or directory, open '.../dist/server/src/protos/google/firestore/v1/firestore.proto'
externalDependencies: [
              "@firebase/analytics",
              "@firebase/analytics-types",
              "@firebase/app",
              "@firebase/app-types",
              "@firebase/auth",
              "@firebase/auth-interop-types",
              "@firebase/auth-types",
              "@firebase/component",
              "@firebase/database",
              "@firebase/database-types",
              "@firebase/firestore",
              "@firebase/firestore-types",
              "@firebase/functions",
              "@firebase/functions-types",
              "@firebase/installations",
              "@firebase/installations-types",
              "@firebase/logger",
              "@firebase/messaging",
              "@firebase/messaging-types",
              "@firebase/performance",
              "@firebase/performance-types",
              "@firebase/polyfill",
              "@firebase/remote-config",
              "@firebase/remote-config-types",
              "@firebase/storage",
              "@firebase/storage-types",
              "@firebase/util",
              "@firebase/webchannel-wrapper"]

Answer: After a very long debugging session, I narrowed down source of the problem to Firebase query listed in the question. The following query is a workaround that gets the page rendered, without hanging.
this.firestore.collection<T>('collection', ref => ref.limit(5))
    .valueChanges()   <<<<
    .pipe(
      take(2),        <<<<
    );

One aspect that made it hard to debug was because the more sane version here below, which closes the source observable causes the server to also hang (Remember, I do not want to observe the changes, so take(1) is what makes sense). Take(2) however, does not hang... This looks like a bug somewhere in the stack, likely in Firebase.
This would be the more sane workaround... but causes the express server to hang, leaving the client with a pending request:
this.firestore.collection<T>('collection', ref => ref.limit(5))
    .valueChanges()
    .pipe(
      take(1),      <<<<
    );

Using promises also causes hanging, so I'm currently left with the valueChanges()+take(2) workaround.
Comment: It took a long time, but this fixed it for me! So difficult to find that take(1) was the issue.


Rails 3.2 Obj.try() failing

Question: I just upgraded from Rails 3.1.0 to 3.2.3.  Once I got my gem dependency issues cleared up I managed to run tests and I discovered this:
1.9.2p180 :005 > Rails.version
 => "3.2.3"
1.9.2p180 :006 > a = 'test'
 => "test"
1.9.2p180 :007 > a.try(:banana)
NoMethodError: undefined method `banana' for "test":String
    from /Users/jamesthullbery/.rvm/gems/ruby-1.9.2-p180@app_tier/gems/activesupport-3.2.3/lib    /active_support/core_ext/object/try.rb:32:in `try'
    from (irb):7
    from /Users/jamesthullbery/.rvm/gems/ruby-1.9.2-p180@app_tier/gems/railties-3.2.3/lib/rails    /commands/console.rb:47:in `start'
    from /Users/jamesthullbery/.rvm/gems/ruby-1.9.2-p180@app_tier/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
    from /Users/jamesthullbery/.rvm/gems/ruby-1.9.2-p180@app_tier/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `'
1.9.2p180 :008 >

When I perform the same command on Rails 3.1.0 I get no issues:
1.9.2p180 :004 >   Rails.version
 => "3.1.0"
1.9.2p180 :005 > a = 'test'
 => "test"
1.9.2p180 :006 > a.try(:banana)
 => nil
1.9.2p180 :007 >

Has anyone seen this issue?  Certainly there is something wrong with my environment and not the Rails framework.  It seems to be pretty difficult to accurately search for the method try, so I haven't found anything online yet.  Is anyone else seeing this?  Thanks!
Comment: some one already posted this.
http://stackoverflow.com/questions/8697235/rails-3-objecttry-not-working
Answer: Object#try is supposed to deal with nil receivers. It should not be used to avoid NoMethodError exceptions.
The behavior you saw in 3.1.0 was a bug and it was "fixed" 7 months ago (as of this writing).
Comment: Thank you so much!  I was just diving into the source code and found myself on that commit you linked too.  Suppose it pays to stay on top of the Rails updates, would have caught this much sooner.

Rails 3.2 Obj.try() failing


Serving Changes in Table Tennis

Question: In table tennis, the serve changes after every 5 serves. But I don't understand that rule.
If A wins a rally, A get 1 point. After that, if B wins a rally, B get 1 point. Now, who should do the next serving, A or B?
I don't understand what "after every 5 serves" means.
Answer: First of all, your statement of the rule is not correct. From Pongworld (emphasis added):

After each 2 points have been scored the receiving player or pair shall become the serving player or pair and so on until the end of the game, unless both players or pairs score 10 points or the expedite system is in operation, when the sequences of serving and receiving shall be the same but each player shall serve for only 1 point in turn.

This is a very different specification from even "every two serves", much less from "every five serves ".
A serve which leads to a rally in which no point is scored (i.e. a let) would not be counted under the official rules, while it would be counted under your specification.
Quite simply, the winner of the point and the number of serves made are both irrelevant. It is the number of points won since service last changed (or when serving first, since the match started) which matters. Whether it was A twice, B twice, each once or that there were fifty lets in between, the serve won't change until two points are scored.
This makes it easy to determine when service will change. Simply add the scores of both players. If the total is odd, the same player serves again. If it is even, the other player serves the next rally.
The exception is during expedited serve, where service changes after every point.
Comment: I'm sorry. I am using and asking about the old system.
Comment: @BillyHalim According to the ITTF history, it was never "after five serves" - the limiting factor has always been points, and changed from five to two, over fifteen years ago.
Comment: But I'm still confused with the rule. If A got 0 and B got 2. Who will be the next server ?
Comment: Whoever was not serving already. That's what "the receiv[er] shall become the serv[er]" means...
Comment: So if A is the first server and now he get 2 points (B get 0 point). So the next server is B ? And the serve is not depend on the "who wins the rally" right ?
Comment: In Badminton, if you win a rally repeatedly, you can continue to serve and serve. In table tennis, it depends on the 2 points score right ?
Comment: Correct. It doesn't matter who scored the points, as long as there have been two points won altogether.
Comment: How about in double team ? If there are 2 points difference between each team, the serve changes to my partner or my opponents ?
Comment: "The receiver becomes the server". Your partner cannot have been the receiver, so they cannot serve next.
Comment: So how could my partner have a chance to serve ? Are there any rules or we decide who do the serving ?
Comment: @BillyHalim that would be a different question. You could ask it and I or someone else might answer.
Answer: The confusion is because of rule changes introduced after the 2000 Sydney olympics. The serve now changes after 2 points. Previously the served changed after 5 points. Also, a game is now first to 11 points not 21.
Comment: Welcome to Sports SE, please reference your answer to the direct source.

Serving Changes in Table Tennis


Place a Page before Context Blocks

Question: I want to achieve this result in my Drupal front page:
<code>[Headers]
[Welcome Block]
[View of contents]
</code>
So I created a Welcome Page (as a Basic Page), and put it as a Front Page from site configuration.
Then I add the view by the context module.
The problem is that the welcome page appears after the view, at the bottom of the page:
<code>[Headers]
[SECTION Content]
  [View of contents] (view, added with context)
  [Welcome]          (Basic Page with path /welcome)
[/SECTION Content]
</code>
A possible solution is to make a Block instead of a page, but I would have no more welcome/ path where to link the front. I want also to use a page so that editors can edit, update and translate that when needed. With blocks I should add higher permissions. My purpose is just to show the welcome basic page before the view of contents.
Answer: You can use panel page for this.
Create a panel, set it is as front page and pull the things you want to pull like blocks, views, nodes etc.
Comment: Thank you @Stephen.R, I prefer not to use panels since they add too many degrees of freedom, and stick to Context + Views. Of course this solution is good, and Panels are ultra-widely used. But my purpose (in case that'd be possible) is _just_ to display my basic page on the top of other content added with context.

In this case I want to use a page so that editors can edit that. With blocks I should add higher permissions.

Place a Page before Context Blocks


Bounds of rotated egg?

Question: I'm attempting to find the bounding box for a rotated egg shape without resorting to interpolation if at all possible.  In researching this I've come across this link which lists useful equations for plotting the $(x, y)$ coordinates of an egg shape as:
\begin{align*}
  x &= \frac{r((c-2) \cos \theta + c + 2)(\cos \theta + 1)}{4}, \\
  y &= r \cdot \sin \theta.
\end{align*}
But if I were to normalize it to the centerpoint of the circular area—$(0, 1)$ in the image below, then rotate it by some arbitrary angle about that new centerpoint—how can the $x$ and $y$ bounds be found without interpolation?
Answer: Instead of rotating your egg I'd prefer to rotate the bounding box. I hope you are able to translate between these views. Suppose $(a,b)$ is one direction of the box. Then in order to find the points where the curve is maximal or minimal with respect to that direction, you need to find the points where the tangent of the curve is orthogonal to that direction. Orthogonal means dot product is zero, and the tangent direction is the direction of derivatives. So let's start by computing some derivatives (for which I used Sage):
\begin{align*}
\frac{\mathrm d\,x}{\mathrm d\theta}&=
\frac12r\sin\theta\bigl((2-c)\cos\theta-c\bigr) &
\frac{\mathrm d\,y}{\mathrm d\theta}&=
r\cos\theta
\end{align*}
Now set the dot product equal to zero:
\begin{align*}
0&\overset!=\left\langle\begin{pmatrix}a\\b\end{pmatrix},
\begin{pmatrix}\frac{\mathrm d\,x}{\mathrm d\theta}\\
\frac{\mathrm d\,y}{\mathrm d\theta}\end{pmatrix}\right\rangle=
\frac12ar\sin\theta\bigl((2-c)\cos\theta-c\bigr)+br\cos\theta\\
0&\overset!=a\sin\theta\bigl((2-c)\cos\theta-c\bigr)+2b\cos\theta
\end{align*}
Now dealing with trigonometric functions here may make things a bit hard, so I'd use the tangent half-angle substitution here:
$$t:=\tan\frac\theta2\qquad
\sin\theta=\frac{2t}{1+t^2}\qquad
\cos\theta=\frac{1-t^2}{1+t^2}$$
Using this you can write
\begin{align*}
0&\overset!=a\frac{2t}{1+t^2}\bigl((2-c)\frac{1-t^2}{1+t^2}-c\bigr)+2b\frac{1-t^2}{1+t^2}\\
0&\overset!=at\bigl((2-c)(1-t^2)-c(1+t^2)\bigr)+b(1-t^2)(1+t^2)\\
0&\overset!=bt^4+2at^3+2a(c-1)t-b
\end{align*}
This is a quartic (i.e. 4th degree) polynomial equation in $t$. Solving those is not beautiful, but you can solve this using radical expressions, without interpolation or resorting to numerical methods. I would expect two real solutions, one corresponding to each boundary. Turn the values $t$ you get back into $\theta$ (or compute $\sin\theta$ and $\cos\theta$ directly from $t$ to avoid the trigonometry) then plug this back into the original formula to obtain the extremal points. Do the same in the orthogonal direction $(-b,a)$ and you have all four points defining your bounding box. Rotate that if you want it aligned with your axes.
Note that the tangent half-angle substitution has a blind spot: $\theta=\pm\pi$ corresponds to $t\to\infty$. So if your direction is not rotated, and you are looking for vertical tangents, be sure to cover that case separately.
Below is a snapshot of one instance of this problem.
See this blog page for an interactive version with some additional text.
Comment: @CoryG: I created an interactive version for you and other readers. Applying the transformation you applied to the egg to these extremal points as well shouldn't be too hard. Note that only the direction of $(a,b)$ is important, so you might pick $a=\cos\varphi,b=\sin\varphi$ where $\varphi$ depends on the rotation of the egg. I'm not sure what expansion and compression you are talking about.
Comment: I voted this up for now but it might take some time to accept.  I want to translate it into the minX, minY, maxX, maxY equations needed to make sure it works first and math isn't my strongest suite so it might take some time.
Comment: As a follow-up, would you be able to give these in the form of the min/max equations, or the equations for the angles of the egg?  I'm having serious issues translating these into the required form even with Mathematica.
Comment: I went ahead and marked this as correct, though the equations I'm using now are substantially more complex due to factors for compression and expansion on independent a and b axis as well as rotational normalization for the result of the independent a and b radius+expansion+compression - interpolation is probably how I need to go about it now.

Bounds of rotated egg?


Show the fibers are geometrically connected

Question: This exercise is the 5.3.9 of Liu's famous book about algebraic geometry.
Let Y be a normal, locally Noetherian, integral scheme, and let $f : X \mapsto Y$
be a projective dominant morphism with $X$ integral.
(a) Let us suppose $f$ is finite. Show that $f$ is purely inseparable if and
only if the extension $K(Y ) \mapsto K(X)$ is purely inseparable. Moreover,
if $f$ is purely inseparable, it will be a homeomorphism.
(b) Let us suppose that the algebraic closure of $K(Y )$ in $K(X)$ is purely
inseparable over $K(Y )$. Show that the fibers of $X \mapsto Y$ are geomet-
rically connected.

The answer of (a) is Ok. I'm looking for (b). Here is what I've done :
It's enough to check that $\mathcal{O}_{Y} \mapsto f_{*}\mathcal{O}_{X}$ is an isomorphism by the Corollary $3.17.$ page $201$. We can suppose $X = Spec(A), Y = Spec(B)$ affine with $A, B$ integral noetherian and $B$ integrally closed and $f$ is defined by a morphism of ring $\phi : B \mapsto A$. It's enough to see $\phi$ is an isomorphism. We know it's injective by dominance. Since the morphism is projectif (hence proper) the elements of $A$ are integral over $B$ (Proposition $3.18.$ page $105$) so they are in the algebraic closure of $K(Y)$ in $K(X)$. By hypothesis, we can show their minimal polynom are of the form $X^{p^{d}} - b$ with $b \in B$.
Here, I don't know what to do. If b would have a $p-$root, I could conclude but I have any hypothesis on the field $K(X)$.
I precise the link given above only answer to (a) and not to (b) (the question I'm looking for). Is their a possibility to re open the conversation to accept answer?
Comment: If you want a proof of (a) or a details about $X^{p^{d}} - b$ tell me...
Comment: Please use Mathjax for your whole post… I'm not sure how you can assume that $X$ and $Y$ are affine in (b), unless you keep the assumption that $f$ is finite.
Comment: 1. Please look around MSE to see if your question has been answered before *prior to posting*. 2. Please use MathJax for all of your post, including the statement of the problem. 3. Your reduction is not correct - it will not always be the case that $\mathcal{O}_Y\to f_*\mathcal{O}_X$ is an isomorphism (consider Spec of any purely inseparable field extension, for instance).
Comment: Hello KReiser, thank you for your answer. I already looked and I don't find satisfying things and I find your link. The link only answer to (a).
Comment: I'm going to edit the first line with MathJax, sorry.
Comment: For 3. you're right. Do you have ideas or a reference?
Comment: Could someone explain me how the folowing link https://math.stackexchange.com/questions/3293355/purely-inseparable-morphism-of-schemes-ex-from-lius-ag-ac help me with (b)?
Comment: @Analyse300 Sorry for missing your previous comment, I did not get a notification. In the future, an [@-reply](https://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) may be useful. I'll write you an answer soon.
Answer: We'll first reduce to the case when $X\to Y$ is finite: by Stein factorization, we may write $f:X\to Y$ as $X\stackrel{g}{\to} Y'\stackrel{h}{\to} Y$ where $g$ is projective with $g_*\mathcal{O}_X \cong \mathcal{O}_{Y'}$ (and thus geometrically connected fibers) and $h:Y'\to Y$ is finite. If we can show the fibers of $h$ are singletons, we'll have demonstrated the claim.
Now consider the fields $K(Y)$, $K(Y')$, $K(X)$, and $K(Y)^{alg}$, the algebraic closure of $K(Y)$ in $K(X)$. We know that $K(Y)\subset K(Y')\subset K(X)$ from the sequence of dominant morphisms $X\to Y'\to Y$, and we know that $K(Y)\subset K(Y')$ is a finite extension of fields, so we have that $K(Y')\subset K(Y)^{alg}$, too. Since every subextension of a purely inseparable extension is purely inseparable, this means $K(Y)\subset K(Y')$ is a purely inseparable field extension, so now we apply (a) and we're done.
Comment: Thank you very much KReiser, it works. I'll use $@-reply next time (I didn't knew this tool). Thanks again.


Is there a way to strip identifying data from commerce tables?

Question: I am interested in stripping personal addresses out of the  commerce_customer_profile and commerce_customer_profile_revisions database tables to sanitize the database for development purposes.
The site is using Drupal 7 and Drupal Commerce 7.x-1.13.
Has anyone come up with a way to do this?
Answer: There's nothing special about sanitizing Commerce.  When I sanitize the db, I simply delete all the info in SQL:
TRUNCATE TABLE commerce_customer_profile;
TRUNCATE TABLE commerce_customer_profile_revision;
TRUNCATE TABLE field_data_commerce_customer_address;
TRUNCATE TABLE field_revision_commerce_customer_address;
TRUNCATE TABLE field_data_commerce_customer_billing;
TRUNCATE TABLE field_revision_commerce_customer_billing;

NOTE: This is just an example.  You need to check your database and make sure you get all the relevant tables.
If you want to use dummy data instead of deleting the data outright, you can use a statement like this:
UPDATE users SET users.name = users.uid WHERE users.uid > 0;

If you don't have a tool like PhpMyAdmin for accessing your database easily, I would use Sequel Pro on macOS or MySQL Workbench on Windows/Linux.
Drush has a sql-sanitize command but I have encountered several issues with it over the years.  I don't want to risk accidentally exposing anything before handing off a db to another developer, so I check the db anyway; in that case, there's no real speed advantage to using Drush vs. running the SQL myself and since I'm checking it with my own eyes I can be confident the job got done.
Comment: Thanks for taking time to answer my question, Patrick.  I had hoped to replace the existing addresses with something anonymous like you suggest for the users table.  They are stored in binary blobs.  I worked out sql that does this and throws no errors, but when I run it, the profile I 'changed' is still the same as it was before when I view it in Drupal.  I can't see anything in the table structure that suggests a lock.
Comment: Also, `drush sql-sanitize` does nothing for Commerce tables.  There is a sandbox for a module called commerce_sanitize but it appears to have been abandoned before they got to profile addresses.
Comment: @JeeElmore Make sure you changed all the relevant tables, including any revision tables.
Comment: Good catch...  Also, I am looking forward to trying your red wine debugging tip.  *grin   Thanks!
Answer: You can do this via custom module, implementing hook_drush_sql_sync_sanitize
You can see detailed instruction on this site
At the end, just run
drush sql-sanitize

IMPORTANT: Drush sql-sanitize will sanitise data in the current database – you do not want to play with this on a live or production server!
<?php
/**
 * @file /sites/all/modules/custom/es_gdpr_custom/es_gdpr_custom.drush.inc
 * Extends drush santize functionality.
 */

/**
 * Implements hook_drush_sql_sync_sanitize.
 */
function es_gdpr_custom_drush_sql_sync_sanitize($source) {
  // Truncate cache tables with personal data.
  $query = "TRUNCATE cache_field;";
  $query .= "TRUNCATE cache_form;";

  drush_sql_register_post_sync_op('sanitise_cache tables', dt('Truncate cache tables with personal data: cache_field, cache_form'), $query);

  // The query to sanitise field_data_commerce_customer_address table.
  $query = "UPDATE field_data_commerce_customer_address SET commerce_customer_address_administrative_area = 'State';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_locality = 'Some City';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_dependent_locality = 'Some City';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_postal_code = '00000';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_thoroughfare = 'Some address';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_premise = '00';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_sub_premise = '00';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_organisation_name = 'Some organization';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_name_line = 'First and Last Name';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_first_name = 'First name';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_last_name = 'Last name';";
  $query .= "UPDATE field_data_commerce_customer_address SET commerce_customer_address_data = NULL;";

  drush_sql_register_post_sync_op('sanitise_commerce_address', dt('Sanitise field_data_commerce_customer_address table.'), $query);

  // The query to sanitise field_revision_commerce_customer_address table.
  $query = "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_administrative_area = 'State';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_locality = 'Some City';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_dependent_locality = 'Some City';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_postal_code = '00000';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_thoroughfare = 'Some address';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_premise = '00';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_sub_premise = '00';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_organisation_name = 'Some organization';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_name_line = 'First and Last Name';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_first_name = 'First name';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_last_name = 'Last name';";
  $query .= "UPDATE field_revision_commerce_customer_address SET commerce_customer_address_data = NULL;";

  drush_sql_register_post_sync_op('sanitise_commerce_address_rev', dt('Sanitise field_revision_commerce_customer_address table.'), $query);

  // The query to sanitise commerce_order table.
  $query = "UPDATE commerce_order SET mail = 'firstname.lastname@example.com';";
  $query .= "UPDATE commerce_order SET data = NULL;";
  drush_sql_register_post_sync_op('sanitise_commerce_order', dt('Sanitise commerce_order table.'), $query);

  // The query to sanitise commerce_order_revision table.
  $query = "UPDATE commerce_order_revision SET mail = 'email@example.com';";
  $query .= "UPDATE commerce_order_revision SET data = NULL;";
  drush_sql_register_post_sync_op('sanitise_commerce_order_rev', dt('Sanitise commerce_order_revision table.'), $query);

  /*
   * Sanitize custom fields.
   */

  // Place your custom fields here.
}


SSH tunnel to Docker container

Question: Goal: connect locally to a remote repl (e.g. via lein repl :connect).
Locally, this is easy:

Run server (it starts an embedded nrepl server on port 8081)
Run lein repl :connect 8081 & voila! repl connected

I've also done this to connect to a repl on a remote server when the repl was running on a port that was not open, by using a SSH tunnel:

On some.host, run server (it starts embedded nrepl server on port 8081)
SSH tunnel ssh -N -T -L 8081:localhost:8081 email@example.com
Locally, lein repl :connect 8081 & voila! repl connected

However, my current setup is that "server" is run in a Docker container, which maps port 8081. So, in order to connect to the nrepl server, it's gotta go local -> some.host -> docker-container -> nrepl.
I can see that my docker container has port 8081 mapped:
$ sudo docker port container-id 8081
0.0.0.0:8081

And, on the server hosting the docker container, I can see that port 8081 is listening:
$ netstat -anl | sed -n '2p;/8081/p'
Proto    Recv-Q    Send-Q    Local Address   Foreign Address     State
tcp      0         0         :::8081         :::*                LISTEN

And it seems like I can open a SSH tunnel for port 8081; e.g. no errors/warnings from running:
ssh -N -T -L *:8081:localhost:8081 firstname.lastname@example.com

Which makes me think that I have the correct SSH tunnel, except that whenever I try to connect to the running repl server, it immediately fails, like so:
$ lein repl :connect 8081
Connecting to nREPL at 127.0.0.1:8081
SocketException The transport's socket appears to have lost its connection to the nREPL server

It's notable that the error is the connection is lost, because run without the SSH tunnel open, the same command fails with Connection refused. That makes me think that the SSH tunnel is OK and that the problem is on the server forwarding to the docker container, which is why the title of this is a generic question about opening a tunnel from client -> server -> docker container.
I thought it might be something to do with SSH GatewayPorts, so I tried enabling GatewayPorts but that didn't change anything.
Questions:

Is there anything obviously wrong with the SSH tunnel approach above?
How can I determine where the connection is being dropped?
Any other suggestions?

Thanks!
Answer: And... it turns out there was nothing wrong with the tunnel.
The problem was that starting an embedded nrepl server inside a docker container requires an explicit binding to "0.0.0.0". Without that, the nrepl server by default binds to "localhost", which makes it inaccessible from outside the docker container, despite the port mapping, because the docker port mapping uses 0.0.0.0:. Once the nrepl server was bound correctly, the port mapping took care of the rest.
Answer: Just as a helpful link to have a look at - Docker SSH. Very simplified way of managing SSH for Docker.
Comment: Howdy Harry, welcome to ServerFault.  https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers  Could you please make your answer stand on its own?

SSH tunnel to Docker container