How to add css immediately (display:none) to a block created through hook?

Question: I created a block through drupal hook_block_info (and hook_block_view, but this doesn't really matter)
function mymodule_block_info() {
  $blocks['menu_mobile'] = array(
    'info' => t('Mobile Menu'),
    );
  return $blocks;
}

I need it to be hidden initially and then to show on webpage resize/mobile.
I did this by applying a display:none to css and the media rule
@media screen and (max-width: 768px)

It works. Almost Perfectly. The problem is that, at the very beginning of webpage loading, the block is visible and, for maybe a second, it shows on its webpage, then the display:none does its work hiding it. It is annoying. I saw here some properties of the array to be returned by the hook, but none really fits my case. For example, enabling/disabling hides the block, but i don't really know how or when to show it again.
https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7

So, how i can have the block initially hidden, or fasten the display:none (that is contained in the style.css of my custom theme)?
Answer: A block can have a content element when created in code. This content element can be raw HTML or a drupal render array. If you use raw HTML for your block you can just put  directly into your block output.
Or if you use a render array you can do something similar with the #attached key on the render array. This is outlined in the API usage of drupal.org and a comment provides an example:
$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

Obviously the render array approach is a cleaner, more elegant solution. You can even have the CSS inline when using #attached.
Comment: Good solutions! Unfortunately, yet too slow and the issue is still there.


React Function undefined at onClick although it's bound?

Question: I have this function:
  deleteTag() {
    // this.data.tags.pop();
    console.log("I will delete a tag");
  }

I bind it in the constructor:
this.deleteTag = this.deleteTag.bind(this);

But when I try to do this:
render() {
    const renderTags = this.state.data.tags.map(function(tag,i){
      return  this.deleteTag()}>{tag}
    });

   return (
 {renderTags}
 );
}

I get:

Uncaught TypeError: Cannot read property 'deleteTag' of undefined
      at onClick (bundle.js:46275)
      at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4594)
      at executeDispatch (bundle.js:4394)
      at Object.executeDispatchesInOrder (bundle.js:4417)
      at executeDispatchesAndRelease (bundle.js:3847)
      at executeDispatchesAndReleaseTopLevel (bundle.js:3858)
      at Array.forEach ()
      at forEachAccumulated (bundle.js:4694)
      at Object.processEventQueue (bundle.js:4063)
      at runEventQueueInBatch (bundle.js:4723)

I'm sure it's something silly, but I can't figure it out!
Answer: That's becuase the function given to map is not bound. You could use an arrow function instead, and this will be what you expect.
const renderTags = this.state.data.tags.map((tag,i) => {
  return  this.deleteTag()}>{tag}
});

Comment: omg so silly of me! thanks a lot!!! (I gotta wait 12 minutes before picking the answer)


Pegar o valor de uma input pelo name

Question: Olá,
Tenho a seguinte função:
function capturar($string, $start, $end) {
    $str = explode($start, $string);
    $str = explode($end, $str[1]);
    return $str[0];
}

Eu uso ela com o cURL, para pegar o valor de um input.
Exemplo de uso:
$pagina = curl("http://example.com");
$texto = capturar($pagina, 'name="texto"', '"');
echo $texto;

Aí no caso, o PHP iria retornar o valor do input ou qualquer tag que tenha o name de texto, até aí tudo bem, mas a página que o cURL acessa tem o seguinte input:
<input value="João Lima" name="texto" id="texto"/>

Como eu iria pegar o valor do input nesta ordem?
Obrigado desde já.

Atual código que eu estou usando:
<?php
function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/test.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/test.txt');
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
$array = [];
preg_match('/value="([^"]+)"/e', curl('http://example.com'), $array);
var_dump($array);
echo '

'.curl('http://example.com');

Nesta página tem outros inputs, mas tem um input com o value de 11.5, 12, 12.5.
Answer: Acho que o ideal é usar o próprio XPath, nativo do PHP.

Neste caso utiliza o //input[@name="texto"] que para obter o input que contem o atributo de name de texto.
Dessa forma ficaria como:
$html = curl("http://example.com");

$DOM = new DOMDocument;
$DOM->loadHTML($html);
$XPath = new DomXPath($DOM);

// Procura pelo elemento:
$inputs = $XPath->query('//input[@name="texto"]');

// Para cada //input[@name="texto"] (já que pode haver mais de um) e exibe o `value`.
foreach($inputs as $_ => $input){
    echo $input->getAttribute('value');
}

Answer: Se for um único input, isso aqui deve resolver:
$conteudo = '<input value="João Lima" name="texto" id="texto"/>';
$array = [];
preg_match('/value="([^"]+)"/e',$conteudo,$array);
var_dump($array);

Este é apenas um exemplo, deverá ser adaptado. O $conteudo deverá ser o retorno da tua requisição feita com CURL.
Comment: E quando o `value` conter números? Coloquei um input com o `value` de `11.5, 12, 12.5` e não retornou o `value` na array.
Comment: Tem certeza, pois testei com esses valores e funcionou. Ta fazendo dessa forma: value="11.5" ?
Comment: Sim, eu testei com esses valores só na string, depois eu fui testar com o cURL, mas ele não retorna.

Pegar o valor de uma input pelo name


How to determine $ \int \sec^{\frac{1}{3}}(x) dx $?

Question: How to determine $$ \int \sec^{\frac{1}{3}}(x) dx ?$$

An attempt:
$$ \int \frac{1}{\cos^{1/3}(x)}dx = \int \frac{\sin^{2}(x) + \cos^{2}(x)}{\cos^{1/3}(x)}dx$$
$$ = \int \frac{\sin^{2}(x)}{\cos^{1/3}(x)}dx + \int \cos^{2/3}(x) \cos(x) dx $$
Let $ A=\int \frac{\sin^{2}(x)}{\cos^{1/3}(x)}dx $, we focus on $\int \cos^{2/3}(x) \cos(x) dx$.
$$\int \underbrace{\cos^{2/3}(x)}_{u} \underbrace{\cos(x) dx}_{dv} = \sin(x) \cos^{2/3}(x) + (2/3) \underbrace{\int \frac{\sin^{2}(x)}{\cos^{1/3}(x)}dx }_{A}  $$
We encounter $A$ once more.

How to continue? Or is there a better approach? Thanks.
The hint says use Trig. substitution two times
Comment: According to Wolfram Alpha the primitive isn't elementary.
Comment: @Martín-BlasPérezPinilla This appeared in a quiz. But i also suspect that it may meant to be definite integral? In $ [0, 0.5\pi]$
Answer: Your question is equivalent to finding a primitive for $\sin(x)^{-1/3}$, or to finding a primitive for $\frac{x^{-1/3}}{\sqrt{1-x^2}}$. The latter is of course a hypergeometric function related to elliptic integrals:
$$ \int_{0}^{z}\frac{x^{-1/3}}{\sqrt{1-x^2}}\,dx = z^{2/3}\sum_{n\geq 0}\frac{3\binom{2n}{n}}{(6n+2)4^n}z^{2n}=\frac{3}{2}z^{2/3}\cdot{}_2 F_1\left(\tfrac{1}{3},\tfrac{1}{2};\tfrac{4}{3};z^2\right).$$
Some special values can be found through Euler's Beta function. For instance:
$$\begin{eqnarray*} \int_{0}^{\pi/2}\cos(x)^{-1/3}\,dx &=& \int_{0}^{\pi/2}\sin(x)^{-1/3}\,dx = \int_{0}^{1}\frac{dz}{z^{1/3}\sqrt{1-z^2}}=\frac{1}{2}\int_{0}^{1}u^{-2/3}(1-u)^{-1/2}\,du\\&=&\frac{1}{2}B\left(\tfrac{1}{3},\tfrac{1}{2}\right)=\frac{\Gamma\left(\tfrac{1}{3}\right)\,\Gamma\left(\tfrac{1}{2}\right)}{2\,\Gamma\left(\tfrac{5}{6}\right)}=\sqrt{\frac{\Gamma\left(\tfrac{1}{6}\right)^3}{2^{11/3}\sqrt{3\pi}}}=\frac{2^{1/2}3^{1/4}\pi}{\text{AGM}(1+\sqrt{3},\sqrt{8})}.\end{eqnarray*} $$
The representation through the AGM mean gives this tight inequality, for instance:
$$ \int_{0}^{\pi/2}\cos(x)^{-1/3}\,dx \leq \pi\sqrt{\frac{\sqrt{3}}{\sqrt{2}+\sqrt{6}}}.$$
Comment: Thanks for the answer. But the context should be within 1st year Calculus..
Comment: The hint says use trig.subs two times..
Comment: @Arief: hint or not, that is a hypergeometric function and not an elementary function.
Comment: By this you mean we cannot find exact solution..?
Comment: Apparently, this problem is a bonus problem and meant to test how far the students have gone..
Comment: A hypergeometric function is an exact solution, but not an elementary one.


How to make local /etc/group take priority over LDAP when names collide?

Question: We have a working LDAP set up. However we hit a problem recently due to some user names and group names existing both in the local files and in LDAP. Specifically the apache user and group existed both in:

/etc/passwd and /etc/group
LDAP as both user and group

After a recent yum update (CentOS 5), it appeared that the group ID of the process had changed from the value in /etc/group to the value in LDAP (while the user ID remained the ID from /etc/passwd). As some of the files needed by httpd were owned by user root, with group apache (from /etc/group) but not world readable, this caused problems.
Note that we already have nss_initgroups_ignoreusers apache,... in both /etc/ldap.conf and /etc/openldap/ldap.conf. Also, in /etc/nsswitch.conf we have
passwd:     files ldap
group:     files ldap
shadow:     files ldap

and the rest of the normal bits and bobs.
So if a name exists in both LDAP and the local files, is there a way to ensure that the ID from the local files will take precedence over the ID in LDAP?
Answer: I don't know if it's a typo in your example but the group database is called group and not groups.
You should be able to force the search to stop after a successful lookup e.g.
passwd:    files [SUCCESS=return] ldap
group:     files [SUCCESS=return] ldap

The above should be the deafult action anyway so you should confirm that what you are looking for really is in the files.

NOTES
         Within each process that uses nsswitch.conf, the entire  file
  is  read
         only  once;  if  the  file  is later changed, the process will
  continue
         using the old configuration.
Comment: The groups was a typo, corrected in question now. Will look into this in more detail tomorrow at work.
Comment: I also had to clear the **nscd** cache.  This didn't happen during service restart, so I had to do it manually: `sudo mv /var/cache/nscd/passwd{,.old}` .


residual vs. QQ-plot in multiple regression

Question: I'm working on a Kaggle multiple regression tutorial competition and inspecting plots of my residuals. I followed a suggestion and log transformed several independent variables and the dependent variable. These are the plots I got after fitting a Ridge regression model (sample size is 1500):

I'm trying to determine how to interpret these plots, and to better understand which is useful for which purposes. I believe that the first two plots illustrate that the regression assumptions of linearity, additivity, and homoscedasticity are not violated, although at lower prices my model tends to underestimate. I think that the pattern in the QQ-plot shows a distribution more heavily tailed than normal, so the variance is higher than expected for a normal distribution, and so the normality of error assumption is violated. Is this a correct assessment? And if my goal is prediction rather than inference, should I be concerned with this QQ-plot? I also did not divide the residuals by their standard deviation because I could not find enough information about when this step is necessary.
Comment: @NIck With shrinkage (using ridge regression) you would expect the residual plot would not necessarily be *quite* flat (though I'd have thought it would go the other way)
Comment: To me the summary line on the first graph is tilted. Is that an illusion? Should be residual = 0.
Comment: Thanks, but syntax in unspecified software doesn't explain to most people how the line was calculated. Also, although it is clear from plain regression that residuals have mean zero, I am asking openly whether that is also true for the ridge flavour.
Comment: It does seem slightly tilted. Is this a concern I should address in any particular way to build a more accurate model?
Comment: Tell us how it is produced! (Someone familiar with ridge regression may be able to explain that it need  not be flat -- I have never used it.)
Comment: The plot or the model? The plot was just `sns.regplot(ypred,residuals, line_kws={'color': 'red'});`, however, I did a fair amount of feature engineering in a Jupyter notebook for the model, and then did nested cross-validation using sklearn with `cross_val_predict` and `RidgeCV`.
Comment: Sorry, here's the documentation for the function from Python's Seaborn library: https://seaborn.pydata.org/generated/seaborn.regplot.html. Although I learned about ridge regression in my ML class a while ago, I'm not confident enough in my understanding to answer that.
Comment: Sorry, I can't read that, but someone else may be able to push it further.
Answer: Yes.  To me, your top plots look pretty good.  Your qq-plot shows clear non-normality / fat tails.  The histogram / density plot looks pretty symmetrical, it's just that you have 'too many' residuals that are too far from the predicted line.  This means the kurtosis is too large, not that the residual variance is.  The variance is a parameter of a normal distribution to be fitted, so it cannot be too large.
The effect of non-normality is somewhat complex.  When you want to make inferences, it can mean your p-values are wrong, but you appear to have a good amount of data, so the central limit theorem may kick in enough that it doesn't matter.  If you only care about predicted means, it shouldn't have much impact.  But I suspect it is likely you will want to know something about the prediction intervals as well as the means.  Standard prediction intervals are based much more closely on the idea that the conditional distribution is normal than the confidence intervals.  For example, the central limit theorem cannot save your prediction intervals no matter how much data you have.  You might see if there is a suitable fat-tailed distribution (e.g., a low df t-distribution) that is a good fit for your residuals that you could use for forming prediction intervals.
Comment: @Jake, maybe my answer here: [Linear regression prediction interval](https://stats.stackexchange.com/a/33642/7290) might help.
Comment: Thanks very much for your answer. I edited my question to include sample size (1500). My primary goal is to submit the lowest RMSE value I can with a predictive model in order to rank well in a Kaggle competition. I haven't really learned about prediction intervals, so I'm not quite sure how/if there's a way to use them in order to assess and build a more accurate model. I do know about confidence intervals which appear to be fairly related, and don't immediately see a value for my purpose, but I'm also quite new to this.
Comment: +1 The central limit theorem may give you accurate type I error rate, but it won't help with power; on the other hand I doubt power is a prime consideration here (it would be prediction for this rather than testing hypotheses), but I think it would also affect size of confidence intervals (making them wider than needed? I am a bit overtired so I may have flipped that). Even if we supposed this was (say) a symmetric mixture I don't think that will change much if you're trying to minimize MSE. Out of sample selection and tuning on your criterion should still get you to about the right place.


Obtaining posteriors for multivariate Normal mixture models

Question: So I want to fit a mixture model
$$f(y) = \pi_1 f_1 (y) + \pi_2 f_2 (y)$$
where $\pi_k = P(S = k)$ and $S_i$ is a latent unobserved variable.
I assume that, conditional on $S=k$, we have the model
$$y_i = \mu_k + \beta_k x_i + \epsilon_i$$
where $\epsilon_i \sim N_p (0, \Sigma_k)$.
My goal is to estimate parameters $\mu_k, \beta_k, \Sigma_k, \pi_k$ for each $k$.

Firstly, As I understand it, under this model we have likelihood function
$$L(\theta |y) = \prod_i \left( \pi_1 \phi_{1,p} \left(y_i-\mu_1 -\beta_1 x_i\right) + (1-\pi_1) \phi_{2,p} \left(y_i-\mu_2 -\beta_2 x_i\right)
   \right)$$
where $\phi_{k,p} \sim N_p(0, \Sigma_k)$.

Secondly, in order to obtain point estimates of the parameters in a Bayesian framework, I need to obtain a posterior sample from the posterior distribution
$$p(\mu, \beta, \Sigma, \pi | y)$$
But as this is difficult, an alternative would be to use Gibbs sampling with posteriors
$$p(\mu |  \beta, \Sigma, \pi , y)$$
$$p(\beta |  \mu, \Sigma, \pi , y)$$
$$p(\Sigma |  \mu, \beta, \pi , y)$$
$$p(\pi |  \mu, \Sigma, \beta , y)$$
What I don't understand, is how to get from the given model equation and likelihood function to those posteriors. Once I have those posteriors, I am confident I can impliment Gibbs sampling.
Since my likelihood is not multivariate normal, it is a mixture of multivariate normals, I am unsure how to proceed, as there are no conjugates listed on the Wikipedia page for mixture distributions. Any help/advice is much appreciated!
Answer: You are quite correct there is no conjugate for the mixture model.
One way you can proceed.  You have $N$ data points of $K$ dimensional multivariate data $X$ ($N \times K$) (I'm assuming you already think that there are 2 components?  I'll call it $M$ here to be a bit more general.).  You define a latent parameter $Z$ ($N \times M$) that is an assignment of each data point into one of the $M$ components. Initialize your $\mu$ ($M \times K$), $\Sigma$  ($M \times K \times K$)and $\pi$ ($M \times K$).  I'm sorry, I didn't quite understand what purpose $\beta$ serves.
The basic idea is you assign each data point to one of the components, and conditional on these assignments, you can sample parameters for each of the $M$ components using the data assigned to it using conditional posteriors for a single multivariate normal.
Each Gibbs iteration consists of 2 steps:
1)  Re-assign (re-sample) component membership, conditional on current parameter values
using the probability that the $j$th data is assigned into the $m$th component:
$p(z_{jm} = 1) = \frac{\pi_m N(x_j | \mu_m, \Sigma_m)}{\sum_l \pi_l N(x_j | \mu_l, \Sigma_l)}$,
where $N(..)$ stands for the normal density.
2)  Conditional on component membership, sample parameters for each component, using the conditional posteriors as you wrote above, except with it also being conditional on ONLY the data that are currently assigned to $m$th component.  Your conditional posterior had it on ALL the data.
$\mu_m \sim p(\mu_m | \Sigma_m, \pi_m, \{\forall j, x_j | z_{jm} = 1\})$
Here, each component parameter sampling is independent of parameters of all other components.
Repeat.
========
There are ways to also infer # of components in a Bayesian manner, but this is a fairly simple algorithm that you can try first.  For the priors, you can use standard Gaussian prior for each of the $M$ components in step 2.
This is roughly the procedure developed here:
https://www.jstor.org/stable/2345907?seq=1#page_scan_tab_contents
Comment: The thing that confuses me is the model I'm supposed to fit specifically conditional densities $f(y|S=k) = x_i \beta_k + \epsilon_i$ where $\epsilon_i \sim N_p (\mu_k , \Sigma_k)$ and covariate $x_i$. Without this beta, I understand your answer well. But with it, I am completely lost as to how I'm supposed to obtain estimates for $\beta$.  I think (?) this is called a Mixture Structural Equation Model, but tbh our lecture notes do not go into detail in the slightest and have no info on fitting it... I could use EM but then I'm maximising a function of 20ish parameters which seems unworldly.
Comment: If I understand correctly, estimation of all parameters except $\mu$ and $\beta$ are the same regardless of whether $\beta$ is included or not. But, with the inclusion of $\beta$, neither $\mu$ nor $\beta$ are the mean of the normal densities, and so I'm not sure how to obtain congujate priors for each of them in this situation.
Comment: What does the data look like when scatter plotted?  x_i are the raw data points?
Comment: The data is simulated and follows that mixture model with the specified conditional densities. $x_i$ are generated covariates used to construct the response variables $y_i$ from known multivariate normals so that the model  holds. It's just estimation that has me completely confused
Comment: can you post a pic of your simulated data?  I'm having a bit of hard time picturing what's going on.
Comment: or why this form of model is necessary
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/84430/discussion-between-xiaomi-and-ken).


How to recognize the type of data in C++?

Question: I learn C++ by a book, and always when I have a task to do, I'll add some of my features.
Now I wanted to add "check for dummy people", and if they write fractional number, not integer, the console will be closed.
I wanted to do like that:
cin >> timing;
if (timing == double) {
    ...

But the Visual Studio compiler says "type name is not allowed".
Please, tell me how to do this check
Comment: variables have static types. Therefore the shown code doesn't make sense and would never be necessary
Comment: What you probably want to do instead is read the input into a `std::string` then use one of the parsing functions (such as `std::stod` : https://en.cppreference.com/w/cpp/string/basic_string/stof) to check if you can convert the text into a `double`
Comment: Whatever book you're using it doesn't seem to to a very good job. [Here's a list of books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) that are commonly recommended. If possible please invest in one or two of the beginners books from the list.
Comment: How to do string input I know. But what parsing functions do you mean? And I don't know any convert functions, 'cause I'm newbie( I hope you will answer in details. Anyway, thank you :)
Comment: You probably would have to make `timing` a std::string then write a function to check if the string looks like a double. This is not really a newbie type project. Wait till you learn more c++ before attempting.
Comment: I've already understood that, thanks) But what functions can we use for check?
Comment: Thank you, but your comment makes no sense. I asked about my problem and asked how to solve it, not about "I read this book - is it good or not?"
Answer: The type of your timing variable is static, as are all types in C++. I'm going to assume it's an std::string. It will never be a double or an int. What you can do with it, is translate the information stored in it into another object of a different type.
For example, with std::stod you can try and convert the string into a double. This will return a double for all inputs, e.g. "3.1", "0", "horse", or "". For the last two, however conversion will fail, and std::stod will throw.
However, the return value is always a double.
Now, you can check if the double holds an integral value. For instance you can convert the value to long and back and check if you get the same value. There are more sophisticated ways to check this, but it would be a good start.


Using controlBus from spring DSL with parameters

Question: I need to control my routes and I am using spring DSL for Camel.
I need to exposed a service which will perform thoses actions to the routeId given in paramaters.
The following code does not work (the body contain the routeId)
<route id="stopRoute">
            <from uri="direct:stopRoute"/>
            <log message="about to stop a route"/>

            <to uri="controlbus:route?routeId=${body}&action=stop"/>
            <to uri="controlbus:route?routeId=${body}&action=status"/>

</route>

I also tried with simple language but I can't figure out the correct syntax
Answer: See this FAQ
http://camel.apache.org/how-to-use-a-dynamic-uri-in-to.html
Use <toD> to make the to dynamic.
Comment: Thanks that's work, I had'nt seen this new expression, that's explaining while old examples does not work with dynamic URI.
Comment: By the way do you know if the stopRoute or any other controlBus action could disable the server connector in http cases?


Não consigo adicionar OverlayView

Question: Preciso adicionar uma OverlayView sobre um mapa em um projeto Ionic3.
Foi usado como base o tutorial da Google: Adicionar OverlayView Customizada
O código usado é uma adaptação pro TypeScript que encontrei pesquisando.
Código:
declare var google;

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

    overlay: any;

    private srcImg: string = 'https://developers.google.com/maps/documentation/' + 'javascript/examples/full/images/talkeetna.png';

    //Todos os parametros necessários são passados no construtor
    constructor() {}

    //Definição de uma classe interna para o OverlayView
    //Adaptação encontrada de JavaScritp para TypeScritp
    USGSOverlay = class extends google.maps.OverlayView {

          bounds_: any;
          div_: any;
          image_: any;

          constructor(bounds, image, private map) {
            this.bounds_ = bounds;
            this.image_ = image;

            this.div_ = null;

            this.setMap(map);
          }

          onAdd() {
            var div = document.createElement('div');
            div.style.borderStyle = 'none';
            div.style.borderWidth = '0px';
            div.style.position = 'absolute';

            var img = document.createElement('img');
            img.src = this.image_;
            img.style.width = "100%";
            img.style.height = "100%";
            img.style.position = "absolute";
            div.appendChild(img);

            this.div_ = div;

            var panes = this.getPanes();
            panes.overlayLayer.appendChild(div);
          }

          draw() {
            var overlayProjection = this.getProjection();

            var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
            var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

            var div = this.div_;
            div.style.left = sw.x + 'px';
            div.style.top = ne.y + 'px';
            div.style.width = (ne.x - sw.x) + 'px';
            div.style.height = (sw.y - ne.y) + 'px';
          }

          onRemove() {
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
          }
    };

    //Aqui é onde a OverlayView deveria ser colocada sobre o mapa
    //na atual posição do usuário
    updateLocation() {
      this.platform.ready().then(()=>{
        this.geolocation.getCurrentPosition({
            maximumAge:0,
            timeout:5000,
            enableHighAccuracy: true
         }).then((resp) => {

               console.log(resp);
               let latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
               this.LL = latLng;

               let bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(resp.coords.latitude - 0.04, resp.coords.longitude - 0.04),
    new google.maps.LatLng(resp.coords.latitude + 0.04, resp.coords.longitude + 0.04));

               this.overlay = new this.USGSOverlay(bounds, this.srcImg, this.map);

               this.changeMarker(resp.coords.latitude, resp.coords.longitude);

        }).catch((error) => {
               console.log('Erro ao recuperar sua posição',
               JSON.stringify(error.stack));
               console.error(error);
               this.toastCtrl.create({
                   message: 'Erro ao localizar seu dispositivo. Insira manualmente seu ponto de partida.',
                   duration: 5000,
                   position: 'bottom'
            });
         });
      });
    }
}

Porém, nada acontece.
Alguém pode achar que é algum problema por eu não colocar a chamada super(); dentro do construtor da classe interna USGSOverlay. O problema que quando coloco essa chamada me retorna o seguinte erro ao rodar o projeto:

Call target does not contain any signatures.

Mas se eu tiro a chamada de super(); o projeto roda, mas a IDE me aponta o Warning :

Construtores de classes derivadas precisam conter uma chamada a 'super'

E de qualquer jeito nada funciona.
Alguém tem alguma ideia de como eu posso fazer essa OverlayView funcionar?
Answer:  constructor(bounds, image, private map) {
        super(bounds, image, map);//Passar parâmetros ao chamar super()
        this.bounds_ = bounds;
        this.image_ = image;

        this.div_ = null;

        this.setMap(map);
      }

Não consigo adicionar OverlayView


$\mathcal{A}+K$ is norm-closed where $\mathcal{A}$ is a $C^*$-algebra and $K$ is the compact operators.

Question: Let $\mathcal{A}\subset B(H)$ be a unital $C^*$-algebra and let $K$ be the closed ideal of compact operators. I need to show that $\mathcal{A}+K$ is also a $C^*$-subalgebra of $B(H)$. I am stuck at proving that the space $\mathcal{A}+K$ is norm-closed.
I begin with a a sequence $\{B_n\}_{n=1}^{\infty}$ in $\mathcal{A}+K$ with $B_n\rightarrow B$, for some operator $B\in B(H)$. Now, for each $n\in\mathbb{N}$, $B_n=A_n+K_n$, where $A_n\in \mathcal{A}$ and $K_n\in K$. And from here I'm lost. Is there some kind of Bolzano-Weierstrass property for compact operators? Hints are welcome.
Answer: Note that $\mathcal{A}\cap K$ is a closed ideal in $\mathcal{A}$, and we have a well-defined $\ast$-homomorphism
$$
\varphi : \mathcal{A}/(\mathcal{A}\cap K) \to B(H)/K \text{ given by } a + (\mathcal{A}\cap K) \mapsto a+K
$$
The range of $\varphi$ is precisely $(\mathcal{A} + K)/K$, and the range of a $\ast$-homomorphism is complete.
Since $K$ is complete, it follows that $\mathcal{A} + K$ is also complete; and hence closed.
Edit: Added is a proof of the following fact:

If $A$ is a normed linear space and $B\subset A$ a closed subspace such that $B$ and $A/B$ are both complete, then $A$ is complete

Suppose $(x_n) \subset A$ is Cauchy, since $\|(x_n + B) - (x_m+B)\| \leq \|x_n - x_m\|$, it follows that $(x_n+B)$ is Cauchy in $A/B$. By hypothesis, $\exists y\in A$ such that
$$
x_n + B\to y+B
$$
By definition of the quotient norm, for each $n\in \mathbb{N}, \exists z_n \in B$ such that
$$
\|x_n - y - z_n\| < \|(x_n+B) - (y+B)\| + 2^{-n}
$$
So if $y_n := x_n - y - z_n$, then
$$
y_n \to 0 \text{ in } A
$$
Hence, $z_n = x_n - y - y_n$ is Cauchy in $B$ (being the difference of two Cauchy sequences). Since $B$ is complete, $\exists z\in B$ such that
$$
z_n \to z
$$
and hence
$$
x_n = (x_n - y-y_n) + (y+y_n) \to z+y
$$
Comment: it is not immediately obvious to me how you deduce that an algebra is complete if its quotient is complete.
Comment: If $A$ is a normed linear space and $B \subset A$ a closed subspace, then one can prove that if $B$ and $A/B$ are both complete, then so is $A$ [the proof I remember uses the fact that an absolutely summable series is summable iff the space is Banach]
Comment: Do you have a reference for that? I cannot imagine how to prove it, so I would love to see how the argument goes.
Comment: @MartinArgerami: I have added a proof since I couldn't find a reference (it is usually an exercise in textbooks I seem to have)
Comment: Thank you. I wasn't aware of this approach. This seems a more elegant way.
Comment: Nice, thanks! $ $


How to create make file for only object and header file?

Question: I'm performing blackbox testing using a set.h interface where I have no access to set.c, I've been provided with the object file set.o and I'm required to write a bunch of tests in a main.c file for the set. How do I create a makefile that would include set.o, set.h and main.c?
**I already have the set.o file so I don't have to regenerate it using set.c
I'm confused because I only know how to do this using the complete files.
Here's my template
CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o $(OBJDIR)/set.o

# compiling rules

$(PROG): $(OBJS) $(OBJDIR)
    $(CC) $(CFLAGS) $(OBJS) -o $(PROG)

$(OBJDIR)/set.o: set.h $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c set.h -o $(OBJDIR)/set.o

$(OBJDIR)/main.o: main.c $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

$(OBJDIR):
    mkdir $(OBJDIR)

clean:
    rm -f $(PROG) $(OBJS)

Comment: Check your compilers options for link-only.
Answer: If you already have the set.o file there is no need to create a rule for it, just use it. Also note I got rid of the mkdir because if you already have a set.o, it should already be in objects/ right?
CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o

# compiling rules

$(PROG): $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) $(OBJDIR)/set.o -o $(PROG)

$(OBJDIR)/main.o: main.c $(HDRS)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

clean:
    rm -f $(PROG) $(OBJS)

Comment: I keep getting this error, `Makefile:16: *** missing separator.  Stop.`
Comment: If you are copying and pasting make sure there are tabs and not spaces. Just realized you were using clang. Try the edited answer.
Comment: So I've implemented that. Now, when I use make it says `clang -g -Wall -c main.c -o object/main.o` and then goes on to say error:use of identifier set. The set declaration is in set.h
Comment: do you have `#include "set.h" ` in main.c?
Comment: It works when I change $(OBJDIR)/set.o to set.o, why?
Comment: Good question. Not sure. Is set.o in the same directory as main.c?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148703/discussion-between-ekeith-and-atomsmasher).


Role list command send objecct Object instead of roles discord.js

Question: It sends [object Object]. There are no errors in the console.
let embed = new Discord.MessageEmbed()
 .setTitle('Availible Roles')
 .setColor('RANDOM')
 .setDescription(roles.array().join(' \n'));
message.channel.send(embed, { split: true });

rest of the code
const Discord = require('discord.js');
const { prefix, token } = require('../config.json');

module.exports = {
    name: '',
    description: '',
    execute(message, args, client) {
        if (!message.content.startsWith(prefix) || message.author.bot) return;
        const roles = message.guild.roles.cache.filter(c => c.name.startsWith('A'))

        const arr = roles
            .array()
            .join('\n')
            .match(/.{1,2048}/g);

        for (let chunk of arr) {
            // loop through every element (every 2048 characters)
            let embed = new Discord.MessageEmbed()
                .setTitle('Available Roles')
                .setColor('RANDOM')
                .setDescription(chunk);

            message.channel.send(embed); // wait for the embed to be sent
        }
    },
};

const roles = message.guild.roles.cache.filter(c => c.name.startsWith('A'))

Comment: How is the `roles` variable defined? Please show more of your code
Comment: I have added it to the question now
Answer: Your problem is { split: true }. This option can mess up embeds, as it is meant for regular text messages. If you remove it, the embed should work perfectly.

If you are worried about there being too many roles, and exceeding the 2048 character limit, you can implement this function:
// array of your description split every 2048 characters
const arr = roles
 .array()
 .join('\n')
 .match(/.{1,2048}/g);

for (let chunk of arr) {
 // loop through every element (every 2048 characters)
 let embed = new Discord.MessageEmbed()
  .setTitle('Available Roles')
  .setColor('RANDOM')
  .setDescription(chunk);

 await message.channel.send(embed); // wait for the embed to be sent
}

Code Snippet Example:

const string = 'Hello world! This is a string. Strings are very fun. Fun is also very, by definition, fun!'

// array of your description split every 20 characters
const arr = string.match(/.{1,20}/g);

for (let chunk of arr) {
  // loop through every element (every 20 characters)
  console.log(chunk)
}
Comment: It sends each role as its own embed | So it's basically flooding the chat
Comment: Why don't you use [`Discord.Util.splitMessage()`](https://discord.js.org/#/docs/main/stable/class/Util?scrollTo=s-splitMessage) instead?
Comment: The problem might be that your not `await`ing the message being sent. Make sure you make your execute function async: `async execute(message, args, client)`


How to use the Message module to log site and user activity?

Question: I am just unable to use the Message module or the Activity module to record the following activities and show them in a view.

User A just got 10 points.
User B just became User A's friend.
User C just joined the site.
User D just logged in.
User E just viewed "Any Blog".
User F just commented on "Any Blog".

The Activity module does not provide hooks for some of this in the CMS UI itself and I am having real difficulties to configure the Message module for these cases.
There is not enough documentation for this, especially the Message module. There is one tutorial at Log Site Activity with Message and Rules but that is for only one of my cases. I haven't been able to figure out the other use cases. I don't get exactly the same options (entity and tokens) as described in the tutorial.
Any help with my use cases?
Comment: To see how message module works, enable "message example" module.
Comment: will look into it and then get back...thanks for the direction though
Comment: I have same question,when adding a new message type,there is no Message text area to add the message.What am I missing?How did you solve this?
Comment: @sokratis you might get it to work using the technique of "*Replacement tokens*" as detailed in my answer below ...
Answer: The Message module is great, really! But still poorly documented. However, have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module, together with the Rules module. What follows is a summary of what's included in this tutorial.

You can use the Message module in combination with the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).
Here is a blueprint of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in 'Which user related token(s) can be used to create a Rule for setting up a message type?' for some examples.
Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.

Some more details specific to your question here:

For each of the 6 activities you want to record, define an appropriate (corresponding) Message Type (using the Message module). Let's name those message types like M1, M2, ... M6 for now.
For each of the 6 activities you want to record, there is an appropriate Rules Event you can take advantage of. If you'd just create 6 custom rules (1 for each activity to record, let's name those rules like R1, R2, ... R6 for now), it's a matter of combining each rule with a Rules Action to "Create an entity" (i.e. of type "Message"). E.g. Rule R3 should have a Rules Action to create a message of type M3.
As per the "I don't get exactly the same options (entity and tokens) ..."-part of your question: I bet sooner or later you're going to run into the issue that you want to create a message using a token which is NOT made available by only the Message module. E.g.: Assume that for recording your 6th activity (= "User F just commented on ...") you want the message to also include the actual comment body (text) that was posted. But the Message module doesn't offer any relevant token related to that comment body. In that case, you can use the approach/solution as documented in "What's the purpose of "Replacement tokens" of a Message type?", which is basically a technique to create your custom tokens (the comment body in the example here) and make them available to the Message module (so that you can include them in the message to be created).
Obviously, creating appropriate views of these messages (which are just entities) should be straight forward.

More info about the Message module
There is not a lot of documentation available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:

What is Drupal's Message Stack and how do its modules work together?
How to allow users to manage their own Message Stack messages?


How to send one time login url with Rules?

Question: I have a rule to create a user and an action to send login url to user's email. I didn't find any action to send login url, so added an Send HTML Email action and added the [user-created:one-time-login-url] token in mail body. but it appears as it is([user-created:one-time-login-url]), and is not translated to login url.
Then I used this php function to print the same url:
<?php
print user_pass_reset_url($user_created);
?>

It prints a url but also prints the following notices:
Notice: Undefined property: stdClass::$uid in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$pass in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$login in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).

$user_created is the php variable referring to the user created in the previous action. But it seems it's not a user object(because of notices).
What's the proper way to send one time login url?
Comment: If $user_created is the UID variable, you will need to load the user object like this: $user = user_load($user_created); Then you can use your other function like: user_pass_reset_url($user);
Comment: tried that but this time I get some fatal errors
Answer: Try out Login one time module

The use case for this is where your users can't figure out how to use
  a username and password - so they request an email link to what they
  need.
Comment: using this module with _recipient user_ field set to `user-created` value still prints the same notices.
Answer: You need to use the token_replace function like this
$newly_created_user = user_load(101);
$subject =token_replace('Hello  [user:field-your-first-name]  [user:field-your-last-name], here is your password reset link [user:one-time-login-url] ', array('user' => $newly_created_user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE));

ultimately you need to add extra third parameter to the token_replace function
array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)

Answer: The solution was adding an Save entity action before using user_pass_reset_url() function or login one time action.


Operation defined on a group uniquely determines that group

Question: This is an exercise (2.2:3) in An Invitation to General Algebra and Universal Constructions by George M. Bergman:

If $G$ is a group, let us define an operation $\delta_{G}$ on $|G|$ by $\delta_{G}(x, y) = xy^{-1}x$. Does the pair $G' = (|G|, \delta_{G})$  determine the group $(|G|, {}\cdot{} , ^{-1}, e)$? (I.e., if $G_1$ and $G_2$ yield the same pair, $G'_1 = G'_2$, must $G_1 = G_2$?)

($|G|$ means underlying set of a group).
If $G'_1 = G'_2$ then they are equal as pairs and that means that $|G_1| = |G_2|$ and $\delta_{G_1} = \delta_{G_2}$. Let $\circ$, $^{-1}$, $e_1$ (resp. $\star$ , $^{'}$, $e_2$) be binary operation, operation of taking inverse and identity operation in group $G_1$ (resp. $G_2$). By virtue of $\delta_{G_1} = \delta_{G_2}$ we get
$$ x \circ y^{-1} \circ x = x \star y^{'} \star x \tag{1}$$
for every $x, y$ of $|G_1|$.
Plugging various $x$ and $y$ in $(1)$ we can get following relations of identities:
$$ e_1 \star e_1 = {e_2}^{-1} \tag{2}$$
$$ e_2 \circ e_2 = {e_1}^{'} \tag{3}$$
$$ {e_2}^{-1} \star e_1 = {e_2}^{-1} \circ {e_2}^{-1} \tag{4}$$
And I'm stuck with that: can't get any reasonable relation which would allow to get equalitity of identities or equality of inverses or just distributivity between two group operations (to prove that groups are equal).
On the other hand, to disprove that one must find a counterexample e.g. in groups of small order (i.e. two different group structures on the same set giving the same derived operations), but it is tedious.
Comment: Yes, but in this book it means underlying set of a group. That's exactly what author writes.
Comment: $|G|$ usually denotes the cardinality of the set $G$.
Comment: @DietrichBurde: Bergman distinguishes between the algebraic structure (which involves both the underlying set and the operations and/or relations defined on it) and the underlying set. So he uses that notation throughout (and being very explicit about it, and about the clash with its common use) for underlying set, and uses $\mathrm{card}(X)$ for the cardinality of a set $X$. The book was originally typeset in troff, where  there were fewer options vis a vis available fonts, and the notation originated in that version.
Comment: Perhaps it is helpful to read the solution for Example $2.2.2$ with $\delta_{G}(x, y) = xy^{-1}$.
Comment: I solved 2.2:2, but can't handle this one. In 2.2:2 just plug $x$ instead of $y$ in $x \circ y^{-1} = x \star y^{'}$ and get $e_1 = e_2$. Equality of inverses and binary operations follows.
Answer: Since the question asks for equality of operations rather than isomorphism: take $G$ to be any elementary abelian $2$-group. Then $xy^{-1} x = y$ so the operation $\delta_G$ gives you no information and, for example, there are already two such structures on the two-element set (given by choosing one or the other of the two elements to be the identity).
Answer: This question is was answered a year and a half ago, but let me add a comment. In the answer given, it is argued that if $G$ is a nontrivial elementary abelian $2$ group, then $(|G|,\delta_G)$ does not contain enough information to determine which element of $G$ is the identity element.
In fact, if $G$ is ANY nontrivial group, then $(|G|,\delta_G)$ does not contain enough information to determine which element is the identity element.
This is because $\delta_G$ is an idempotent operation ($\delta_G(x,x)=x$) and the idempotent subclone of a group cannot identify the identity element.
More concretely, let $G$ be any nontrivial group and choose any $a\in G-\{e\}$. The operation $x\otimes y:=xa^{-1}y$ is a group multiplication on the set $|G|$. This multiplication has identity element $a$ (which was chosen essentially arbitrarily) and inverse operation $\textrm{inv}_{\otimes}(x)=ax^{-1}a$. Finally, $\delta_{G_\otimes}(x,y)=x\otimes \textrm{inv}_{\otimes}(y)\otimes x = xa^{-1}ay^{-1}aa^{-1}x=xy^{-1}x=\delta_G(x,y)$. This shows that $(|G|, \otimes, \textrm{inv}_{\otimes}, a)$ and $(|G|,\cdot, {}^{-1},e)$ have the same $\delta$-function but different identity elements. These groups also have different multiplication tables. They will also have different inverse operation tables unless $a$ is a central involution.


Um pequeno probleminha no Eclipse

Question: Havia, ontem, feito uma pergunta aqui mesmo no site em relação a um problema em meu Eclipse ADT. Agradeço de coração ao felizardo, cujo nome não estou lembrado, por ter me ajudado! O jeito foi instalar um plugin no SDK.
Mesmo assim, ao construir meus projetinhos Android no Eclipse ADT, acredito que a IDE sugere-me uma modificação no código (essas lâmpadas!). Vejam o que estou a falar:

Esse modelo de código não aparecia quando havia instalado o plugin do ADT há alguns dias, e nem aparecia as lâmpadas.
Se há algum problema ou melhoria no código, o que eu faço?
Comment: Nomes de objetos/propriedades/métodos em sublinhado estão depreciados não é recomendado utilizar eles, a lampada deve ser uma sugestão do recurso novo ou similar.
Comment: Você pode ver o histórico da sua participação aqui no site acedendo ao seu [perfil](http://pt.stackoverflow.com/users/23601/gabriel). Para saber o porquê das lâmpadas coloque o ponteiro do rato por cima delas.
Answer: Nomes de objetos/propriedades/métodos etc. em sublinhado estão obsoletos, não é recomendado utilizar eles em novos projetos, a lâmpada deve ser uma sugestão do recurso novo ou similar.
A classe ActionBarActivity está obsoleta conforme indica a documentação no lugar dela deve ser utilizada a AppCompatActivity
Mude:
public class Tela extends ActionBarActivity

Para:
public class Tela extends AppCompatActivity

Comment: Hummm.. entendi... faço o quê agora?
Comment: Seguindo os "conselhos" das lâmpadas, consegui removê-las.

O que houve no meu código: acrescémio da instrução: @SuppressWarnings("deprecation")

Mesmo assim, o sublinhado ainda existe!
Comment: No lugar de `public class tela extends ActionBarActivity` coloque `public class tela extends AppCompatActivity`, e faça o import correto que seja sugerido pelo eclipse. @Gabriel
Comment: VALEEEEU! Tudo correu nos conformes! Existe algum lugar neste tópico onde eu possa marcar a questão como resolvida?
Comment: Sim no lado esquerdo tem umas setas abaixo delas tem um `V` que sinaliza que essa resposta foi aceita, aproveite e veja [Como e por que aceitar uma resposta?](http://meta.pt.stackoverflow.com/a/1079/91). @Gabriel

Um pequeno probleminha no Eclipse


Where am I going wrong

Question: So I am very new to Django and I am confused where am I going wrong. I am trying to create a simple calculator to calculate profit estimates. Here is what it shows in my HTML so far. Kind of confused where am I going wrong. Any help appreciated.

This the HTML file code
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test</title>

    {% block content %}
    <form action = "something" method = "post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value=Submit>
    </form>
    {% endblock %}

This is forms.py
from django import forms
from .models import Calc

class Calculator(forms.ModelForm):
    class Meta:
        model = Calc
        fields = ['gross_receivable', 'TDS', 'bank_charges', 'vendor_payable']

This is the models.py
from django.db import models

# Create your models here.
class Calc(models.Model):
    gross_receivable = models.IntegerField()
    TDS = models.BooleanField(default=False)
    bank_charges = models.BooleanField(default=False)
    vendor_payable = models.IntegerField()

This is the views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import Calc

    def something(request):
        form = Calc()
        context = {'form': form}
        return render(request, "calculator1.html", context)

Comment: You haven't asked a question, what is it doing that you dont expect?
Answer: Your form name is Calculator but you are importing your model as form.
You should change
from .forms import Calc

to
from .forms import Calculator

and in the something function
form = Calculator()

Where am I going wrong


Is it possible to solve this system of equations in terms of p?

Question: Given
$$
\begin{aligned}
b(1-p) +cp &= a \\
ap +c(1-p) &= b \\
a(1-p) + bp &= c \\
a+b+c&=1
\end{aligned}
$$
Is it possible to solve a, b, and c, individually, only in terms of p?
Comment: What have you tried so far?
Comment: Use the first three to get three separate equations for $p$.  Multiply these to determine $p^3$.
Comment: @CyclotomicField Gaussian Elimination using the first three equations which did not yield what I was looking for. I have tried to play around the equations but cannot seem to solve any of a, b, or c in terms of p. Hence why I was wondering if it was possible in the first place.
Comment: @Saint: The first three equations are linearly dependent. (Add them together, and you'll get $0=0$.) So, try Gaussian Elimination on, say, the first two equations and the fourth one.
Answer:
1 = a + b + c

1 = [b - bp + cp] + [c - cp + ap] + [a - ap + bp]
Substituting the p terms for a, b, and c, we find the p terms cancel.
p can be any number.  It does not affect the value of a, b, or c.
If p = 0, then a = b = c


Clean field value handling inside views_handler_field subclass?

Question: I am writing a few views_handler_field subclasses that render fields of my entity depending on other values of the entity. The examples I see use a very awkward way of accessing the other field data, eg.
<code>function render($values) {
  if (isset($values->field_name[0])) {
    $my_stuff = $values->field_name[0]['raw']['value'];
  }
  ...
}
</code>
Is there a clean way of accessing other fields in the entity, like EntityMetadataWrapper? I would just load the entity and create a EMW instance but that seems expensive to do for each cell in a big table.
Answer: field_get_items() and field_view_value() are as clean as it gets without Entity API.


What is the issue in the following node.js mySQL query?

Question: =================================================
> here is a query to be stored in a variable
  let x = tempCont.query('SELECT password FROM `users` WHERE `user_name` =' + req.body.user_name,
                function (err, result, field) {
                    if (!!error) {
                        console.log('Error in user_name Query');
                    }
                    else {
                        console.log(result);
  }
                    console.log(x[0]);

                })

Comment: String concatenation -> SQL Injection alert. And please do not store password as plain text.
Comment: The issue I can not retrieve the query value in the last console.log .. How could I get the password?
Comment: I do not understand .. How to do so? .. I can not retrieve the value of x which is the result of a SQL Query
Comment: @isodino Print your raw MySQL query to the console and you will see why it does not behave as you expect.  You never escape the username with single quotes, but don't do that anyway, use parameters instead.
Answer: You should be using parameters in your query, i.e.
let x = tempCont.query('SELECT password FROM `users` WHERE `user_name` = ?',
    [req.body.user_name],
    function (err, result) {
        if (err) {
            console.log('Error in user_name Query');
        }
        else {
            console.log(result);
        }
    });

By passing the username variable as a parameter in the array the proper escaping should already be done for you.
Comment: sorry I tried it .. but it gave me undefined value ...
Comment: when we use the inner console.log with result[0].role it gives a value .. When we try to get the value from x variable in the outer console.log .. it gives undefined.. the issue I do need to get the value from the variable
Comment: I don't know what you are trying to do, but if no error occurred then `result` should contain your result set.
Answer: how about
var x = 0;

tempCont.query('SELECT password FROM `users` WHERE `user_name` =' + req.body.user_name,
            function (err, result, field) {
                if (!!error) {
                    console.log('Error in user_name Query');
                }
                else {
                    console.log(result);
                }

                x = result

                // to display password of row 1
                console.log(x[0].password);

                // to display row 1
                console.log(x[0]);

                // to display the object
                console.log(x);

            })

Also use this format:
tempCont.query('SELECT password FROM `users` WHERE `user_name` = ?',[req.body.user_name],(err, result, field){
});

Comment: it is not working .. I can not get the value of the query through variable x
Comment: try running console.log(result) in the function, does your desired result show up in the terminal?
Comment: yes it appears but i do need it outside the function of query
Comment: how about passing only the password

    x = result[0].password

since its seems that you are only trying to get 1 password
Comment: var x = 1;
var y = 0;

 var z =connection.query ('SELECT * from `roles` where `id` = '+x , function (error, results, fields) {
    if (error) throw error;

    console.log (results[0].role);
   y=results[0].role;
   console.log (y);
   return y;
});
console.log(y);
console.log(z);
Comment: Here z shows object .. while y inside query shows a specific value .. I can not get the specific value outside the query
Answer: Here's how I use the data of the query and use it externally. Used it like an external module.
function fuser(req,res,next){
  var db = require('../../lib/database')();
  db.query("SELECT * FROM tbluser WHERE strSNum= ?",[req.params.userid], (err, results, fields) => {
      if (err) console.log(err);
      req.user= results;
      return next();
    });
}

router.get('/:userid', fuser, (req, res)) => {
   res.render('profile/views/index',{usertab: req.user});
});

In this case, assigning the results object to req.user, but this example uses express
Comment: ok how do i use promise?
Comment: in your example .. i can not also console.log of req.user outside the function or the query


Finding a formula for a matrix

Question: $$B:=\begin{bmatrix} -1&9&0&0&0\\
0&-1&0&0&0\\
0&3&-1&0&0\\
0&1&1&1&0\\
0&-2&-2&0&1\end{bmatrix}$$
Is there any way to compute a formula for $B^n$ for all integers $n\geq5$? I ran across this and was curious.
Comment: Last bit on [this](https://en.wikipedia.org/wiki/Jordan_normal_form#Matrix_functions) section.
Comment: We did something similar in Linear Algebra when we covered diagonalization of matrices. If $B=PDP^{-1}$ then wouldn't the pattern work out to be $B^k=PD^kP^{-1}$?
Comment: Are you comfortable with diagonalization? Is this along the lines of what you were looking for?
Comment: @Mallory yeah that's for sure along the lines. I'm just not sure how to even go about it
Answer: The multiplication below represents $B\cdot B^n$ where $\delta_n=0$ for $n$ even and $1$ for $n$ odd. It is not hard to check that the product has the required form. So we have verified by induction that the form holds for all positive integers $n$.
$$\left(\begin{matrix} -1&9&0&0&0\\
0&-1&0&0&0\\
0&3&-1&0&0\\
0&1&1&1&0\\
0&-2&-2&0&1\end{matrix}\right)\left(\begin{matrix} (-1)^n&(-1)^{n+1}9n&0&0&0\\
0&(-1)^n&0&0&0\\
0&(-1)^{n+1}3n&(-1)^n&0&0\\
0&(-1)^n\frac{3n}{2}+\frac{5\delta_n}{2}&\delta_n&1&0\\
0&(-1)^{n+1}3n-5\delta_n&-2\delta_n&0&1\end{matrix}\right)$$
As to how one gets the form, that is simple: work out the first few powers and observe the pattern.
Of course the more sophisticated approach is to find $$P=\left(\begin{matrix} -\frac{1}{15}&0&\frac{1}{5}&0&0\\
\frac{1}{36}&0&0&0&0\\
0&\frac{1}{4}&0&0&0\\
0&-\frac{5}{2}&-1&0&1\\
0&\frac{5}{4}&\frac{1}{2}&1&0\end{matrix}\right)$$ so that $PAP^{-1}=$ $$\left(\begin{matrix} -1&0&0&0&0\\
0&-1&1&0&0\\
0&0&-1&0&0\\
0&0&0&1&0\\
0&0&0&0&1\end{matrix}\right)$$
Then we can take powers of that to get $$\left(\begin{matrix} 1&0&0&0&0\\
0&1&-n&0&0\\
0&0&1&0&0\\
0&0&0&1&0\\
0&0&0&0&1\end{matrix}\right)$$ for the even powers and $$\left(\begin{matrix} -1&0&0&0&0\\
0&-1&n&0&0\\
0&0&-1&0&0\\
0&0&0&1&0\\
0&0&0&0&1\end{matrix}\right)$$ for the odd powers. Then we convert back to get $B^n$ by premultiplying by $P^{-1}$ and postmultiplying by $P$.
Answer: Not a full answer but this wouldn't format correctly when I put in a comment.
$$B^n=\begin{bmatrix} (-1)^n&-9(-1)^n&0&0&0\\
0&(-1)^n&0&0&0\\
0&-3(-1)^n&(-1)^n&0&0\\
0&\frac{1}{4}\left(5-5(-1)^n+6(-1)^nn\right)&\frac{1}{2}\left(1-(-1)^n\right)&1&0\\
0&-\frac{1}{2}\left(5-5(-1)^n+6(-1)^nn\right)&-1+(-1)^n&0&1\end{bmatrix}$$
Comment: can i ask how and why you are taking this approach? @ianmiller
Comment: Hi, I don't understand your question. This isn't an approach just the answer. I intended to leave a comment but the matrix wouldn't format correctly in a comment.

Finding a formula for a matrix


Proving that $\mu(C(x,\delta))\ge \delta^2/2 $ where $C(x,\delta)=B(x,\delta)\cap C$ and $C$ is a square.

Question: Let $\mu$ denote Lebesgue measure. Consider a closed square $C\subset \mathbb{R}^2$. Let $d$ be the diameter of $C$ and $$C(x,\delta)=B(x,\delta)\cap C,$$
where $B(x,\delta)=\{y\in \mathbb{R}^2: |y-x|<\delta\}$. I can prove that for $x\in C$ and $\delta< d$, the quantity $$\frac{\mu(C(x,\delta))}{\delta^2},$$
is bounded below by some postive constant, independently of $x$ and $\delta$. However, I fail to see why this constant can be takne to be $1/2$. Any idea is appreciated.
Comment: It seems to me that it is suffices to analyse the case where $x$ is a point in the corner of the square.
Comment: Did you see if $\mu(C(x,\delta))/\delta^2$ is nonincreasing? The value of $\mu(C(x,d))/d^2$ is exactly $1/2$.
Comment: Yes @UmbertoP., and I am trying to prove it, however, until now I have no success.
Answer: First note that if $x$ is in the corner of the square, we have that $$\mu(C(x,\delta))\le \mu(C(y,\delta)),$$
for any $y\in C$, therefore, we can prove the estimate only for $x$ in the corner. Assume without loss of generality that the square is given by $[0,t]\times [0,t]$.
If $\delta\le t$, we are done, so assume that $\delta> t$ and let $P_1=(\sqrt{\delta^2-t^2},t)$ and $P_2=(t,\sqrt{\delta^2-t^2})$ be the two points in the intersection of $C$ and $\partial B(x,\delta)$. We see that the desired area is composed of the area of two triangles and a circular sector.
The area of the two triangles is $t\sqrt{\delta^2-t^2}$, while the area of the circular sector is given by $(\pi/4-\arctan({\sqrt{\delta^2-t^2}/t}))\delta^2$. Therefore, $$\frac{\mu(C(x,\delta))}{\delta^2}=\frac{t\sqrt{\delta^2-t^2}+(\pi/4-\arctan({\sqrt{\delta^2-t^2}/t}))\delta^2}{\delta^2}, \ \delta\in(t,\sqrt{2}t). \tag{1}$$
From $(1)$ we see that if $\delta=t$ then , $\mu(C(x,\delta))/\delta^2=\pi/4$, while if $\delta=\sqrt{2}t$ then, $\mu(C(x,\delta))/\delta^2=1/2$. Moreover, by differentiating the function $\mu(C(x,\delta))/\delta^2$, with respect to $\delta$, we see that it is a decreasing function in the interval $(t,\sqrt{2}t)$, therefore, the estimates is proved.


Integral Calculus: Plane Areas in Rectangular Coordinates

Question: Find the area bounded by the given curves:
$y^2+2x-2y-3=0$ and the $y$-axis
(using horizontal & vertical strip)
Comment: Hi, welcome to MSE. Did you make a graph of the parabola? That could be very helpful
Answer: Finding the points:
$x = 0$ so
$$ y^2+2(0)-2y-3=0 $$
$$ y^2-2y-3=0 $$
$$ (y-3)(y+1)=0 $$
Thus points $P$ are $(0,3),(0,-1)$.
By completing the square
$y^2-2y+1=-2x+3+1$.
$$ (y-1)^2=-2(2x-2) $$
$ y=1, x=2 ,
V = (2,1) $
The parabola opens left.
Comment: What's the area of the portion of plane delimited by that parabola and that straigth line?
Comment: See [this introductory note](http://math.stackexchange.com/help/notation) about using mathematical expressions in posts, ie. using $\LaTeX$.


Most maintainable way to make page with one top half and alternative bottom halves selected by tabs?

Question: I want to make a page which has one top part, a row of two or more horizontal tabs beneath it, and alternative bottom parts which appear beneath that and can be selected by clicking on the tabs.
For example, imagine a page that someone might write about their cat. The top half is a photo of the cat and some text. At the moment, it's static, but I might later add a Twitter feed. Under it are tabs labelled "Poem", "Photo", and "Blog". The bottom half that gets selected when the user clicks on "Poem" is a poem, static HTML. That which gets selected when clicking on "Photos" is also static HTML, another image. And that which gets selected when clicking on "Blog" is dynamic: a blogroll implemented as a View.
Just to make sure that's unambiguous, there are pictures of the top half and the three bottom halves at http: //www.j-paine.org/dobbs/kitty_page_top_264.gif, http: //www.j-paine.org/dobbs/kitty_page_poem_257.gif, http: //www.j-paine.org/dobbs/kitty_page_photo_296.gif, and http: //www.j-paine.org/dobbs/kitty_page_blog_279.gif. Apologies for the deformed HTML, but this thing only lets me post two links.
I've found quite a lot of methods that on first sight, may do what I want. These include the modules Quick Tabs and Node Tab, as well as the trick with views menus that Ron Golan describes in "Views Menu Tabs Quick Guide" (see https://www.urbaninsight.com/2013/11/01/views-menu-tabs-quick-guide). There are also assorted PHP code hacks. But I can't find recommendations about which solution is best for reliability and maintainability. It does appear that some of the techniques were written for older versions of Drupal, and may have been superseded.
One thing is that unskilled site administrators should easily be able to find all the content (tops, tabbed menus, and alternative bottoms). That might rule out of some of the modules: I can't find the reference again, but at least one of them is said to implement its own special interface for keeping track of tabbed content rather than extending the standard Drupal interface.
This problem raised another question. How should I think about Drupal when working out how to do this? It's well known that programming needs three key concepts, used both in describing control and describing data: sequencing, alternation, and repetition. If I were programming the problem in Pascal, I would represent the page as a record. The first field would represent the top half of my page; the second would represent the bottom halves. Because these require alternation, I'd represent them as a discriminated union. I'd also need some pragmatic information saying that the union is to be displayed using tabs and giving the tabs' labels.
Now, it's clear that some of the built-in Drupal menus implement that kind of alternation. I get the impression, actually, that they're more important than the content itself, because users on various discussion groups have wondered why they couldn't see their content, then been told by an expert that this was because it's not attached to a menu. But I don't think the Drupal documentation says this anywhere. A formal semantics of Drupal would be good, but I can't find one. So when designing a structure like my page with one top and multiple bottoms, where should I start? What's the equivalent of C.A.R. Hoare's famous essay "Notes on Data Structuring" that every computer scientist will know from the classic Structured Programming?
Comment: Is this meant to be a one-off page?  Or is this a pattern that you wish your content editors to be able to apply to a certain type of page?  Or is this a pattern that content editors should apply arbitrarily to any page they might choose?  As you note, there are a lot of ways to do things in Drupal with subtle pros/cons depending on your needs.
Comment: Pierre, C.A.R. is his initials. See [this Oxford University biography](http://www.cs.ox.ac.uk/people/tony.hoare/) . Maybe I should make it clear that I'm talking about the computer scientist, Tony Hoare. Although he started working on computing in the fifties, his papers and essays are still worth reading, because he worked on showing that programs are correct. The essay I mentioned, "Notes on Data Structuring", does that for data represented using records, arrays, and unions. Drupal, and indeed any Drupal-like CMS, ought to have some equivalent.
Comment: Aaron, it's a pattern needed for a maximum of ten pages on the site. The implementors know in advance which pages they are. Having said that, we all know that specifications change, so I suspect it would be very useful for content editors to be able to come along later and restructure existing pages to fit this pattern.
Answer: Looks like you need to look at some of the typical "page layout" modules, such as these ones (excerpts from their project pages):

Display Suite.

... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Panels.

... allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Not sure if Display Suite will be sufficient for all your needs, but Panels will pretty sure be helpfull. Possibly also with 'mini-panels' added to that.
Be prepared however to invest some time in learning about these amazing modules. A great resource for learning about Panels is the (free) video training about Learn Page manager. Panels uses 'Page manager', which is one of the sub-modules of Chaos tool suite (ctools)).
Comment: Good answer.  Would add that Display Suite definitely isn't a good solution if you're building this as a one-off page.  For that, Panels is the right answer.  Probably combined with Quick Tabs or Panels Tabs.  Panelizer is another important module that can bring the page layout power of Panels to every single entity in your system.
Comment: Pierre, Aaron, thanks for those. Why do you say that Display Suite isn't the right solution?
Comment: @JocelynIreson-Paine : "I" am not sure if Display Suite (=DS) is "sufficient", because of the various "needs" I noticed in the question. Nevertheless, I personally appreciate DS a lot, and use it quite often in various sites. My rule of thumb: at least DS is usefull in many situations. But if requirements get tougher (more demanding), then it's probably a good moment to start considering the Panels module. DS's major advantage over Panels, I think, is the overhead (required resources), performance, etc that come with Panels. So if DS is enough, just stick with that. Just my 2 cents ...
Comment: I'm reading Steve Persch's [Explaining Panels](https://www.palantir.net/blog/explaining-panels-overview-drupal-developers). At the end, Matt Hicks commented "We're moving away from this approach and towards using shortcodes (https://www.drupal.org/project/shortcode) - the less abstract and cumbersome the process of getting HTML into the page the better. If there was ever a complex abstract way of doing things, it's panels. They have their uses but for the most part there are better ways of doing things now." Perhaps his problems are different from mine, but it doesn't make panels sound good.
Comment: Hm, valid (great) points! And thank you for the shortcode mention. Didn't know about that module, but will digest it in more detail later on (16K reported installs can't be wrong ...)!
Comment: I'm also discussing this at [Drupal.org](https://www.drupal.org/node/2545320) . Reader "nevets" suggested that if I have more than one page with this layout, I should use a content type with fields to hold the various pieces of information, a module like eva so I can include a view as one of the tabs, and the field groups module so that on the Manage display for the content type I can organise the fields into groups and include horizontal tabs. So: (A) Panels with Quick Tabs or Panel Tabs; (B) shortcodes; (C) fields with the eva and field groups modules; or (D) Display Suite.
Comment: I tried using Panels and found it fine, not too abstract or cumbersome. I also tried Quick Tabs. That caused me a maintenance problem, which I've reported on [The difficulty of putting two views on a page](https://www.drupal.org/node/2545320#comment-10186314). Briefly, to attach a tabbed block to a page, you have to tell the block which page it's in, rather than telling the page there's a block in it. That's back-to-front thinking, and bad for maintenance.
Comment: I also tried Panels Tabs, imitating the example on [Panels - Panels Tabs](https://www.drupal.org/node/2535252). But it didn't work. I got three tabbed panes side by side. Completely static, and it wasn't possible to switch between them. Perhaps this is because of Panels Tabs' JQuery requirements, documented [here](https://www.drupal.org/node/1043432). These are onerous, and I note the comment from user "asb": "Matching the vague "requirements" and dependencies of this module, and keeping them, is sheer madness :-(". Other users have reported such difficulties. So perhaps avoid Panels Tabs?


Doubts about this nicely integral identity with floor function

Question: I'm trying to prove for $f:(a,b]\to\mathbb{R}$ be a continuous and strictly decreasing function, with $\displaystyle \lim_{x\to a^{+}} f(x)=\infty$, that:
$$ \int_a^b (-1)^{\left \lfloor f(x) \right \rfloor}\mathrm dx=(-1)^{\left \lceil  f(b) \right \rceil -1}b +2\sum_{n=\left \lceil  f(b) \right \rceil}^\infty (-1)^{n}f^{-1}(n)$$
where $\left \lfloor m \right \rfloor$ and $\left \lceil  m \right \rceil$ are floor and ceiling function of $m$, respectively. Intuitively, I start with the substitution $f(x)=y$ and then:
$$ \int_a^b (-1)^{\left \lfloor f(x) \right \rfloor}\mathrm dx=\int_{f(a)}^{f(b)} (-1)^{\left \lfloor y \right \rfloor}\left[f^{-1}(y)\right]'\mathrm dy= -\int_{f(b)}^{\infty} (-1)^{\left \lfloor y \right \rfloor}\left[f^{-1}(y)\right]'\mathrm dy$$
Here, I'm having trouble developing the last integral and what I know is that I need to add integrals over some interval which for me is still a mystery. Thanks for some clarification.
Comment: Don't shout!!!!
Answer: Since the floor function is not continuous (let alone differentiable), it seems more promising to start with letting $x_n=f^{-1}(n)$ for all naturals $n\ge n_0:=\lceil f(b)\rceil$.  Then $\{x_n\}_n$ is a sequence in $(a,b]$ and strictly decreasing to $a$.
As the integrand is piecewise constant, we have
$$ \int_{x_{n_0}}^b(-1)^{\lfloor f(x)\rfloor}\,\mathrm dx = \int_{x_{n_0}}^b(-1)^{\lfloor f(b)\rfloor}\,\mathrm dx =(b-x_{n_0})(-1)^{\lfloor f(b)\rfloor}
=(-1)^{n_0}(x_{n_0}-b)$$
and for $n\ge n_0$,
$$ \int_{x_{n+1}}^{x_{n}}(-1)^{\lfloor f(x)\rfloor}\,\mathrm dx=\int_{x_{n+1}}^{x_{n}}(-1)^{n}\,\mathrm dx=(-1)^n(x_{n}-x_{n+1}).$$
By summing and telescoping,
$$\begin{align}\int_{x_{N+1}}^{b}&=(-1)^{n_0}(x_{n_0}-b)+\sum_{n=n_0}^N(-1)^n(x_{n}-x_{n+1})\\
&=(-1)^{n_0+1}b+(-1)^{n_0}x_{n_0}+\sum_{n=n_0}^N(-1)^nx_{n}+\sum_{n=n_0+1}^{N+1}(-1)^nx_{n}\\
&=(-1)^{n_0+1}b+2\sum_{n=n_0}^N(-1)^nx_{n}+(-1)^{N+1}x_{N}
\end{align}$$
Let's assume $a=0$ for the moment. Then if we take the limit as $N\to\infty$ of the right hand side above, we arrive at
$$ (-1)^{n_0+1}b+2\sum_{n=n_0}^\infty(-1)^nx_{n}$$
where the series converges by the Leibniz criterion, while at the same time the left hand side converges to the improper integral from $a$ to $b$, as desired.
In the general case when $a\ne 0$, the series does not converge, while clearly the improper integral does. We can adjust for that: Define $g\colon (0,b-a]\to \Bbb R$, $g(x)=f(x+a)$, do the above with $g$. We can then express the result in terms of $f$ and note that the original claim has to be adjusted to have $(-1)^n(f^{-1}(n)-a)$ instead of $(-1)^nf^{-1}(n)$ as series summand.


Curves And Surfaces Exercise (6) of Chapter 1

Question: I am currently reading the book "CURVES AND SURFACES" [ SECOND EDITION 2009 ] by Ros and Montiel.
I am having trouble to solve and understand Exercise (6) of Chapter 1.
It says the following Exercise Statement :
Show that a curve $ \alpha: I \rightarrow \mathbb{R}^2 $ is a segment of a straight line or an arc of a circle if and only if all its tangent lines are equidistant from a given point in the plane.
Also the Hint given says :
Assume that $a\in \mathbb{R}^2 $ is the point from which all the tangent lines of the curve $ \alpha: I \rightarrow \mathbb{R}^2 $ are equidistant. Let $ s \in I $ be an arbitrary parameter value. The tangent line to the curve at $ s $ passes through $ \alpha(s) $ and is perpendicular to $ N(s)$ , the normal vector at $ s$.
We have
$$
\langle \alpha(s) - a, N(s) \rangle = c,
$$
where $ \langle \cdot, \cdot \rangle$ denotes the inner product, $ c \in \mathbb{R} $ is a constant, and $ s \in I $.
Taking derivatives and using the Frenet equations, we get that for each $ s \in I$ , either $ k(s) = 0 $ or $ 1 + ck(s) = 0 $.
Since $ k $ is continuous, it follows that $ k $ is either identically zero or identically $ -1/c $ over $ I $.
My Problem : I do not understand how to arrive at the equation
$$
\langle\alpha(s) - a, N(s) \rangle = c.
$$
I think it makes the additional assumption that the distance between the tangent line and the point $a$ is realized at $\alpha(s)$, which I do not see why it should be the case.
It could be realized at a point $\alpha(s) + \lambda(s) \cdot \alpha'(s)$ for some $\lambda(s) \in \mathbb{R}$ ...
Answer: No, you don't need that additional assumption. As you observed, without it we obtain an equation of the form
$$\langle\alpha(s)+\lambda(s)\alpha'(s)-a, N(s)\rangle= \pm c$$
for some constant $c \geq 0$.
But now just note that
$$\langle \alpha'(s), N(s)\rangle =0$$
which yields exactly
$$\langle\alpha(s)-a, N(s)\rangle= \pm c$$
where the sign $\pm$ is uniquely determined by continuity.
Answer: Denote by $\beta(s)$ the point on the tangent where the minimum distance to $a$ is achieved. We have
$$c=\langle \beta(s) - a, N(s) \rangle = \langle \beta(s) -\alpha(s) + \alpha(s)- a, N(s) \rangle = \langle \alpha(s) - a, N(s) \rangle$$ as $\langle \beta(s) - \alpha(s), N(s) \rangle = 0$. Proving the desired result.
Comment: That seems almost identical to my answer....
Comment: @DarkMagician If you mean that your answer looks almost the same as mine... I do agree! ;-)!


$\Lambda$ a lattice in $\Bbb{C}^g$, $\Bbb{C}^{g'}$ is subvector space of $\Bbb{C}^g$. $\Lambda$ image in $\frac{\Bbb{C}^g}{\Bbb{C}^{g'}}$ a lattice?

Question: $\Lambda$ is a lattice in $\Bbb{C}^g$ and $\Bbb{C}^{g'}$ is a subvector space of $\Bbb{C}^g$ where $\Bbb{C}$ is complex number.
$\textbf{Q:}$ Is $\Lambda$ image in $\frac{\Bbb{C}^g}{\Bbb{C}^{g'}}$ a lattice? I could not see discreteness of $\Lambda$'s image here. If not, what is the counter example?
Comment: Ok, I understand. Although you should not say that $\Bbb{C}$ is a complex number since it is rather the set of complex numbers
Answer: No. Consider the case where $g=2$, $g'=1$ and consider the lattice $\Lambda$ which is generated as an abelian group by $(1,0),(i,0),(\sqrt2,1),(i\sqrt2,i)$ ($\Lambda$ is a lattice since the elements are a basis for $\Bbb{C}^2$ as a vector space over $\Bbb{R}$). We need to be specific about which subspace of $\Bbb{C}^2$ we are referring to; consider the space $\{(0,x)|x\in \Bbb{C}\}\cong \Bbb{C}^1$. Then in the quotient, $\pi(\Lambda)$ will be generated by $\overline{(1,0)},\overline{(\sqrt2,0)},\overline{(i,0)},\overline{(i\sqrt2,0)}$ (where $\overline{(a,b)}$ denotes a coset in the quotient.). Then $\pi(\Lambda)$ will still be isomorphic to $\Bbb{Z}^4$ as an abelian group. But to be a lattice in the quotient, it needs to be isomorphic to $\Bbb{Z}^2$ since the quotient space has dimension $2$ over $\Bbb{R}$.
Comment: I am pretty sure this answer is wrong as in $C=R^2$, the maximal rank is at most 2. There could not be a rank 4 free abelian group in $R^2$ or you will violate rank invariant theorem.
Comment: Are you referring to the theorem that the rank of a submodule over a PID is less than or equal to the rank of the original module?
Comment: In this case, to talk about the theorem, we need to think about $\Bbb{R}$ and $\Bbb{C}$ as $\Bbb{Z}$-modules since lattices are $\Bbb{Z}$-modules but not $\Bbb{R}$-modules. But $\Bbb{R}$ and $\Bbb{C}$ have infinite rank as $\Bbb{Z}$-modules
Comment: What? $\Lambda$ is a lattice.(i.e. Discrete group.) The theorem says for discrete abelian subgroup/lattice in $R^n$, it can be as $Z-$module by at most $n$ elements. Ref. Pierre Samuel, Algebraic Number Theory, Thm 1 of chpt 4.
Comment: Ok, the problem then is that we did not project onto a lattice, but the theorem only applies to lattices/discrete abelian subgroups in $\Bbb{R}^n$. In the example, notice that the image of lambda is not a discrete subgroup


Why this specific string is untranslatable

Question: I want to translate "You can only change the parent menu item for the published version of this content" which belongs to  Menu UI module.
The string is defined in /core/modules/menu_ui/src/Plugin/Validation/Constraint/MenuSettingsConstraint.php like below:
<?php

namespace Drupal\menu_ui\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Validation constraint for changing the menu settings in pending revisions.
 *
 * @Constraint(
 *   id = "MenuSettings",
 *   label = @Translation("Menu settings.", context = "Validation"),
 * )
 */
class MenuSettingsConstraint extends Constraint {

  // This string is untranslatable.
  public $message = 'You can only change the menu settings for the published version of this content.';
  public $messageWeight = 'You can only change the menu item weight for the published version of this content.';
  public $messageParent = 'You can only change the parent menu item for the published version of this content.';
  public $messageRemove = 'You can only remove the menu item in the published version of this content.';

}

This extends a class from Symfony and doesn't use t() function, but other strings defined in the same way are translatable(which means you can find the string in the localize.drupal.org). Below is an example of a translatable string.
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <email@example.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 * @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
 *
 * @author Fabien Potencier <email@example.com>
 * @author Bernhard Schussek <firstname.lastname@example.com>
 */
class Expression extends Constraint
{
    const EXPRESSION_FAILED_ERROR = '6b3befbc-2f01-4ddf-be21-b57898905284';

    protected static $errorNames = [
        self::EXPRESSION_FAILED_ERROR => 'EXPRESSION_FAILED_ERROR',
    ];

    // This string is translatable.
    public $message = 'This value is not valid.';
    public $expression;

    /**
     * {@inheritdoc}
     */
    public function getDefaultOption()
    {
        return 'expression';
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredOptions()
    {
        return ['expression'];
    }

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return 'validator.expression';
    }
}

I guess there're Drupal wrappers to make the strings originated in Symfony class implementations translatable. But why does the string in Menu UI remain untranslatable? It's not urgent, but I'm curious.
EDIT:
 Entity Validation API overview says
"Symfony validator is configured to use a Drupal translator class, such that violation messages correctly run through t(). ". So if my understanding is right, the untranslatable string also gets wrapped in t() eventually...?
Answer: There are two different aspects. The first one is how Drupal compiles the core translation list. This is based on the (not running) PHP code using the Translation template extractor (POTX).
You find only the first of the four messages on localize.drupal.org because of a naming issue in this particular constraint. Drupal searches for translation strings in certain locations and $messageParent doesn't match:
/**
 * Detect validation constraint messages. Drupal 8+.
 *
 * This sequences is searched for:
 *   T_POTX_CONSTRAINT = T_CONSTANT_ENCAPSED_STRING.
 *
 * note: T_POTX_CONSTRAINT is marked for T_VARIABLE tokens inside .php files
 *   with the "Constraint" suffix, where the token is "$message", or ends
 *   with "Message"
 *
 * @param string $file_name
 *   Name of file parsed.
 * @param string $save_callback
 *   Callback function used to save strings.
 */
function _potx_find_constraint_messages($file_name, $save_callback) {

See https://www.drupal.org/project/potx/issues/2884361#comment-13052396
The second aspect is about the run-time behavior. Symfony contraints are integrated into the Drupal translation system, so that messages are wrapped in a Drupal translatable markup object.
So a quick fix would be to visit the site in a non english language and trigger the error, then the string will be added to the translation list of your local site.
Comment: The first string appeared in /admin/config/regional/translate after I triggered the error following @4k4's advice. Thanks a lot!


Como fazer um Dowload no IE via VBA?

Question: Olá estou utilizando o seguinte código para iniciar um dowload no Intenet Explorer.

Public Sub Dashboard()
    Dim Navegador As InternetExplorer
    Dim objShellWindows As New SHDocVw.ShellWindows
    Dim currentWindow As HTMLWindowProxy
    Dim url As String

    On Error GoTo Erro
    url = "http://..................../"
    Set Navegador = New InternetExplorer
    Navegador.navigate url
    Navegador.Visible = True

    Do While Navegador.readyState <> 4
        DoEvents
    Loop

    'Faz login
    Navegador.document.getElementById("usuario").Value = "xxxxxxxx"
    Navegador.document.getElementById("senha").Value = "xxxxxx"
    Navegador.document.getElementById("bt_entrar").Click
'    Set Navegador = Nothing
'    Set Navegador = New InternetExplorer
'    Navegador.navigate url
'    Navegador.Visible = True

    Do While Navegador.readyState <> 4
        DoEvents
    Loop

    Navegador.document.getElementById("submenu2_SatisfacaoGeral").Click
    Set currentWindow = Navegador.document.parentWindow
    currentWindow.execScript code:="chart.exportChart()"

Erro:
    MsgBox Err.Description
    Resume Next
 End Sub

acontece que eu não sei como eu posso "salvar como o download" definindo a pasta e o Nome do arquivo.
Comment: Esse não serve para o meu caso, o script que eu executo, já inicia o Download, eu preciso manipular a janela do IE, alterando nome do arquivo e local de salvamento.
De medida paliativa estou usando o .SendKeys:
`Set JanelaSite = IE.document.parentWindow
    JanelaSite.execScript code:="chart.exportChart()"

    Application.Wait (Now + TimeValue("0:00:02"))
    JanelaSite.Focus
    'JanelaSite.document.execCommandShowHelp ("SaveAs")
    tela.SendKeys "{TAB}"
    tela.SendKeys "{TAB}"
    tela.SendKeys "{DOWN}"
    tela.SendKeys "{DOWN}"
    tela.SendKeys "{ENTER}"`
Comment: Não entendo de IE, mas se for útil, encontrei alguns links: [1](https://www.mrexcel.com/forum/excel-questions/567033-automate-file-download-dialog-box-without-sendkeys.html), [2](http://www.siddharthrout.com/2012/02/02/vbavb-netvb6click-opensavecancel-button-on-ie-download-window-part-ii/),[3](https://stackoverflow.com/questions/37664260/click-on-an-ie-window-without-sendkeys-or-mouseevent-vba)
Comment: Já tentou usar [este método](https://stackoverflow.com/a/29367304/7690982)?
Answer: Você consegue interagir com o PDF, por exemplo, baixando-o pelo URL criado para uma pasta especificada, usando a função URLDownloadToFile,
Declare Function URLDownloadToFile _
    Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
    Function DownloadFile(URL As String, LocalFilename As String) As Boolean
        Dim lngRetVal As Long
        lngRetVal = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
        If lngRetVal = 0 Then DownloadFile = True
    End Function
    Sub test()
        URL = Navegador.LocationURL 'URL do pdf
        DownloadFile URL, "C:\PASTA\EXEMPLO.pdf" 'Pasta e nome do arquivo
    End Sub

Comment: Olá Marcelo, vou testar aqui e te falo.
Eu até consegui sem utilizar ".SendKeys", mas não consegui alterar o nome do arquivo e ainda esbarrei em outro problema, o IE começou a inserir Números (aleatórios) no nome do arquivo (acho que pelo número de download). Por isso tive que criar uma página em PHP e consegui fazer tudo que queria.
Comment: Tentei aqui, o problema é que no meu caso o comando que eu executo já inicia o download. Eu queria manipular a janela de Download pra alterar o nome do arquivo e o local.

Como fazer um Dowload no IE via VBA?


Reducing trigonometry functions in exponents

Question: I need to know a bit about replacing the trig functions in exponents with simpler algebraic equations which can then be reduced with logarithms. For example, an answer to this question said that
$$e^{\sin(x)} = e^{\frac{1}{2i}(e^{ix} - e^{-ix})}$$
applies, which would do the trick. As well as this, using a few basic log rules it could be adjusted to deal with any base as well. I do have a few questions though.
Firstly, how does this work? It looks like it has a fair bit to do with Euler's identity but I don't understand the exact derivation.
Next, how do I generalize it (For example, with the exponent as $4*sin^2(3x)$)? I honestly don't know if it barely involves changing numbers or if it doesn't apply at all anymore.
Finally, is this transferrable to the other trig functions? If it's connected to Euler's identity as I think it is, it should be easy to change it to apply to cosine instead, and then the two together may somehow be used to derive the transformation (if I can call it that) to tan.
Thank you so much for your help!
Answer: The derivation of the definitions of $\sin x$ and come from subtracting Euler's formulas.
\begin{align}
e^{ix}&=\cos x+i\sin x\\
e^{-ix}&=\cos x-i\sin x\\
\implies\sin x&=\frac1{2i}(e^{ix}-e^{-ix})
\end{align}
It therefore follows that $$\exp(\sin x)=\exp\left(\frac1{2i}(e^{ix}-e^{-ix})\right).$$
For your example, we can write
\begin{align}
4\sin^2(3x)=4(\sin(3x))^2&=4\left(\frac1{2i}(e^{3ix}-e^{-3ix})\right)^2\\
&=-(e^{3ix}-e^{-3ix})^2\\
&=2-e^{6ix}-e^{-6ix}\\
\implies\exp(4\sin^2(3x))&=\exp(2-e^{6ix}-e^{-6ix}).\\
\end{align}


Show that a topology is a first countable space

Question:
Let $\tau$ be the topology on the real line $\mathbb{R}$ generated by the closed open intervals $[a,b)$. Show that it is a first countable space.

So, what I think I have to do is to show that for any point $p \in \mathbb{R}$ there is a countable local base, for example $$B_{p}= \left\{\left[p,n^{-1} \right)\; n \in \mathbb{N}\right\}$$
My reasoning is that the open spheres in this topology are the same close open intervals and that the open sphere is getting smaller as $n$ increases and all of those balls include $p$. Am i correct?
Comment: Almost there. You're morally correct. We just replace the usual $(p-1/n,p+1/n)$ by $[p,p+1/n)$.
Comment: Thank you, i got it now :)
Answer: That's not going to work unless $p=0$. If $p\ge 1$, the sets $\left[p,\frac1n\right)$ are all empty. However, you could let
$$\mathscr{B}_p=\left\{\left[p,p+\frac1n\right):n\in\Bbb Z^+\right\}\,.$$
To prove that this is a local base at $p$ you must show that if $U$ is any open nbhd of $p$ in this topology, there is an $n\in\Bbb Z^+$ such that $p\in\left[p,p+\frac1n\right)\subseteq U$. You can start by observing that the sets of the form $[a,b)$ with $a<b$ are a base for the topology, so if $U$ is an open nbhd of $p$, there must be $a,b\in\Bbb R$ such that $p\in[a,b)\subseteq U$. Now you just have to explain why there is an $n\in\Bbb Z^+$ such that
$$\left[p,p+\frac1n\right)\subseteq[a,b)\,.$$


What does this mean in MySQL?

Question: <code>C:\Documents and Settings\Administrator>mysqld-nt --defaults-file="D:\MySQL\MySQ
L Server 5.0\my.ini" --standalone --console
100125 10:47:26  InnoDB: Operating system error number 32 in a file operation.
InnoDB: Some operating system error numbers are described at
InnoDB: http://dev.mysql.com/doc/mysql/en/Operating_System_error_codes.html
InnoDB: File name .\ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
</code>
Answer: The first line starts MySQL. It errors out. Looking up the error message at the URL provided by the error message suggests that:

The process cannot access the file because it is being used by another process.

I'd guess that MySQL is already running or didn't stop cleanly previously. If you've never seen this before, a reboot would probably help. If it happens a lot, you'll need to figure out why the files are being locked. Some of the SysInternals tools can help with that.

What does this mean in MySQL?


Java Swing how to draw polygons with coordinate params when layout is not absolute

Question: I am trying to make a little GUI using swing. I would like it to draw a polygon on a JPanel that has a GridBagLayout. How do I do this? Can I give the polygon coordinates to draw from? Are the coordinates based on the cell the polygon is drawn in, or the JPanel, or the Frame?
Initially to test, I have just tried to draw a line with coordinates in the class I have, and then add it to the JPanel. Nothing is drawn.
The overriden paintComponent method I have in the class UniverseDisplay is:
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.black);
    g.drawLine(20,  20,  30,  30);
    System.out.println("PAINTED");
}

The function I have which sets up a UniverseDisplay and which causes paintComponent to be called is as follows:
public void setUpGenerateButton(){
    generateButton = new JButton("Generate Model");
    generateButton.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    Universe u = new Universe(reflexive, transitive, symmetric, hereditary);
                    World w = new World(u);
                    u.addWorld(w);
                    Tree t = new Tree();
                    t.setRoot(t);
                    t.setData(expressions, 0, expressions.size());
                    t.setInitialWorlds(w);
                    t.setInitialUniverses(u);
                    t.evaluateModalExpressionV2(u);
                    /*
                     * this bit below isnt actually painting anything on the
                     * JPanel even though paintComponent() is being called properly
                     */
                    UniverseDisplay ud = new UniverseDisplay(u);
                    rightPanel.add(ud);
                    rightPanel.revalidate();
                    rightPanel.repaint();
                }
            });
}

The JPanel is set
public void setUpPanels() {
    setUpTextInputField();
    setUpGenerateButton();
    setUpPropsPanel();
    setUpButtons();
    setUpClearButton();

    leftPanel = new JPanel();
    rightPanel = new JPanel();
    leftPanel.setLayout(new GridBagLayout());
    rightPanel.setLayout(new GridBagLayout());

    leftPanel.setBackground(Color.gray);
    rightPanel.setBackground(Color.white);

    /*
     * create a new constraints for each new component, to avoid bugs
     */
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 0;
    leftPanel.add(inputL, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 1;
    leftPanel.add(inputField, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 1;
    constraints.gridy = 1;
    constraints.insets = new Insets(0, 15, 0, 0);
    leftPanel.add(generateButton, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 2;
    leftPanel.add(propsL, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 3;
    constraints.insets = new Insets(10, 0, 0, 0);
    constraints.fill = GridBagConstraints.BOTH;
    constraints.anchor = GridBagConstraints.WEST;
    leftPanel.add(propsPanel, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 1;
    constraints.gridy = 3;
    constraints.ipadx = 30;
    constraints.ipady = 70;
    constraints.anchor = GridBagConstraints.WEST;
    constraints.insets = new Insets(10, 15, 0, 0);
    leftPanel.add(buttonPanel, constraints);

    constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 4;
    constraints.insets = new Insets(10, 0, 0, 0);
    constraints.anchor = GridBagConstraints.WEST;
    leftPanel.add(clearButton, constraints);

    add(leftPanel);
    add(rightPanel);
}

Why is that no line is drawn in the JPanel? How do I go about drawing shapes in a JPanel that does not have its layout set to null?
I hope that is enough information for a useful answer :)
Comment: For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/).
Answer: When you do custom painting you are responsible for determining the preferred size of the component. This is done by overriding the getPreferredSize() of your component.
So in your case you need to use:
@Overrid
public Dimension getPreferredSize()
{
    return new Dimension(50, 50);
}

Then the layout manager can use the preferred size information to position the component in your layout.