place own block from module to the left of the screen

Question: This is the first time i'm making a module for drupal.
In my module I create a block with a vertical menu in it.
I would like to place the block glued to the left of the screen (out the wrapper).
So far i tried to make my own region in the module (which worked) but I can't get the region to appear in the website. I know i would have to do this in the page.tpl.php from the theme, but I'm trying to do this through my module only.
So is there a way to make the website take the region?
Is there a other/better way to place the block to the left?
thanks in advance!
TL
Answer: You have to edit your theme's template to create a new region.
You will need to add something like:
<?php print render($page['your_region']); ?>

Without this nothing in that region will ever get rendered.
You will also need to add it to your themes .info file.
For more information see: How do I create custom regions in a theme?
Comment: Where do I have to put that code?
Comment: And like I said, I would like not to adapt any oh the theme files :)
Comment: If you want to add a new region you have to modify your theme. No way around that. That code would sit in your page.tpl.php file.
Comment: Okaaj thanks!
Is there another way to place the bloxk there, without a region ?
Comment: Whilst it is possible to render blocks directly into a nodes content or a template it is rather missing the point of the whole block system. Generally themes are there to take care of what your site looks like and what regions are available, and modules are there to offer additional functionality. Your module should just create the block - but it is down to the theme to decide where it should be rendered. If you want to create new regions then you should make a new theme instead.
Answer: Making sure the region is in the .info file, and rendering should work to get it displayed.
You could put the block in whatever existing region you alrdy have, and 'pull it out' using purely CSS, using position:absolute and go from there.
Or, still use a separate region, and combine the output of that region, with the output of a 'default' region you have, using code.
While both work, you should avoid them, and stick to adding another custom region. Then make sure your template puts it in the right place.
If you really don't want to touch the theme, maybe you should think of working with a sub-theme instead. You'll still need to edit the templates to get the additional regions, but at least you'll have the original theme next to you for reference ( or whatever the reason is you don't want to change your theme files ).
Read up on sub-themes here


Show $|x(t)|$ is strictly decreasing for $t>0$ for the initial value problem $\dot{x} = -x^{3}, x(0)=1 $

Question: Solving the inital value problem gives me $x(t)=\frac{1}{(2t+1)^{1/2}}$ which is clearly striclty decreasing as $(2t+1)^{1/2}$ is strictly increasing. However is it possible to just say it's strictly decreasing as the derivative  $\dot{x} = -x^{3}$ is strictly decreasing for postive x, if not how would I solve this without having to explicitly solve the inital value problem.
Answer: Yes, you show that exactly like that. As $x(t)=0$ is a solution, and the right side is locally Lipschitz, the uniqueness theorem implies that the zero solution can not be crossed, all solutions have a constant sign.
Now the initial value $x(0)=1$ fixes the sign for the solution of the given IVP as positive, and the formula for the right side gives then the sign of the derivative  as negative.


Adjacency graph of cutting plane is a bipartite graph

Question: Each time you draw a line on a plane, you are cutting it in half. Suppose you keep doing this without drawing a line parallel to a previous one. An adjacency graph can be constructed to represent this where each node represents an undivided portion of the plane, and edges exist between portions that share a boundary edge (as created by the lines).
I want to prove that the adjacency graph is bipartite regardless of what lines are drawn.
I know that a graph is bipartite if it is 2-colourable and this could be used to prove that the adjacency graph is 2-colourable but I'm stuck with proving how a graph is 2-colourable by induction.
Any help is appreciated!!
Thanks.
EDIT
Here's an example
Comment: Im not sure about the result but this might lead you to some result: http://en.wikipedia.org/wiki/Voronoi_diagram
Answer: As Learner pointed out, the problem is equivalent to showing that there is no odd circuit in the graph. Roughly, the idea is that when you move from a region to an adjacent region, we are moving across one line, while remaining on the same side with respect to all other lines. So to reach back to the original region, we need to cross this line again, showing that all cycles must be of even degree.
To write it more formally, for each line, consider the two half-planes it created. Assign (arbitrarily) value $0$ to one of them and $1$ to the other. Now each region is uniquely determined by a sequence of bits $0,1$, one bit for each line. Also, observe that adjacent regions differ in exactly one bit (corresponding to the line separating them).
Now consider any cycle starting from a vertex $v$. As we saw above, after moving along an edge to a adjacent vertex, exactly one of the bits is flipped. So the parity of the sequence is toggled. It follows from this that if we start from $v$ and move along some edges and reach $v$ again, there must be even number of edges (as the parity must come back to original parity of $v$). Hence all cycles have even degree.
Answer: Theorem: A graph with atleast one edge is 2-chromatic if and only if it has no circuit of odd length.
Reference: Page 168 Theorem 8-2 in Graph Theory by narsingn Deo.
Your adjacency graph doesnt have any circuit with odd degree.
Answer: Motivated by learner's answer, it seems not difficult to construct an indutive proof based on the fact that a line cut a region it passed into two parts that there must be no odd circuits involved. Hence the graph is 2-colorable and must be bipartite(I cannot find a proof of this, actually...)


Template conditional based on a list field

Question: I have a 'List (text)' field set up with five options displayed as a series of checkboxes.
I would like the last of these checkboxes to control the visibility of a button in the node template.
<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'): ?>
    // do stuff
<?php endif; ?>

The problem with the above is that it only works when this checkbox is the only one selected, otherwise it is no longer the '[0]' result.
How could I go about checking all of the potential five checkboxes for my result?
Thanks!
EDIT
I thought I'd found a horribly verbose workaround by checking every offset one by one like so:
<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][1]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][2]['value'] == 'key_of_checkbox'): ?>
        // do stuff
<?php endif; ?>

etc... but, now I get an 'undefined offset' error for each offset that doesn't exist, ie. not all of the boxes will ever be checked, and so there are never usually five results, meaning that when only two of these checkboxes are checked offsets 2 - 4 don't exist. PHP doesn't like that, apparently.
I'm wondering if my problem here is that I should be using five boolean checkboxes, which at least will always return a result one way or another. That seemed messy when I was planning this out, but now it's looking ever more inviting!
EDIT 2
Since I'm short on time, I decided to go with my thoughts above and base my conditionals on single points of data which can either return me a 'true' or 'false' status. My PHP (as you can probably see above) is crappy to say the least - far too crappy to work out how to get around this one. I'd be interested if anyone has any ideas regarding this though!
Thanks for reading.
EXTRA EDITS for clarity and grammar
Answer: My php isn't the best, but I think this should work...
You could try using a foreach loop, and using a condition similar to this:
<?php foreach ($node->field_the_checkbox_field['und'] as $thisfield) {
    if($thisfield['value'] == 'key_of_checkbox'):
   // do stuff
} ?>

Comment: Thanks Geoff, I don't have time to check this out right now so I wont mark it as the answer, but when I do finally find time, I'll be sure to report back!


Why does forward stepwise selection reduce the AUC of a classifier to values < 0.500?

Question: I've recently been benchmarking different methods for feature selection, and found a weird issue when using forward stepwise regression. Specifically, when I train a sparse logistic regression model using forward stepwise selection (with AIC as my selection criterion), I can obtain a model with an AUC < 0.500.
I've included code to reproduce this situation below using the StepAIC function in the MASS R package and a processed version of the UCI Mammography Dataset (link). I ran this code several times to show how AUC and AIC change based on the number of variables added to the model.
As shown, AIC decreases monotonically with each variable, which is expected given that we are add variables to minimize AIC. However, the AUC falls way below 0.500 after adding the second variable... and then stays below 0.500 thereafter. To be clear, I wouldn't expect forward stepwise selection to monotonically increase AUC, but I also would not expect it to reduce AUC so drastically in a single step / output a classifier that is worse than random guessing.
I'm wondering if anyone can explain this phenomenon? Is there a methodological issue in using AIC as the selection criterion? Or could there be a bug with the StepAIC package?

Example (Dataset @ mammography_processed.csv):
require(ROCR)
require(MASS)

target_size = 2
train_data = read.csv(file = "mammography_processed.csv")

#fit model using forward stepwise logistic regression
model_initial = glm(y ~ 1, family = binomial, data = train_data)
model_final = glm(formula = y ~ ., family = binomial, data = train_data)
model = stepAIC(model_initial, scope =  as.formula(model_final), direction = "forward", steps = target_size, trace = FALSE)
coefs = model$coefficients;

#store coefficients all variables + the intercept in a vector
coef_names = c("(Intercept)", colnames(X));
coefficients = setNames(rep(0, length(coef_names)), coef_names);
idx = which(coef_names %in% names(coefs))
coefficients[idx] = coefs;

#compute AUC
X = as.matrix(train_data[1:ncol(train_data)-1])
scores = cbind(1, X) %*% coefficients
probabilities = inv.logit(scores)
prediction_object = prediction(probabilities, labels = train_data$y);
auc = performance(prediction_object, measure = "auc")@y.values[[1]]
aic = model$aic

print(sprintf("auc: %1.3f", auc))
print(sprintf("aic: %1.1f", aic))

Answer: I don't see the problem.  Check this demo.
library(pROC)  ## simpler alternative package
library(MASS)

target_size <- 2
train_data <- within(read.csv(file = "mammography_processed.csv"), {
  y <- factor(y)
})

## fit model using forward stepwise logistic regression
model_initial <- glm(y ~ 1, family = binomial, data = train_data)

upper_formula <- as.formula(paste("~",
                                  paste(setdiff(colnames(train_data), "y"),
                                        collapse = "+")))
target <- train_data$y

k <- ncol(train_data)
AUC <- AIC <- numeric(k)
AUC[1] <- auc(roc(target, predict(model_initial,
                                  train_data, type = "response")))
AIC[1] <- stats::AIC(model_initial)

for(j in 2:k) {
  model <- stepAIC(model_initial,
                   scope =  list(lower = ~1, upper = upper_formula),
                   direction = "forward",
                   steps = j-1, trace = FALSE)
  AUC[j] <- auc(roc(target, predict(model, train_data, type = "response")))
  AIC[j] <- stats::AIC(model)
}

dev.new(height = 6, width = 12)
par(mfrow = c(1,2))
plot(AIC, type = "b")
plot(AUC, type = "b", ylim = c(0, 1))
abline(h = 0.5, col = "red")

Comment: So what's the answer, why did it do that in the OP's case? Also can you post your AUC;AIC plots so we don't have to install that package and run your code, just to see the answer?


Should salutations be removed from questions?

Question: While reviewing suggested edits I noticed that some users sometimes edit others posts and remove salutations like

[Question text which follows the rules]
...
Thanks!

or

[Question text which follows the rules]
...
Thanks a lot
[Name]

Should we remove salutations? I personally wouldn't like it if somebody else edits my posts like that. At least thanking in advance should be ok in my opinion. Begin polite is also part of a community. I'd suggest to only remove extended salutations, e.g. if they more look like these much-beloved 10 line mail signatures.
What is your take on this?
Answer: The rules for stackoverflow apply to magento.SE.
See this for reference.
I read some of the answers (I hope I didn't miss something importan) and my conclusion is salutations are kind of a grey area. They are not encouraged but they are not banned.
Signing your posts...a big NO NO. You shouldn't do that.
Comment: *"Signing your posts...a big NO NO. You shouldn't do that."* - I completely agree! - Ben Marks, Developer & Community Evangelist, Magento, an eBay Inc Company, MCAB, MCD, MCD+, MCFD, MCSS, Sagittarius, Isle of Palms, SC...
Comment: @benmarks. Sorry the name doesn't ring a bell. Can you give me more info, please?
Answer: When editing questions, I always remove "fluff" like that, as it is policy on StackOverflow as well, but I wouldn't go so far to edit questions just to remove "Thank you".
What I consider fluff:

"thanks"
salutation and signing
irrelevant information about the poster (like "I am new to Magento")
irrelevant information about the problem (like "this is urgent!!!111")

Side note: When reading "Thanks in advance", I always think about the quote:

this connotes an intention not to thank anybody afterwards
Answer: "Welcome to Magento.SE!" is a standard I use for first-timers. I think this should be an exception and be allowed.
Comment: yup. Me too using this. It should be allowed
Answer: Say Hi at first and an anticipated Thanks at the end just make it polite and no disturbance for the following readers.
Signing : Agreed with Marius answer, a big no no, simply because no matter what, the post is signed already, so that becomes redundant...


Does level set has a boundary?

Question: Let $g:\mathbb{R}^n \to \mathbb{R}$ be a continuous function and for some $c>0$, we think its $c$-level set $g^{-1}(c)$.
Then does $g^{-1}(c)$ has a boundary? For example, is it possible that the set $\{x\in \mathbb{R} | 0\le x \le 1\}$ could be a level set of some continuous function?
I heard that if $g$ is differentiable, then its level set should be always manifold and so it thus not have boundary.
But how about level set for continuous function?
Any comments will be appreciated!
Answer: Yes the segment $[0,1]$ can be a level set of a continuous function. But for the example I'm going to construct it will be more convenient to show that $[1,2]$ is a level set of a continuous function
Consider the following continuous "trapezoid" function $f:\mathbb{R}\rightarrow\mathbb{R}$

For $x<0$ we let $f(x)=0$.
For $0\leq x<1$ let $f(x)=x$
For $1\leq x\leq 2$ let $f(x)=1$
for $2< x\leq 3$ let $f(x)= 3-x$
for $3<x$ let $f(x)=0$

(draw it)
I leave it as an exercise for you to show that this function is continuous (note that it is far from being differentiable). And it is easy to see that $[1,2]=f^{-1}(1)$.
Comment: Thank you very much! It helped me a lot!

Does level set has a boundary?


Calculating Average trend with possible missing data

Question: I am conducting a research on a group of subjects with population about 90. For each of them I have a time-serial datapoints such as:
  P1 =  [ [T1, 100],
          [T2, 23],
          [T3, 33],
           ...
        ]

   P2 =  [ [T1, 80],
           [T3, 77],
           [T4, 88]
           ...
        ]
   ...

Given that some datapoints are missing, for example, P2 doesn't have a datapoint for T2, how should I calculate the average for each time T? Should I simply use available points like
P1[T2] + P3[T2] + ... / 83

assuming that there are 83 datapoints at time T2
or should I "compensate" the missing data points like
P1[T2] + P2[somecompensited number] + P3[T2] + ... / 90

assuming 90 is the total population
Answer: It looks like you may want to do some sort of time series imputation. Imputation refers to the prediction of missing values so you can perform an analysis as if your data were complete. Some common (basic) choices for time series are last observation carried forward (if person 1 is missing T2, you would use substitute it with their value from T1) or the average of the individual's time series to fill in missing points.
Here's a link to an article, imputeTS: Time Series Missing ValueImputation in R, that might help you dig into this problem a little deeper: https://cloud.r-project.org/web/packages/imputeTS/vignettes/imputeTS-Time-Series-Missing-Value-Imputation-in-R.pdf
Comment: An average of values before and after is an alternative. A more sophisticated replacement value can be based on the arima structure e.g. 1,9,1,9,1,9,?,9 where a good estimate of the missing value would be"1" based upon the memory/arima structure


SCRIPT para Converter e Salvar Endereços

Question: Desenvolvi em uma API REST com CakePHP um script para converter uma coordenada $lat e $lng em endereços formatados. O script verifica se a coordenada está salva no banco, caso negativo ela busca do google e já salva no banco.
O script tem funcionado normalmente, segue script abaixo:
GEOCODES CONTROLLER
        // Function to serialize array $response to the format requested
        public function beforeRender() {
            $this->set('_serialize', 'response');
        }
        public function index(){
            //$functions = new GeocodeFunctions();
            //$latlng = $functions->verificaLatLng($this->request->query['latlng']);
            $response = $this->requestAction(
                array('controller' => 'geocodes', 'action' => 'geocode'),
                array('pass' => array($this->request->query['latlng']))
            );
            $this->set('response',$response);
        }
        public function geocode($latlng = null) {
            $db = ConnectionManager::getDataSource("geocode");
            $functions = new GeocodeFunctions();
            //$latlng = $functions->verificaLatLng($latlng);
            if($latlng != null){
                $geocode = $db->fetchAll(
                    'Select enderecos.endereco as endereco from geocodes inner join enderecos on geocodes.id_endereco = enderecos.id where geocodes.latlng like ? ;'
                    ,array($latlng)
                );
                if(empty($geocode)){
                    $google = $this->google($latlng, $db);
                    if(array_key_exists('results',$google) && $google->results != array()){
                        $response = array('code'=>2, 'endereco'=>$google->results[0]->formatted_address);
                    }else if(array_key_exists('error_message',$google)){
                        $response = array('code'=>3, 'endereco'=>'O seguinte erro ocorreu "'.$google->error_message.'", por favor informe ao suporte do ocorrido.');
                    }else{
                        $response = array('code'=>3, 'endereco'=>'Novo erro detectado! Por favor, entre em contato com o suporte informando dia e hora do ocorrido.');
                        CakeLog::write('geocodes', json_encode($google));
                    }
                }
                else{
                    $response= array('code'=>1, 'endereco'=>$geocode[0]['enderecos']['endereco']);
                }
            }
            else{
                $response = array('code'=>0, 'endereco'=>'latitude e longitudade vazia!');
            }
            return $response;
        }

        public function google($latlng = null, $db){
                $data = array();
                if($latlng != null){
                    $HttpSocket = new HttpSocket();
                    $results = $HttpSocket->get(
                    'https://maps.googleapis.com/maps/api/geocode/json',
                       array(
                        'latlng' => $latlng,
                        'key' => 'minha-chave-secreta'

                        )
                    );
                    if(array_key_exists('body', $results)) $data = json_decode($results['body']);
                    if(array_key_exists('results',$data) && count($data->results)>0){
                        $id = $db->fetchAll(
                            'Select id from enderecos where endereco like ? ;'
                            ,array($data->results[0]->formatted_address)
                        );
                        if(empty($id)){
                             $db->fetchAll(
                                '
                                 INSERT INTO `enderecos`(`endereco`) select ? from dual
                                 WHERE NOT EXISTS (SELECT endereco FROM enderecos WHERE endereco = ?);
                                 INSERT INTO `geocodes`(`latlng`, `id_endereco`) SELECT  ? , (SELECT LAST_INSERT_ID()) from dual
                                 WHERE NOT EXISTS (SELECT latlng FROM geocodes WHERE latlng = ?);
                                '
                                 ,array($data->results[0]->formatted_address, $data->results[0]->formatted_address, $latlng,$latlng)
                             );
                        }else{
                            $db->fetchAll(
                                'INSERT INTO `geocodes`(`latlng`, `id_endereco`) select  ? , ? from dual
                                 WHERE NOT EXISTS (SELECT latlng FROM geocodes WHERE latlng = ?)'
                                ,array( $latlng, $id[0]['enderecos']['id'], $latlng )
                            );
                        }
                    }
                    return $data;//->results[0]->formatted_address

                }
                else{
                    return null;
                }
        }
        public function save(){

        }
    }
    ?>

Entretanto ao colocar ela numa das funções de um outro Controller, deixa o script muito lento gerando um Error 502 Bad Gateway na página. O controller é o seguinte:
Uma função de um dos controller que usá o GeocodeController
[...]
public function getRelatorioRotas(){
    // Declarando classes
    $fun = new Functions();
    $GEO = new GeocodesController;
    // obtendo dados da requisição
    $data = $this->request->data;
        // contador de pontos
        if($data['dtFim'] == null){
            $count = $this->Record->query("
                Select Count(*) as total FROM  `records`
                WHERE  `hour` >= ".$data['dtInicio']."
                AND `vehicle_id` = ".$data['veiculo']."
                ORDER BY `records`.`hour` asc
            ");
        }else{
            $count = $this->Record->query("
                Select Count(*) as total FROM  `records`
                WHERE  `hour` >= ".$data['dtInicio']."
                AND `hour` <= ".$data['dtFim']."
                AND `vehicle_id` = ".$data['veiculo']."
                ORDER BY `records`.`hour` asc
            ");
        }
        $count = $count[0][0]['total'];
    if($count>0){
        // Instancia de variaveis
            // variavel paginas e tempo
            $i=$inicial=$distancia=$chega=0;
            $final=20;
            // Ponto Final e Endereço
             $PontoFinal=$PontoInicial=$LastPonto=$dt=null;
            // variavel de retorno dos pontos
            $rotas = $rota = array();
            $velMed = $velMax = $contadorRotas = 0;
            $menor=true;
            if($data['dtFim'] == null){
                $query = $this->Record->query(
                    "SELECT
                    lat, lng, `ignition`, `hour`, `speed`
                    FROM  `records`
                    WHERE  `hour` >= ".$data['dtInicio']."
                    AND `vehicle_id` = ".$data['veiculo']."
                    ORDER BY `records`.`hour` asc
                    "
                );
            }else{
                $query = $this->Record->query(
                    "SELECT
                    lat, lng, `ignition`, `hour`, `speed`
                    FROM  `records`
                    WHERE  `hour` >= ".$data['dtInicio']."
                    AND `hour` <= ".$data['dtFim']."
                    AND `vehicle_id` = ".$data['veiculo']."
                    ORDER BY `records`.`hour` asc
                    "
                );

            }
                $count = count($query)-1;
                foreach ($query as $key => $record) {
                    $latlng = $record['records']['lat'].",".$record['records']['lng'];
                    if( $record['records']['speed'] > $velMax){
                        $velMax =  $record['records']['speed'];
                    }
                    $velMed+=$record['records']['speed'];
                    if( count($rota) <= 0 || $PontoInicial == null ) {
                            $dt = $GEO->geocode($latlng);

                            $PontoInicial = array(
                                'endereco' => $dt['endereco'],
                                'hour' => $record['records']['hour']
                            );
                            if($PontoFinal!=null && ( ($record['records']['hour'] - $PontoFinal['ponto']['hour'])<= (3*60*60))){
                                array_push($rota, array(
                                    'latlng' => $PontoFinal['ponto']['latlng'],
                                    'ignition' => $PontoFinal['ponto']['ignition'],
                                    'speed' => $PontoFinal['ponto']['speed'],
                                    'hour' => $record['records']['hour']
                                ));
                            }
                            $obj = array(
                                'latlng' => $latlng,
                                'ignition' => $record['records']['ignition'],
                                'speed' => $record['records']['speed'],
                                'hour' => $record['records']['hour']
                            );
                            array_push($rota, $obj);
                        $distancia = 0;
                    }
                    else if(
                             $record['records']['ignition']==true
                             && ($record['records']['hour'] - $LastPonto['hour']) < 600
                    ) {
                        $ola = $fun->calcDistancia($LastPonto['lat'], $LastPonto['lng'], $record['records']['lat'], $record['records']['lng']);
                        $distancia += $ola;

                        if($ola > 0.01 &&  end($rota)['hour'] <= $record['records']['hour']){
                            $obj = array(
                                'latlng' => $latlng,
                                'ignition' => $record['records']['ignition'],
                                'speed' => $record['records']['speed'],
                                'hour' => $record['records']['hour'],
                                'distancia_do_ultimo_ponto' => $ola
                            );
                            array_push($rota, $obj);
                        }
                    }else {
                        if($key >= $count &&  end($rota)['hour'] <= $record['records']['hour']){
                            $ola = $fun->calcDistancia($LastPonto['lat'], $LastPonto['lng'], $record['records']['lat'], $record['records']['lng']);
                            $distancia += $ola;
                                $obj = array(
                                    'latlng' => $latlng,
                                    'ignition' => $record['records']['ignition'],
                                    'speed' => $record['records']['speed'],
                                    'hour' => $record['records']['hour'],
                                    'distancia_do_ultimo_ponto' => $ola
                                );
                            $ultimoPonto = $obj;
                        }else{
                            $ultimoPonto = end($rota);
                        }

                            //$dt = $GEO->geocode($ultimoPonto['latlng']);
                            $PontoFinal = array(
                                'endereco' => $dt['endereco'],
                                'hour' => $ultimoPonto['hour']
                            );
                            $velMed /= (count($rota));
                            if($PontoFinal['hour'] != $PontoInicial['hour']){
                                $dur = $PontoFinal['hour'] - $PontoInicial['hour'];
                                if($dur > 60 && $distancia >0 && count($rota) >=4){
                                    if(count($rotas)>0){
                                        $ultima = end($rotas);
                                        $ultima = end($ultima['Pontos']);
                                        $oux = $rota[0];
                                        $diferenca = (int)$rota[0]['hour'] - (int)$ultima['hour'];
                                        if($diferenca < (600)){
                                            $nova=false;
                                            $contadorRotas--;
                                            $ultima=array_pop($rotas);
                                            if($ultima['velocidadeMaxima']>$velMax){
                                                $velMax = $ultima['velocidadeMaxima'];
                                            }
                                            foreach ($rota as $value) {
                                                array_push($ultima['Pontos'], $value);
                                            }

                                            array_push($rotas, array(
                                                'id'=> $contadorRotas,
                                                'pontoInicial'=>$ultima['pontoInicial'],
                                                'Pontos' => $ultima['Pontos'],
                                                'pontoFinal'=> $PontoFinal,
                                                'distancia'=>$ultima['distancia']+$distancia,
                                                'duracao'=> $ultima['duracao']+$dur,
                                                'velocidadeMaxima'=> $velMax,
                                                'velocidadeMedia'=> ($ultima['velocidadeMedia']+$velMed)/2
                                            ));

                                        }else{
                                            $nova = true;
                                        }
                                    }else{
                                        $nova = true;
                                    }
                                    if($nova){
                                        array_push($rotas, array(
                                            'id'=> $contadorRotas,
                                            'pontoInicial'=>$PontoInicial,
                                            'Pontos' => $rota,
                                            'pontoFinal'=> $PontoFinal,
                                            'distancia'=>$distancia,
                                            'duracao'=> $dur,
                                            'velocidadeMaxima'=> $velMax,
                                            'velocidadeMedia'=> $velMed
                                        ));
                                    }
                                    $contadorRotas++;
                                }
                            }
                            $PontoFinal['ponto'] = $rota[count($rota)-1];

                            $distancia = $velMed = $velMax = 0;
                            $PontoInicial=null;
                            $rota=array();
                    }
                    $LastPonto = $record['records'];
                }
                if(count($rotas)>0){
                    $this->set('response', array('code'=>1,'rotas'=>$rotas, 'dataInicial'=> $data['dtInicio']));
                }else{
                    $this->set('response', array('code'=>0, 'rotas'=>$rotas, 'dataInicial'=> $data['dtInicio']));
                }
    }
    else{
        $this->set('response', array('code'=>0));
    }

}
[...]

Se eu comentar a linha $dt = $GEO->geocode($latlng); o script funciona perfeitamente.
Toda via, para razões de debug comecei a comentar o Controller do Geocodee e printar por etapas. E verifiquei que estava dando conflito no insert das tabelas por causa das unique key, coisa que tinha resolvido com um Insert Select com clausula WHERE para verificar se existia, mas não esta funcionando. Depois disso verifiquei que o erro não ocorria com a mesma coordenada ou endereço duas vezes. Até o momento estou sem solução.
Comment: Escreva no campo resposta a resposta que você encontrou =] Assim isso poderá ajudar demais pessoas. Também não é considerado bem visto colocar "resolvido" no título, o ideal seria marcar a resposta que de fato resolveu seu problema
Comment: Coloque a resposta no campo de resposta abaixo: https://pt.stackoverflow.com/revisions/248697/3
Comment: Obrigado, não conheço muito das normalizações do stackoverflow.
Answer: SOLUÇÂO ENCONTRADA
Notei que estava realizando varias requisições por segundo ao google, o que estourava o limite deles, entretanto tais requisições não eram necessárias visto que só precisava dos endereços final e inicial de cada rota. Então fiz outro foreach no final do script para buscar os endereço conforme segue abaixo:
Dentro do antigo foreach troquei as seguintes linhas:
[...]
//  $dt = $GEO->geocode($latlng);
$PontoInicial = array(
    'endereco' => $latlng,
    'hour' => $record['records']['hour']
);
[...]

E acrescentei o seguinte foreach:
            foreach ($rotas as $K => $V) {
                $rotas[$K]['pontoFinal']['endereco'] = $GEO->geocode($rotas[$K]['pontoFinal']['endereco']);
                $rotas[$K]['pontoFinal']['endereco'] = $rotas[$K]['pontoFinal']['endereco']['endereco'];
                $rotas[$K]['pontoInicial']['endereco'] = $GEO->geocode($rotas[$K]['pontoInicial']['endereco']);
                $rotas[$K]['pontoInicial']['endereco'] = $rotas[$K]['pontoInicial']['endereco']['endereco'];
            }


Multilingual content and single language admin interface

Question: I want my site's content to be multi-lingual. I have a language switcher that can toggle between both the English and Spanish translations of a page. I want the administrative interface to always be in English, no matter whether you navigate to it from a Spanish or English translation of the page.
Here is my configuration at /admin/config/regional/language/detection:

Here is my configuration at user/1/edit:

My admin interface is always in English, but now my content is also always in English, no matter if I toggle the page to Spanish.
I have tried many settings, including the settings in Content language detection.
What is the correct configuration to achieve this?

/es/node/1

/admin/config/regional/language/detection/url

/admin/config/regional/language
Comment: What happens if you change the URL path manually on an English page to a Spanish path?  Also, try putting URL first and account admin pages second.
Comment: The content remains in English, but the surrounding interface is in Spanish. Screen shot added to question.
Comment: In your user settings you set site language to english what happens if you logout?
Comment: If I logout, it works correctly I can toggle between the English and Spanish content.
Answer: On a fresh install, I could get it working that way:
In admin/config/regional/language/detection

put  Account administration pages on top of Interface text language detection an enable it of course.
enable URL method as second choice
enable Content language detection and put URL on top of detection methods.

In user/1/edit language settings :

set Administration pages language with your preferred language

There are various issues on D.O about that, maybe this is the most relevant  one : When content language detection is different from interface language detection, the detected language is not applied to the rendered content.
Apply these patches :

When content language detection is different ... (patch #24)
'Account administration pages' language negotiation causes 'access denied' in toolbar subtree caching (patch #10)
Admin toolbar should always be rendered in the admin language (if set) (patch #40)

Empty caches :

$ drush cache-rebuild

Language dropdown switcher and everything else seems now to be working fine !
An example of spanish content, strings passed through t() are translated, admin toolbar in english...

The same page edited: admin interface fully in english, but content shows  the correct translation....
Comment: Seems to work. Good answer :-)
Comment: thank you! I cannot understand why this solution is still not out of the box patch less enabled in core... in 2018 August!
Comment: If I understand your answer correctly, the problem with your configuration is: (a) the language switcher disappears (when URL is disabled in Interface text language detection; and (b) only the content is translated at _es/node/1_: anything in code run through `t()` or `|t` remains untranslated. For example: 'Powered by Drupal' does not transform to 'Funciona con Drupal'. I only want _/admin_ pages to be English-only.
Comment: @24ma13wg my bad ! Right, I'v been working a bit more around your problem, and I believe this is working fine now. I'm going to edit the answer. Check in 15mn ;)
Comment: @24ma13wg, for  the sake of clarity and future reference, I rewrote the  answer with exact setup and patches.


vb.net, sqlexpress, table does not exist

Question: I have sqlexpress installed, am able to connect to the server but says the table does not exits.
Here is the code:
<code>Dim myConn As SqlConnection
        myConn = New SqlConnection("Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;")
        Dim mySQL As String = "SELECT * FROM tblStores"
        Dim myDA As New SqlDataAdapter(mySQL, myConn)
        Dim MyDS As New DataSet()
        myConn.Open()
        myDA.Fill(MyDS)
        Me.DataGridView1.DataSource = MyDS.Tables(0)
        myConn.Close()
</code>

Any ideas of why I can't connect to the table says it doesn't exist
Comment: Why are you creating user objects in `master`? Also, you are clearly not connected to the same instance. The Connection string says `localhost\SQLEXPRESS` and the image says `SKIP` (no named instance)
Comment: thanks for the help .... firgured it out with your info.  I am now connected to the SQLEXPRESS and created a new DB shopping ... new connection string: myConn = New SqlConnection("Server=SKIP\SQLEXPRESS;Database=shopping;Trusted_Connection=True;") ... it now populates ... ty so much
Comment: What is "it"? What gave you that connection string? That doesn't change my point; in SSMS you are connected to a instance on the host `SKIP` using the default instance name (`MSSQLSERVER`), and in the code you are connecting to an instance called `SQLEXPRESS` on the localhost. Even if `SKIP` and `localhost` are the same host, `SQLEXPRESS` <> `MSSQLSERVER`; those are 2 different instances.
Comment: first time using it and when I installed the server that is the connection string it gave me.
Answer: First of all, wrong ServerName. And after that please create your own DB, don't use master DB.


Ionic 2 and ApiRTC

Question: I am currently trying to use the ApiRTC APIs in an ionic 2 application and i want to callee to be able to either accept or reject the call before any media stream is sent. I am trying to replicate this example but in my case, the call gets accepted automatically without the callee clicking in the accept button even after a have set webRTCClient.setUserAcceptOnIncomingCall(true) as recommended in the documentation. See below my implementation.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

declare var apiRTC: any

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  showCall: boolean;
  showHangup: boolean;
  showAnswer: boolean;
  showReject: boolean;
  showStatus: boolean;
  showRemoteVideo: boolean = true;
  showMyVideo: boolean = true;

  session;
  webRTCClient;
  incomingCallId = 0;
  myCallId;
  status;
  calleeId;

  constructor(public navCtrl: NavController) {
    this.InitializeApiRTC();
  }

  InitializeApiRTC() {
    //apiRTC initialization
    apiRTC.init({
      apiKey: "<APIKEY>",
      //apiCCId : "1",
      onReady: (e) => {
        this.sessionReadyHandler(e);
      }
    });
  }

  sessionReadyHandler(e) {
    this.myCallId = apiRTC.session.apiCCId;
    this.InitializeControls();
    this.AddEventListeners();
    this.InitializeWebRTCClient();
  }

  InitializeControls() {
    this.showCall = true;
    this.showAnswer = false;
    this.showHangup = false;
    this.showReject = false;
  }

  InitializeControlsForIncomingCall() {
    this.showCall = false;
    this.showAnswer = true;
    this.showReject = true;
    this.showHangup = true;
  }

  InitializeControlsForHangup() {
    this.showCall = true;
    this.showAnswer = false;
    this.showReject = false;
    this.showHangup = false;
  }

  UpdateControlsOnAnswer() {
    this.showAnswer = false;
    this.showReject = false;
    this.showHangup = true;
    this.showCall = false;
  }

  UpdateControlsOnReject() {
    this.showAnswer = false;
    this.showReject = false;
    this.showHangup = false;
    this.showCall = true;
  }

  RemoveMediaElements(callId) {
    this.webRTCClient.removeElementFromDiv('mini', 'miniElt-' + callId);
    this.webRTCClient.removeElementFromDiv('remote', 'remoteElt-' + callId);
  }

  AddStreamInDiv(stream, callType, divId, mediaEltId, style, muted) {
    let mediaElt = null;
    let divElement = null;

    if (callType === 'audio') {
      mediaElt = document.createElement("audio");
    } else {
      mediaElt = document.createElement("video");
    }

    mediaElt.id = mediaEltId;
    mediaElt.autoplay = true;
    mediaElt.muted = muted;
    mediaElt.style.width = style.width;
    mediaElt.style.height = style.height;

    divElement = document.getElementById(divId);
    divElement.appendChild(mediaElt);

    this.webRTCClient.attachMediaStream(mediaElt, stream);
  }

  AddEventListeners() {
    apiRTC.addEventListener("userMediaSuccess", (e) => {
      this.status = "You are calling " + e.detail.remoteId + "
";
      this.status = this.status + "CallID = " + e.detail.callId + "
";
      this.status = this.status + "Call Type = " + e.detail.callType;
      this.showStatus = true;
      this.showMyVideo = true;

      this.webRTCClient.addStreamInDiv(e.detail.stream, e.detail.callType, "mini", 'miniElt-' + e.detail.callId, {
        width: "128px",
        height: "96px"
      }, true);

/*      this.AddStreamInDiv(e.detail.stream, e.detail.callType, "mini", 'miniElt-' + e.detail.callId, {
        width: "128px",
        height: "96px"
      }, true);*/

    });

    apiRTC.addEventListener("userMediaError", (e) => {
      this.InitializeControlsForHangup();

      this.status = this.status + "
 The following error has occurred
 " + e;
    });

    apiRTC.addEventListener("incomingCall", (e) => {
      this.InitializeControlsForIncomingCall();
      this.incomingCallId = e.detail.callId;
    });

    apiRTC.addEventListener("hangup", (e) => {
      if (e.detail.lastEstablishedCall === true) {
        this.InitializeControlsForHangup();
      }
      this.status = this.status + "
 The call has been hunged up due to the following reasons
 " + e.detail.reason;
      this.RemoveMediaElements(e.detail.callId);
    });

    apiRTC.addEventListener("remoteStreamAdded", (e) => {
      this.webRTCClient.addStreamInDiv(e.detail.stream, e.detail.callType, "remote", 'remoteElt-' + e.detail.callId, {
        width: "300px",
        height: "225px"
      }, false);
    });

  }

  InitializeWebRTCClient() {
    this.webRTCClient = apiRTC.session.createWebRTCClient({
      status: "status" //Optionnal
    });
    this.webRTCClient.setAllowMultipleCalls(true);
    this.webRTCClient.setVideoBandwidth(300);
    this.webRTCClient.setUserAcceptOnIncomingCall(true);
  }

  MakeCall(calleeId) {
    var callId = this.webRTCClient.call(calleeId);
    if (callId != null) {
      this.incomingCallId = callId;
      this.showHangup = true;
    }
  }

  HangUp() {
    this.webRTCClient.hangUp(this.incomingCallId);
  }

  AnswerCall(incomingCallId) {
    this.webRTCClient.acceptCall(incomingCallId);
    this.UpdateControlsOnAnswer();
  }

  RejectCall(incomingCallId) {
    this.webRTCClient.refuseCall(incomingCallId);
    this.UpdateControlsOnReject();
    this.RemoveMediaElements(incomingCallId);
  }

}
<ion-header>
    <ion-navbar color="dark">
        <ion-title>
            Call Demo - {{myCallId}}
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-list>
        <ion-item>
            <ion-label floating>Call ID:</ion-label>
            <ion-input type="text" [(ngModel)]="calleeId"></ion-input>
        </ion-item>
    </ion-list>
    <ion-grid>
        <ion-row>
            <ion-col>
                <button *ngIf="showCall" ion-button block (click)='MakeCall(calleeId)'>Call</button>
            </ion-col>
            <ion-col>
                <button *ngIf="showHangup" ion-button block color="danger" (click)='HangUp()'>Hangup</button>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col>
                <button *ngIf="showAnswer" ion-button block color="secondary" (click)='AnswerCall(incomingCallId)'>Answer</button>
            </ion-col>
            <ion-col>
                <button *ngIf="showReject" ion-button block color="danger">Reject</button>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col>

            </ion-col>
        </ion-row>
        <ion-row *ngIf="showRemoteVideo">
            <ion-col>

Remote Stream

            </ion-col>
        </ion-row>
        <ion-row *ngIf="showMyVideo">
            <ion-col>

My Stream

            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

Kindly assist in checking if i am doing anything wrong.
Answer: You must set one more step in sessionReadyHandler.
try to use this function.
webRTCClient.setUserAcceptOnIncomingCallBeforeGetUserMedia(true);
I was facing the same issue . This function helped me and it worked well.
Maybe it will work for you.
Answer: Maybe, there is an asynchronism issue with the code in your application: webRTCClient creation may not be finished as we now check the presence of audio/video device.
I would advice to listen to "webRTCClientCreated" event before using webRTCClient  :
function webRTCClientCreatedHandler(e) {
   this.webRTCClient.setAllowMultipleCalls(true);
   this.webRTCClient.setVideoBandwidth(300);
   this.webRTCClient.setUserAcceptOnIncomingCall(true);
}

apiRTC.addEventListener("webRTCClientCreated", webRTCClientCreatedHandler);

Let us know if this help.
Comment: Thanks Frederic for the response. I have done as advised but the issue still persist. I have uploaded the project to GitHub and can be accessed with the link [Call Demo](https://github.com/efizzy/call-demo). Kindly assist in looking at what else an doing wrong. Regards.
Comment: Hello, I have used your code to make a simple call page demo with call acceptation and it is working correctly : call is not established before user accept the call : you can access it here : https://www.apizee.com/Demo/testIonic/testIonic.html

Ionic 2 and ApiRTC


Construct a martingale with a given distribution?

Question: Given a random variable Y, is it possible to construct a martingale M such that $$M_1 \stackrel{D}{=} Y$$
I'm not sure how to go about proving that such an M exists under such general conditions, but I feel like this is definitely a standard question...
Answer: If random variable $Y$ takes values in $\mathbb R$, you can find a measurable function $f: \mathbb R\to \mathbb R$, such that $f(N)$ has the same distribution as $Y$, where $N$ is a standard Gaussian random variable.
Now, for a Brownian motion $B_t$, define
$$ M_t = E(f(B_1)|\mathcal F^B_t)$$
Comment: How is that first result proved? The one where you can find a measurable $f$ such that $f(N)$ has the same distribution as $Y$?
Comment: Let $g$ be the cdf of $Y$, ang $h$ that of N, and $f= g^{-1}h$


Calling Unmanaged C++ from C#

Question: I'm running VS2012 on Win7 with .NET 4.0.
I've tried the following:

Create C++ DLL project
Checked\Unchecked the export symbols box
I've made sure my platform targets are the same. In my case, win32
I've added the necessary extern "C" and __declspec(dllexport) where needed.
I've successfully compiled my DLL and have tried to reference it in a C# project.

Unfortunately, I get an error telling my it can't be added and that I need to make sure it's a valid assembly or COM object.
I've given up trying to get my code to export, so I'd be happy with just the example "42" getting through!
I've tried looking at it with dumpbin and it is correctly exporting symbols:
1    0 00011023 ??0CEvolutionSimulator@@QAE@XZ
2    1 00011127 ??4CEvolutionSimulator@@QAEAAV0@ABV0@@Z
3    2 00011005 ?GetNumber@CEvolutionSimulator@@QAEHXZ
4    3 0001104B ?fnEvolutionSimulator@@YAHXZ
5    4 00017128 ?nEvolutionSimulator@@3HA

My brain is fresh out of ideas. Can someone please enlighten me? I seem to get this error no matter what I try.
Comment: Sorry about the formatting. Never done this before. I don't know why the editor didn't like my indentations :(
Comment: Thanks for the edit, paqogomez!
Comment: One common approach is to have C++/CLI (managed C++) "glue" project that can be directly referenced by a C# project. In that managed C++ project, you can call the functions of your native DLL.
Comment: I had some similar issue a long time ago. By using Dependency Walker i figured out, that the functions weren't exported. I really had to add a *.def file which contained all the exported functions. From this point on, the methods were visible in Dependency Walker and the DllImport worked fine
Answer: You need to pinvoke the functions residing in your C++ DLL (exported using extern "C") from your .NET code using the DllImportAttribute. You can't reference your C++ DLL like a .NET assembly, and you can't use classes from the DLL, only DllImported C-like functions.
Example from msdn:
using System;
using System.Runtime.InteropServices;

class Example
{
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    static void Main()
    {
        // Call the MessageBox function using platform invoke.
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}

Comment: I've now tried this method, but it claims it can't find the entry point for my test function. And again, I've verified that I'm exporting the functions properly using dumpbin. Everything is public and static of course. I've even put a copy of the DLL in my build folder.

Calling Unmanaged C++ from C#


Intuition for expressing a cycle as a product of transpositions.

Question: I have recently learned the proof of:
$(a_1 \ a_2 \ \ldots \ a_n) = (a_1 \ a_k)(a_1 \ a_{k-1}) \ldots (a_1 \ a_2) = (a_k \ a_{k-1}) (a_k \ a_{k-2}) \ldots (ak \ a_1) = (a_1 \ a_2) (a_2 \ a_3 ) \ldots (a_{k-1} \ a_k)$
Now I can prove the above 3 equalities through induction but unfortunately induction, unlike a direct proof, doesn't quite tell me what is really going on. I'm struggling to understand this intuitively. I don't want to just memorize it.
Can anyone walk me through this with an intuitive explanation. Thank you.
Answer: $(a_1,a_2,\cdots, a_n) = (a_1,a_n)(a_1,a_{n-1})\cdots(a_2, a_1)$
Read the composition of cycles from right to left.  How do they act on the element $a_1$?  The right most transposition "sees" $a_1$ and takes it to $a_2.$  None of the rest of the transpositions act on $a_2.$
Consider the element $a_k,$  the first several transpositions do not act on $a_k.$  The first transposition that does is $(a_1,a_k).$  That takes $a_k$ to $a_1.$  The next transpositions takes that element to $a_{k+1}.$
In this chain of transpositions, $a_1$ is acting as the interchange for all of the other elements.  Every element gets sent to $a_1$ and then sent from $a_1$ to its destination.
$(a_n,a_{n-1})\cdots (a_n,a_1)$ is the same idea, except $a_k$ is acting as the interchange.
$(a_1,a_2)(a_2,a_3)\cdots(a_{n-1},a_n)$ even though it is ultimately the same cycle, the activity that is going on is a little bit different.  Consider the element $a_k,$  it glides along unaffected by the first several transpositions, until it hits $(a_{k+1},a_k)$ gets shifted and then again the rest of the transpositions do nothing.
Answer: The intuition you seem to need is how to read off from a permutation given as a product of cycles the mapping the permutation represents. If you consider a single cycle such as $(1 \; 2 \; 3)$, then it is the permutation that maps $1$ to $2$, $2$ to $3$ and $3$ to $1$. When you look at a product of two or more cycles that may overlap, then you have to decide whether to work from left to right or from right to left. If I work from left to right $(1 \; 2 \; 3)(2 \; 4)$ maps $1$ to $4$ (via $2$), $2$ to $3$, $3$ to $1$ and $4$ to $2$.
So now it should be intuitively clear that $(1 \; 2)(2 \;3)\ldots (47 \; 48) (48 \;1) $ (for example) is the cyclic permutation $(1\; 2\; \ldots \; 48)$. And, in general that if the $a_i$ are all distinct that $(a_1\;a_2)(a_2\;a_3)\ldots (a_{n-1}\;a_n)(a_n\;a_1)$ is the cyclic permutation $(a_1\; a_2\; \ldots \; a_n)$.


Buttons got lock again after unlocking another button

Question: I am having issue regarding the buttons. After succeeding unlocking level 2 based on reaching the score from playing Level 1. I proceed to test Level 2 and ensure it can unlock Level 3 based on the score requirement, however, after succeed in unlocking Level 3. Level 2 become lock again. I am really not sure what went wrong. I may have got my logic wrong or something. It should had already remain enabled(true) after the Level 2 button had been set to enabled true. I will show my code related. Anyone who knows the answer please guide me.
This is in the LevelPage activity where it contains all the Level buttons for the user to choose which level to play, i will show just the relevant since the code in this activity is too long.
    DBHelper db = new DBHelper(LevelPage.this);
    HashMap<String,String> data = db.getData();
    final String level1Score = data.get("LEVEL1");
    final String level2Score = data.get("LEVEL2");
    final String level3Score = data.get("LEVEL3");
    final String level4Score = data.get("LEVEL4");

    btnLevel1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickSound.start();
            Intent intent = new Intent(LevelPage.this, Level1.class);
            startActivity(intent);
        }
    });

    if (level1Score != null && level1Score.equals("30")) {
        btnLevel2.setEnabled(true);
    btnLevel2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level2.class);
                startActivity(intent);

            }
        });

    } else {
        btnLevel2.setEnabled(false);
    }

    if (level2Score != null && level2Score.equals("35")) {
        btnLevel3.setEnabled(true);
        btnLevel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                Intent intent = new Intent(LevelPage.this, Level3.class);
                startActivity(intent);

            }
        });
    } else {
        btnLevel3.setEnabled(false);
    }

This is the Level2 page where the user plays the game and ensure to score 35 points to unlock:
else if (score == 35) {
                DBHelper db = new DBHelper(Level2.this);
                db.saveData(2,"35");
                AlertDialog.Builder builder = new
AlertDialog.Builder(Level2.this);
                builder.setTitle("Level 2 Complete!");
                builder.setMessage("You have won! You have unlock level 3!
You can proceed to Level 3 or go back.");
                builder.setPositiveButton("Unlock", new
DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level2.this,
LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });

This is the SQLite Database to save and get the score data:
 private static final int DATABASE_VERSION = 1;
 private static final String DATABASE_NAME = "Level";
 private static final String USERTABLE = "USER_INFO";
 private static final String KEY_ID = "id";
 private static final String LEVEL1 = "LEVEL1";
 private static final String LEVEL2 = "LEVEL2";
 private static final String LEVEL3 = "LEVEL3";
 private static final String LEVEL4 = "LEVEL4";

private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
        + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT,"
        + LEVEL3 + " TEXT,"
        + LEVEL4 + " TEXT " + ");";

/*private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + LEVEL1 + " TEXT,"
        + LEVEL2 + " TEXT"+");"; */

private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + USERTABLE;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER);
}

//to save score in db according to the level
public void saveData(int level,String score){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues data = new ContentValues();
    switch(level){
        case 1:
            data.put(LEVEL1, score);
            break;
        case 2:
            data.put(LEVEL2,score);
            break;
        case 3:
            data.put(LEVEL3,score);
            break;
        case 4:
            data.put(LEVEL4,score);
            break;
    }
    db.insert(USERTABLE,null,data);
    db.close();
}

//to get score from db
//you can modify this function if you want to get score for a specific level
public HashMap<String,String> getData(){
    HashMap<String,String> scoreMap = new HashMap<>();
    String selectQuery = "SELECT  * FROM " + USERTABLE ;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {

            scoreMap.put(LEVEL1,cursor.getString(cursor.getColumnIndex(LEVEL1)));
            scoreMap.put(LEVEL2,cursor.getString(cursor.getColumnIndex(LEVEL2)));
            scoreMap.put(LEVEL3,cursor.getString(cursor.getColumnIndex(LEVEL3)));
            scoreMap.put(LEVEL4,cursor.getString(cursor.getColumnIndex(LEVEL4)));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return scoreMap;

}

Note: The same also applies to Level 3 and Level 4. Even after Level 4 is unlock, Level 3 also got lock again along with Level 2. The result keep on repeating where it unlock next Level but lock the previous Level all of a sudden
To put SharedPrefences:
 else if (score == 30) {
                /*DBHelper db = new DBHelper(Level1.this);
                db.saveData(1,"30"); */
                AlertDialog.Builder builder = new
 AlertDialog.Builder(Level1.this);
                builder.setTitle("Level 1 Complete!");
                builder.setMessage("You have won! You have unlock level 2! You can proceed to Level 2 or go back.");
                builder.setPositiveButton("Unlock", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        startActivity(intent);
                        finish();
                    }
                });

                builder.setCancelable(false);
                builder.show();
                runTimer.cancel();
            }

Comment: It is because you are adding the score of each level in the new row so other columns except unlocked level have an empty string value.
Comment: Which part am i adding the score of each level? May i know how to solve that part? Sorry, i am new to programming and i received from a guy who helped me along the way
Comment: saveData() method in `DBHelper` class. `db.insert()` method adds new row in database.
Comment: to solve ur problem use shared preferences in android
Comment: Is it ok for you to provide me the solution? i dont know how to do the part. Just one example for a level will do. The rest i will know what to do.
Comment: sure I will give you the overview for implementing shared preference.
Comment: Even though i am using SQL Database, but may i know why to use shared preferences? About the `db.insert()`, what should i do with that in saveData() method?  I should put db.insert(data) after the data.put and before the break?
Comment: shared preference is easy to use and best fit for your purpose.
Answer: Here is an overview of SharedPreference that can be used in our case.
Write Level score to SharedPreference:
Your saveData() method will look like this.
public void saveData(String level, int score) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml",
    Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(level, score); editor.commit();
}

Reading from SharedPreference:
public int getLevelScore(String level) {
SharedPreferences sharedPref = context.getSharedPreferences("score.xml", Context.MODE_PRIVATE);
int levelScore = sharedPref.getInt(level, defaultScoreForLevel);
return levelScore;
}

You can get more information about SharedPreference here.
Edit:
final String level1Score = getLevelScore("LEVEL1");
final String level2Score = getLevelScore("LEVEL2");
final String level3Score = getLevelScore("LEVEL3");
final String level4Score = getLevelScore("LEVEL4");

Call saveData() method whenever user scores.
Comment: Oh, its still possible to use SharedPrefences inside a SQLite DB method? That is something new.
Comment: No...you don't need sql to store such simple data. Why to do such complex things when answer is very simple and easy. Just modify your code to use SharedPrefs.
Comment: Hmm, so i just need to put that code about saveData() in the Level2 and other level activity. And then in LevelPage, it will read SharedPreference?
Comment: Because i need to put that SharedPreference code in the else statement of the score. I will show you my code for that part
Comment: In LevelPage use ` getLevelScore(String level)` method to get the score of any level you want and then perform your check to unlock next level.
Comment: Check above about the Shared Preference part. I should be putting Shared Preference code in the else statament of the score is 30. Instead of calling another public void saveData method()?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148719/discussion-between-mobile-developer-and-murali-prajapati).


What is the slope of the secant line between the points $x=3.1$ And $x=3$ given is $f(x)=\sin(2x)$

Question: Should I replace $x$ in $\sin(2x)$ by $3.1$ and after that will be replaced by $3$?
I tried to compute but the result is $0$. What do I need to do to solve the slope of the secant line of the equation $f(x)=\sin(2x)$ between the points $x=3.1$ and $x=3$.
Please help.
Comment: This is cheating, this is one of the questions in your quiz. AMAUOED
Answer: the slope will be simply $ \frac{sin(6.2) - sin(6)}{3.1 - 1} = 1.9632 $ and not zero
Answer: Slope $m = \dfrac{\sin(2\cdot 3.1) - \sin(2\cdot 3)}{3.1-3}=...$, and you are in radian mode when using the calculator.


Doubt on universal property of quotient vector spaces

Question: We have the following theorem (call it the universal mapping property for quotient spaces): $V,U$ are vector spaces over field $F$, $W⊂V$ a subspace. Then for every linear transformation $t:V→U$ so that $W⊂ker(t)$, there exists a unique linear transformation $T:V/W→U$ so that $T∘p=t$, where $p:V→V/W$ maps elements of $V$ to their cosets, i.e. $p(v)=v+W$.
Does it imply that there is a linear isomorphism from the subspace of linear operators in $\mathcal{L}(V,U)$ whose kernel contains $W$, and the space of linear operators $\mathcal{L}(V/W,U)$?
I guess that the theorem grants an injection from the former to the latter, since, if two functions $t_1$ and $t_2$ belonging to the former give rise to the same element of the latter, i.e., $T_1=T_2$, then we have, from the universal property and the assumption $T_1=T_2$ that $t_1=T_1∘p=T_2∘p=t_2$, which means $t_1=t_2$.
How would you show that instead the inverse map that takes a linear map $\phi$ in $\mathcal{L}(V/W,U)$ and associates to it the map $\psi$ defined by $\psi(v)=\phi(v+W)$ is is the inverse of the previous map?
I guess that one has to show that it takes value in the subspace of linear maps in $\mathcal{L}(V,U)$ whose kernel contains $W$, and that it is injective. Could you help me clarify if this is true and spell the last details out?
Thanks for all the help.
Answer: Just show that the map $L(V/W,U)\to L(V,U)$ that sends $\phi\mapsto \phi\circ p$ is injective, and its image is precisely those elements of $L(V,U)$ whose kernel contains $W$.
Comment: Thanks a lot! So indeed the claim is correct, if I understand correctly.
Comment: Yes it is. (... under character limit)


How many distinct lists of 14 integers $L=\{v_1,\ldots ,v_{14}\}$ exist satisfying $v_i \geq v_{i+1}\geq 0$ and $\sum _{i=1}^{14}(v_i) \leq 54$

Question: I am trying to solve the following problem: I have an ordered list of integers $L = \{v_1,\ldots ,v_{14}\}$ with fourteen elements, satisfying the following two conditions: $v_i \geq v_{i+1}\geq 0$ and $\sum _{i=1}^{14}(v_i) \leq 54$. So in particular every $0\leq v_i \leq 54$. How many different lists $L$ satisfying the conditions exists? Here is some background on the problem.
I am trying to solve something on the computer that boils down to the following problem: find the minimum number $n=p_1^{v_1}\cdot \ldots \cdot p_{k}^{v_k}$ (its prime factorization) such that $S(n)=\frac12\left(\prod _{i=1}^{k}(2v_i+1)+1\right)>1000000$. Now by the fact that $n$ is minimum we see that $v_i \geq v_{i+1}$. If not we would have something like $n = 2\cdot 3^2$ but $S(2\cdot 3^2) = S(2^2 \cdot 3)$ so if some $v_{i} \leq v_{i+1}$ we have not minimized $n$.
Now if we set all $v_i =1$ we get $n=p_1\cdot \ldots \cdot p_k$ and $S(n)=\frac12(3^k+1)>1000000$ or equivalently $3^k \geq 20000000 $ so that $k \geq \log_{3}(2000000) \approx 13.2$. So that for every number $n$ with a prime factorization of at least $14$ distinct primes we see that $S(n) > 1000000$. So, in order to minimize $n$ we look for a number $n$ that has a prime factorization of at most $14$ primes to some power. Also we see that $n$ has a prime factorization that includes not 14 random primes, but the first 14 primes. This is because we can swap primes in the factorization without changing $S(n)$ but this will change $n$, so we choose the smallest primes to minimize $n$. This is the reason the list has $14$ elements.
Now by the minimization of $n$ we see that our minimal $n$ is either equal to or smaller than $p_1\cdot p_2\cdot \ldots p_{14} = 2\cdot 3\cdot \ldots \cdot 43 \approx 1.3\cdot 10^{16}$. Also, for any $n$ we have $n = p_1^{v_1}\cdot \ldots \cdot p_{14}^{v_{14}}> 2^{\sum v_{i}}$ so that again by the minimization of $n$ we have $2^{\sum v_{i}} \leq  1.3\cdot 10^{16}$ implying that $\sum v_i \leq \log_2( 1.3\cdot 10^{16})\approx 53.5$. Thus $\sum v_i \leq 54$.
Thus we have set up the conditions specified at the beginning. Now this is as far as I got, I tried to look at the list $L$ as number base $55$ but this hasn't helped much. Also, I fear that the amount of possible lists is enormous but I am not sure. I am looking for a way to see how many there are and possible an algorithm to generate them in succession. Thanks in advance for any tips or help!
Answer: We consider a smaller case: $x_1 + x_2 + x_3 \le 5$. We look at all the of partitions of $1, 2, 3, 4, 5$ into at most $3$ parts. The possible partitions are:
1 = 1            (1, 0, 0)
2 = 2            (2, 0, 0)
  = 1 + 1        (1, 1, 0)
3 = 3            (3, 0, 0)
  = 2 + 1        (2, 1, 0)
  = 1 + 1 + 1    (1, 1, 1)
4 = 4            (4, 0, 0)
  = 3 + 1        (3, 1, 0)
  = 2 + 2        (2, 2, 0)
  = 2 + 1 + 1    (2, 1, 0)
5 = 5            (5, 0, 0)
  = 4 + 1        (4, 1, 0)
  = 3 + 2        (3, 2, 0)
  = 3 + 1 + 1    (3, 1, 1)
  = 2 + 2 + 1    (2, 2, 1)

Each of these partitions corresponding to an ordered solution for $(x_1, x_2, x_3)$. They also represent all the solutions that exist.

Essentially, what we're looking for in the context of the question is the total number of ways to partition $n$ into at most $14$  parts for $0 \le n \le 54$.
Define the number of ways to partition $n$ into $k$ parts as $p_k(n)$. Then, we need
$$\sum_{n = 0}^{54}\sum_{k = 0}^{14}p_k(n)$$
where $p_0(0) = 1$ and  $p_k(n) = 0$ if either $k \le 0$ or $n \le 0$. From this link on Wikipedia, we have the following recurrence relation for $p_k(n)$:
$$p_k(n) = p_k(n-k) + p_{k-1}(n-1)$$
Below is a PARI-GP script that computes the required number of list using the aforementioned method:
partition(n, k) =
{
    if(n == 0 && k == 0,
        1,
        if(n <= 0 || k <= 0,
            0,
            partition(n - k, k) + partition(n - 1, k - 1)
        )
    )
}

total = 0;
for(n = 0, 54, for(k = 0, 14, total += partition(n, k)));
print(total);

The script gives $1627035$ as the required number of lists.


Changing text with AS3 in a for loop - works for first one, others don't

Question: I have a movieclip called Tab that has two text-fields: named toptxt and bottomtxt. When I create new instances of Tab in a for loop and change the text, only the first instance's text is changed. The rest is the default text in the movieclip.
Here is the code I am using:
for(var i = 0; i < 5; i++){
    var newTab = new Tab();
    newTab.toptxt.text = nameArray[i]; //nameArray is fine
    trace(newTab.toptxt.text); //returns expected value, textfield isn't
    newTab.bottomtxt.text = jobs[i];
    bottom.addChild(newTab); //bottom is a class var.
    newTab.x = i * (newTab.width + 3);
}

Even if I change nameArray[i] to "Test", only the first one works.
This problem does not occur if I don't do it in for loops, however I'd like to do it in a for loop.
Here is a screenshot of the problem: https://i.stack.imgur.com/ByvUq.png
Answer: Pull your declaration of var newTab = new Tab(); outside of the for loop, so your code looks like this:
 var newTab:Tab;
 for(var i:int = 0; i < 5; i++){
    newTab = new Tab();
    newTab.toptxt.text = nameArray[i]; //nameArray is fine
    trace(newTab.toptxt.text); //returns expected value, textfield isn't
    newTab.bottomtxt.text = jobs[i];
    bottom.addChild(newTab); //bottom is a class var.
    newTab.x = i * (newTab.width + 3);
}

Actionscript is becoming confused when you create an instance and assign newTab as a pointer to it, instead of creating a pointer or reference initially, and then creating new instances and adding them to your displayList.
Also, trace your output of nameArray[i] and confirm that those values are correct (i.e. trace(nameArray[i]);. It's possible the data isn't set properly earlier in your code.
Comment: you answer makes little sense, it won't matter where the declaration of the variable is, especially since actionscript does variable hoisting, so any declarations will be at the "top" of the function anyway.
Comment: Thanks! I thought actionscript throws out every variable scoped to the for loop through?
Comment: The variable isn't "thrown away". The reference to the instance is created and assigned to some block of memory. You're creating same-name references and assigning them to different blocks in memory. That's fun for creating objects where you might pass in arguments via the constructor (i.e. new Tab(firstname, jobtitle). But you're using that reference later and losing it because it matches other, identical references. Instead, set the reference outside, and merely update what instance it points to.
Comment: hoisting moves the declaration to the top, during compile, but the issue is about assignment and reference to the specific instance. with hoisting, you could call assignments prior to declaration.


rails invitations controller for events and users

Question: Here's the thing. I have Users and Events and I want to have invitations between them. That is a User can invite another to an Event.
I created an Invitations controller and model. The model looks like this
 user_id: (user being invited), event_id:(event_to_attend), inviter: (sent_the_invite)

I'm building my invitations from the controller by going to /invitations/new and submitting a form but I can't get them to work. They were created before but I made some changes and they don't create, they just say "Invitation has been sent" but no invitation is created in the console or anything.
I know they work because in the console I do
a=User.first
a.invitations.build(event_id: 1, inviter:2)
a.save

And then I can see the invitation and the user_id is the one who created the invitation, a in this case I can see the invitation and can get the user by calling the .invitees method in Event. So the associations work. But I can't create it through the form.
Here's the form
<%= form_for(@invitation) do |f| %>

<% userArray=User.all.select{|u| u.name unless u==current_user }%>
<% names=userArray.map{|u| u.name} %>
<% events=current_user.attended_events.map{|u| u.description} %>

<%= f.label :event %>
<%= f.select :event, events %>

<%= f.label :user %>
<%= f.select :user, names %>

<%= f.submit "Send" %>

<% end %>

I use only name of user and description of event for UX
Here's my invitations controller
class InvitationsController < ApplicationController
    include ApplicationHelper
  def new
    @invitation=Invitation.new
  end
def create
    #Not taking into account, duplicate users, and events with the same name by the same user.
#user being invited
@user=User.find_by(name: params[:invitation][:user])

#event being invited to
@event=Event.find_by(description: params[:invitation][:event])

#Inviter is current user, invitee is @user
@user.invitations.build(event_id: @event.id, inviter: current_user.id)

#Event not in user.attended_events
if !(@user.attended_events.where(id: @event.id) || \
    @user.invitations.where("firstname.lastname@example.com AND firstname.lastname@example.com") )

    flash.now[:danger]="User is already going to the event"
    render 'foo'
    #render 'new'

elsif @user.save!
    flash[:success]="Invitation was SENT!"
    redirect_to new_invitation_path
else
    flash.now[:danger]="Please select both options"
    render 'foobar'
    #render 'new'
end
  end

Answer: Your making it quite a bit harder on yourself than need be.
You can start by using the rails collection helpers to clean up the form:
<%= form_for(@invitation) do |f| %>

    <%= f.label :event_id %>
    <%= f.collection_select :event_id, Event.all, :id, :name, prompt: true %>

    <%= f.label :user_id %>
    <%= f.collection_select :user_id, User.where.not(id: @invitation.inviter.id), :id, :name, prompt: true %>

  <%= f.submit %>
<% end %>

This assumes that you have a current_user method and that your Event and User have a name attribute that you want to use for the label (you can use whatever attribute you want). The actual value used is the ID of the associated record.
Note that we use the param key event_id and user_id. Using event  would cause an error since the setter expects an actual Event instance and not just an ID.
You would handle this in your controller like so:
class InvitationsController < ActiveRecord::Base
  def new
    @invitation = current_user.invitations.new
  end

  def create
    @invitation = current_user.invitations.new(invitation_params)
    @invitation.save
    respond_with(@invitation)
  end

  private
    def invitation_params
      params.require(:invitation).permit(:event_id, :user_id)
    end
end

This does not handle the issue of creating duplicate invitations yet through. The Rails way of handling this is by adding a uniqueness validation to the model:
class Invitation < ActiveRecord::Base
  belongs_to :user
  belongs_to :invitation
  belongs_to :inviter, class_name: 'User'
  validates_uniqueness_of :user_id,
    scope: 'invitation_id',
    message: 'is already going to the event'
end

This will cause @invitation.save to fail if the user has already been invited and render the new view again.
Due to the possibility of race conditions you should back the validation with a database index.
# generate with
# $ rails g migration AddUniqueIndexToInvitation
class AddUniqueIndexToInvitation < ActiveRecord::Migration
  def change
    add_index :invitations, [:user_id, :event_id], unique: true
  end
end


Trapezoid, ratio between two bases.

Question: There is a point $P$ inside the isosceles trapezoid $ABCD$ such that $PA=1$, $PB=2$, $PC=3$ and $PD=4$. What is $\frac{BC}{AD}$?

My attempt:
I applied the cosine rule on those four triangles knowing that the sum of the angles at point $P$ is $360$ degrees but I ended up with too many unknowns and I stuck there.
Any help would be highly appreciated.
Comment: @Peter: My approach was to coordinatize $A=(-u,0)$, $B=(-v,h)$, $C=(v,h)$, $D=(u,0)$, and then to write relations based on the distance formula. (When the distances from $P$ to $A$, $B$, $C$, $D$ are, respectively, $a$, $b$, $c$, $d$, then ratio $|BC|/|AD|$ turns out to be $(b^2-c^2)/(a^2-d^2)$; for the problem as given, this evaluates to $1/3$.)
Comment: @Blue, as hinted by the expression you obtained, a quick geometric solution can be found by drawing perpendicular line through P meeting the parallel sides, and applying Pythagoras in four right triangles.
Comment: The answer turns out to be rather nice. (Even for an arbitrary proportion of distances, the final ratio is uncomplicated.) I don't (yet) have a comparably-nice derivation of it, however.
Comment: @Blue, I've come to the same conclusion and I think the ration is 1:3 but how? :)
Answer: Taking @Blue's expression as hint, following geometric solution was found.

Draw $MN$ through $P$ perpendicular to the parallel sides as in the diagram. Then applying Pythagoras in the four right triangles, it can be shown $PD^2- PA^2 =$ $DM^2 - AM^2$ and $PC^2- PB^2 = CN^2 - BN^2$. Taking ratio,
$$\frac{PC^2- PB^2}{PD^2- PA^2} = \frac{CN+BN}{DM+AM} \cdot \frac{CN-BN}{DM-AM}=\frac{BC}{AD} \cdot \frac{CN-BN}{DM-AM}$$
Now reflect the side $AB$ in $MN$ to get $A'B'$. Clearly $A'B'CD$ is a parallelogram with equal opposite sides $B'C=A'D$. As $B'C=CN-B'N=CN-BN$, similarly, $A'D=DM-A'M=DM-AM$. Their ratio is $1$ and we have
$$\boxed{\frac{BC}{AD} = \frac{PC^2- PB^2}{PD^2- PA^2}}$$
This result holds even when say, $\triangle BPC$ is obtuse; same proof works.
Answer:
Hint: My drawing shows that $\angle APD=5 \angle BPC$
Also we have:
$1^2+2^2-2\times 1\times 2 \cos BPA=3^2+4^2\2\times 3\times 4 \cos CPD$
And the third relation is:
$\angle BPA+\angle CPD= 360 - 4\angle BPC$
Find angle BPC, then angle APD, these woul give you measure of BC and AD. The ratio must be $\frac 13$.

Trapezoid, ratio between two bases.


Python, Pandas: join dataframes on timestamp and offset

Question: Actually two questions, but let's try to explain.
I got two data sources (e.g. dataframes). One contains the GPS coordinates and the timestamp of a driven track. The other one contains specific points of interest, given by an offset in time - but without the GPS coordinate. The task is to find the GPS coordinates for the points of interests.
Here's what I got. The dataframe with the GPS coordinates is resampled to 1sec intervals and missing values are interpolated in a linear manner:
df_resampled.head()

With this output:
Time, LongitudeDegrees, LatitudeDegrees, DistanceMeters, AltitudeMeters

2017-08-24 13:33:46, 15.457636, 47.047332, 0.0, 348.600006
2017-08-24 13:33:47, 15.457668, 47.047288, 0.0, 348.600006
2017-08-24 13:33:48, 15.457699, 47.047244, 0.0, 348.600006
2017-08-24 13:33:49, 15.457973, 47.047136, 0.0, 348.600006

Remark: The types are all float while the index is Numpy.dtype (datetime). Conversion and Resampling was done by:
# convert numeric types first
df = df.apply(pd.to_numeric, errors='ignore')

# convert timestamp to datetime and set the index
df['Time'] = pd.to_datetime(df['Time'])
df.set_index('Time', inplace=True)

# resample to seconds and linear fill of missing values
df_downscaled = df.resample('S').mean()
df_resampled = df_downscaled.interpolate(method='linear')

The other dataframe contains the points of interest and no timestamp but a time-offset:
df_poi.head()

giving this output:
index, time_offset, value

0, 00:25, 60
1, 01:18, 60
2, 01:30, 100
3, 01:55, 100
4, 02:16, 100

Question & Task: But now I'm stuck. I was thinking to convert the time_offset column of the second dataframe to a period or datetime type and add this to the first timestamp (start_time) of the first dataframe.
But a) I have no idea how to convert the string of format mm:ss (Minutes:Seconds) to a datetime-offset (or period) and add it to another timestamp.
The start_time to which all offsets have to be added, would be this:
start_time = df_resampled.index[0]

Once the offset is converted to a real timestamp, I would join the second dataframe with the first one on the timestamp column.
Answer: pd.to_timedelta can convert strings in HH:MM:SS format to timedelta64s.
Since your strings are in MM:SS format, you could use
df_poi['time_offset'] = pd.to_timedelta('00:' + df_poi['time_offset'])

to convert them to timedelta64s. (The ('00:' + df_poi['time_offset']) adds
00: to each string in df_poi['time_offset'] to form a new string in
HH:MM:SS format.)
You can add start to df_poi['time_offset']:
start = df.index[0]
df_poi['Time'] = df_poi['time_offset'] + start

Now you can merge the two DataFrames:
result = pd.merge(df, df_poi, how='right', left_index=True, right_on='Time')

import pandas as pd
import numpy as np
np.random.seed(2017)
N, M = 1000, 5
df = pd.DataFrame({'Time':pd.date_range('2017-8-24 13:33:46', periods=N, freq='S'),
                   'Long':np.random.uniform(0, 360, size=N),
                   'Lat':np.random.uniform(-90, 90, size=N),})
df = df.set_index(['Time'])

df_poi = pd.DataFrame({'time_offset':['00:25', '01:18', '01:30', '01:55', '02:16'],
                       'value':np.random.randint(100, size=M)})

df_poi['time_offset'] = pd.to_timedelta('00:' + df_poi['time_offset'])
start = df.index[0]
df_poi['Time'] = df_poi['time_offset'] + start
result = pd.merge(df, df_poi, how='right', left_index=True, right_on='Time')

yields
         Lat        Long time_offset  value                Time
0 -19.851775  276.063876    00:00:25     28 2017-08-24 13:34:11
1  22.399545   61.956233    00:01:18     68 2017-08-24 13:35:04
2  35.472442  275.165153    00:01:30     56 2017-08-24 13:35:16
3 -60.588755   91.961901    00:01:55      2 2017-08-24 13:35:41
4  34.339641    4.033255    00:02:16     75 2017-08-24 13:36:02

Comment: I used str.split and converted the duration from minutes and seconds to seconds only. Then I added the start_time with the offset. You solution is smarter though.


Change the e-mail value during user registration ?  form_set_value()

Question: I have a custom module (entitled ta_module) : in the user registration form, it hides the e-mail field, and add a custom field where user have to enter what's before @ and then choose his e-mail domain name between the one proposed in a list next to it.
Here's the code :
<?php

/**
 * Implementation of hook_form_alter()
 */
function ta_module_form_alter(&$form, &$form_state, $form_id) {

   // If the form is the user_register form
    if ($form_id == 'user_register_form') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_ta_module_user_validate');
        // Hide the email address field
        $form['account']['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['account']['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 35,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#title' => 'Domaine',
      '#title_display' => 'before',
      '#options' => array(
              // These are the possible email address domains
              'myentreprise.net' => '@myentreprise.net',
              'myentreprise.com' => '@myentreprise.com',
            ),
      '#default_value' => 'myentreprise.net',
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _ta_module_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['complete form']['account']['mail']['#value'] = $form_state['input']['mail_first'] . '@' . $form_state['input']['mail_last'];
    }
}

(see This Q/A for more infos).
All appear quite brightly, but when the user click on "create a new account", the user is created but the last function of my module doesn't work : the e-mail finally saved is the default value (something like email@example.com) instead of the two pieces joined together...
HOW TO FIX THIS : Thus how to assign to mail the value of mail-first + mail-last ?
/!\ I'm working on Drupal 7, so I think it's an issue of uncorrect variables...
Thks for reading !  ;)
Answer: If you need to set the value for the form field used to contain the email address, then you should use code similar to the following one:
function _ta_module_user_validate(&$form, &$form_state) {
  if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
    form_set_value($form['account']['mail'], $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'], $form_state);
  }
}

As an example of how form_set_value() is used, see system_site_information_settings_validate(), which contains the following code:
// Check for empty front page path.
if (empty($form_state['values']['site_frontpage'])) {
  // Set to default "node".
  form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
}
else {
  // Get the normal path of the front page.
  form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
}

Answer: Instead of
$form_state['complete form']['account']['mail']['#value'] = $form_state['input']['mail_first'] . '@' . $form_state['input']['mail_last'];

Try using the form_set_value() function.  Documentation says:
Use this function to change the submitted value of a form element in a form validation function, so that the changed value persists in $form_state through to the submission handlers.
Comment: Please see the form_set_value() documentation as I've never had to use the function myself.  And don't forget to concatenate your '@' sign to the email string.
Comment: Ok, thks! So I put something like :

`form_set_value($form_state['mail'], $form_state['input']['mail_first'].$form_state['input']['mail_last'], $form_state);`

OR

`form_set_value($element['#mail'], $form_state['input']['mail_first'].$form_state['input']['mail_last'], $form_state);`

???
Comment: I've tried both after reading the documentation. But the two times I got the following error :
Notice : Undefined variable: element dans _`_ta_module_user_validate() (line 49 in /**DRUPAL_ROOT**/sites/all/modules/ta_module/ta_module.module).
Recoverable fatal error : Argument 2 passed to drupal_array_set_nested_value() must be an array, null given, called in /homepages/19/d362299801/htdocs/technomaide/includes/form.inc on line 2393 and defined dans drupal_array_set_nested_value() (ligne 6263 dans /homepages/19/d362299801/htdocs/technomaide/includes/common.inc).`_


Drush custom command not found in context of running --root option

Question: Drush 8. Have the custom module with the custom command.
Call drush custom-command works as expected.
Call drush --root=sites/subsite custom-command thiggers the error:
The drush command 'custom-command' could not be found.
How to call the drush command in the context of the subsite?
Comment: Is the custom module enabled in the sub site?
Comment: Drush 8 on a Drupal 8? Better provide Drush 9 commands from inside your module's src/Commands directory.
Comment: Drush 9 handle that pretty good, but there's no possibility to run the @sites alias.
Answer: To call a command on a certain instance of a multisite you are supposed to pass the -l option. Also be sure that the custom module that provides the custom command is enabled on the multisite instance you are trying to call that command on.
$ drush custom-command -l subsite


Draw rectangles on canvas by reading JSON

Question: I'm trying to draw rectangles on a HTML5 canvas. I managed to draw on the canvas but I need to do it dynamically.
x, y: coordinates of the position of the rectangle in the canvas-element.
w: width of the rectangle.
h: height of the rectangle.
f: If true, the rectangle filled without a border. If false the rectangle has a border but no filling.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json = [{
    "x": "50",
    "y": "50",
    "w": "100",
    "h": "50",
    "f": "true"
  },
  {
    "x": "50",
    "y": "150",
    "w": "100",
    "h": "50",
    "f": "false"
  }
];

context.beginPath();
for (var i in json) {
  context.lineTo(json[i].x, json[i].y, json[i].w, json[i].h, json[i].f)
}
<canvas id="c"></canvas>
Comment: That being said, [`lineTo()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineTo) expects only X and Y coordinates. What are you expecting `w`, `h` and `f` to do?
Comment: We need more context here, please. Can you edit the question to include a description of what you're trying to achieve, and also why your current code doesn't meet your needs.
Comment: Thanks for editing, I added an answer for you below
Answer: As you're attempting to draw rectangles on your canvas, it would make far more sense to use the strokeRect() and fillRect() methods.
Note that your f property will determine which one of these methods are invoked. I would also suggest you convert the f property value to be a boolean, instead of a string.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json = [{x: "50", y: "50", w: "100", h: "50", f: "true" }, { x: "50", y: "150", w: "100", h: "50", f: "false" }];

context.canvas.width = 200;
context.canvas.height = 250;

json.forEach(shape => {
  context[shape.f === 'true' ? 'fillRect' : 'strokeRect'](shape.x, shape.y, shape.w, shape.h);
});
<canvas id="c"></canvas>
Comment: Thank you so much! I have an exam tomorrow and just couldnt figure this exercise out. How can I change the colours of the rectangle to red and the stroke width to 2px?

Also the last part of the exercise  was to create a handlebar-Template. The template is supposed to put out the x-y-postions of any number of rectangles that are saved to the variable "rects". I suppose rects is meant to include all of the data in the json file.

I hope I could explain it in a way its understandable.
Comment: You can use [`fillStyle` and `strokeStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) to set the colour of the fill or the border. I'd suggest starting a new question about the handlebars template as have no experience there.


Using the IVP definition of $\cos$ and $\sin$, how can we show that $\cos^2(x)+\sin^2(x) = 1$ without any "magic"?

Question: One way to define the exponential, hyperbolic and circular functions is to assert that they're the unique solutions to certain IVP systems:
The exponential function:
$$\exp'(x) = \exp(x), \qquad \exp(0) = 1$$
Hyperbolic functions:
$$\cosh'(x) = \sinh(x)$$
$$\sinh'(x) = \cosh(x)$$
$$\cosh(0) = 1$$
$$\sinh(0) = 0$$
The circular functions:
$$\cos'(x) = -\sin(x)$$
$$\sin'(x) = \cos(x)$$
$$\cos(0) = 1$$
$$\sin(0) = 0$$

Question. Using the IVP definition of $\cos$ and $\sin$, how can we show that $\cos^2(x)+\sin^2(x) = 1$?
I'm looking for a satisfying proof that I can present to young people, so:

no complex numbers, and
no power series, and, more generally
no "magic"!

In fact, the closer the proof is to being "just plain algebra", the better.

Motivation.
There's a geometric way of defining the circular functions: first, position yourself at $(1,0)$ on the unit circle. Then start walking anticlockwise at unit speed. It follows that if the time elapsed is $t$, your $x$-coordinate will be $\cos t$ and your $y$-coordinate will be $\sin t$.
The above information can be organized into four statements:

We walk on the unit circle centered at the origin.
We position ourselves at $(1,0)$ to begin with.
We walk at unit speed.
We walk anticlockwise.

These can be formalized as follows:

$\cos^2 t + \sin^2 t = 1$
$\cos(0) = 1, \sin(0) = 0$
$(\cos't)^2+(\sin't)^2 = 1$
$\sin'(0) > 0$

Now conditions 2 and 4 follow easily from the IVP definition. Furthermore, if we can show 1, then 3 follows easily. But, I haven't been able to show 1 in a "non-magic way" e.g. without complex numbers.
Comment: If you know that $\cos'=-\sin$ then you just have to differentiate the function $\cos^2+\sin^2$,see it is constant, etc. Is this too magical?
Comment: And the other 10%, like you and me, Goblin, will remember you for the rest of their lives for giving a definition that's much, much easier to work with and approximate to a formalization.
Comment: @Tryss: $\cos(x+a)$ is a solution to the same differential equation as $\cos(x),\sin(x)$ but with different initial values. Consequently $\cos(x+a)=A\cos(x)+B\sin(x)$ for some $A,B$ which can be found by checking initial values.
Comment: @GitGud, a cool feature of your approach to showing $\cos^2+\sin^2=1$ is that, if we try it on the hyperbolic functions, it fails to work, but more to the point its "obvious" why it fails to work, namely that there's a negative missing, which allows us to conjecture $\cosh^2-\sinh^2 = 1$ as the correct formula, and this is easily verified. So your method actually "teaches" us something that we may not have known previously (if we're e.g. high school students.)
Comment: @GitGud, no! That's wonderful.
Comment: but I don't see the point trying to define $\cos,\sin$ non-geometrically... you want to make your students your ennemies ? 90% of them will hate you... even you (the teacher), you have some difficulties defining $\cos,\sin$ this way !!!
Comment: @GitGud : how is that much easier to work with? Can you give a formula for $\cos(a+b)$ starting from this definition?
Comment: @GitGud, thank you for the kind words :)
Comment: @Semiclassical, nice approach. I just used this to check that $\exp(x+y)=\exp(x)\exp(y)$ and it seems to work. I wonder if we can use this approach to say anything interesting about $\cos(xy)$?
Comment: @Semiclassical, do you know what the name of the theorem is that tells us that the vector space of solutions to the system $c' = -s, s' = c$ is two dimensional?
Answer: Since $\frac{d}{dx}\sin(x)=\cos(x)$ and $\frac{d}{dx}\cos(x)=-\sin(x)$ we have
$$ \frac{d}{dx}\left(\sin^2(x)+\cos^2(x)\right) = \sin(x)\cos(x)-\sin(x)\cos(x) = 0 $$
hence $\sin^2(x)+\cos^2(x)$ is a constant function, equal to $\sin^2(0)+\cos^2(0)=1$.
This easily gives 1.,2. and 3. and 4..
Comment: I don't know why it took my so long to accept this. Seems pretty clear!