Serving video with Node.js

Question: I am writing a simple Node.js server to serve videos from my laptop into my local network.
I have been searching around, to check the best way, and I found two ways of doing it, I would like some help figuring out if there is one way that is preferred over the other when it comes to serve video files using nodejs.
Video files would be huge video files, movie size....
Option 1: using Express:
I have seen some people that, after creating all the usual boilerplate code for an Express server, when it comes to sending the video, they would just do something like:
app.get('/getMovie', (req, res) => {
    res.sendFile('assets/video.mp4', { root: __dirname });
});

Option 2: using Http:
For this option, after creating the http server and so on, people would create first a ReadStream using fsand then send the video. Something like:
res.writeHead(200, {'Content-Type': 'video/mp4'});
let readStream = fs.createReadStream("movie.mp4");
readStream.pipe(res);

For me, option 2 sounds more reasonable when it comes to huge video files, but, not sure which one would be best and why.
Comment: Why even use Node.js for this?  Any static HTTP server would be fine.
Comment: because the server. is custom made and written in Node.js
Answer: Express server-static will accept range requests so it does not actually serve the entire video file in one go.
Range requests allow the client to request the video in chunks. So long as the headers are at the start of the video this allows the client to start playing the video as it downloads it.
The network messaging below from a browser inspection, safari in this case, shows an example of a request to a server for a video that accepts range requests:

You can see the response include information that informs the client, a browser in this case, that the server accepts range requests.
If you look at the following request in the left of the image you can see that it requests the video chunk by chunk from a start to an end byte. For example here is a request and response for bytes 81920 to 98303:

You can see more about Express serve-static here: http://expressjs.com/en/resources/middleware/serve-static.html
Comment: thanks for your comment! so you think it is better to use Express than Http?
Comment: Actually most static HTTP servers will now probably accept range requests so you can probably use whatever one you want. If you want a more sophisticated streaming service then its generally better to use a dedicated streaming server which supports an ABR streaming protocol like HLS or DASH - see here to geta feel for what ABR looks like: ABR: https://stackoverflow.com/a/42365034/334402

Serving video with Node.js


Reporting glmer.nb Results

Question: I'm running a mixed negative binomial GLM that looks like this:
Niche2 <- glmer.nb(log_density ~ height * factor(Year) + (1 | Grouping), data = NicheData2)

To see if the way sward height determines the density (log transformed for normality) of a herbivorous insect has changed over time (so I'm particularly interested in the interactions between years and height). The random effect of grouping is of the different sites sampled in different years (to account for temporal pseudoreplication).
> summary(Niche2)
Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
Family: Negative Binomial(225251.6)  ( log )
Formula: log_density ~ height * factor(Year) + (1 | Grouping)
 Data: NicheData2

     AIC      BIC   logLik deviance df.resid
   341.4    364.3   -162.7    325.4      122

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.2436 -0.4351 -0.1003  0.3726  2.1061

Random effects:
 Groups   Name        Variance  Std.Dev.
 Grouping (Intercept) 1.591e-10 1.261e-05
Number of obs: 130, groups:  Grouping, 45

Fixed effects:
                        Estimate Std. Error z value Pr(>|z|)
(Intercept)              0.65834    0.27708   2.376   0.0175 *
height                  -0.08548    0.04371  -1.956   0.0505 .
factor(Year)2010         0.17000    0.43243   0.393   0.6942
factor(Year)2018        -0.40936    0.46493  -0.880   0.3786
height:factor(Year)2010  0.03534    0.05402   0.654   0.5130
height:factor(Year)2018  0.08860    0.05360   1.653   0.0983 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) height f(Y)2010 f(Y)2018 h:(Y)2010
height      -0.873
fctr(Y)2010 -0.650  0.567
fctr(Y)2018 -0.555  0.485  0.361
hgh:(Y)2010  0.713 -0.814 -0.871   -0.396
hgh:(Y)2018  0.684 -0.791 -0.444   -0.853    0.644

I'd like to know the correct way to report these results, (presumably the coefficients, the standard errors, and the p values, while also explaining how much variation is fuelled by the random effect), but I understand that the coefficients need transforming.
Could someone please advise me on the right way to transform these, and how to report the variation due to the random effect?
I've had a look at other questions particularly this one (How to report negative binomial regression results from R) but haven't managed to apply their answers to my model.
EDIT: Following advice, re-ran the model with length as an offset and the response variable as adjusted count data, am keen to know the best way to report the co-efficients (and does the offset change the way I should do this).
Generalized linear mixed model fit by maximum likelihood (Laplace
Approximation) ['glmerMod']
 Family: Negative Binomial(1.7478)  ( log )
Formula: adjusted ~ height * factor(Year) + (1 | Grouping) +
offset(log(length))
   Data: NicheData2

     AIC      BIC   logLik deviance df.resid
  1105.8   1128.2   -544.9   1089.8      114

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.2672 -0.6135 -0.2009  0.5125  3.6734

Random effects:
 Groups   Name        Variance Std.Dev.
 Grouping (Intercept) 0.553    0.7436
Number of obs: 122, groups:  Grouping, 39

Fixed effects:
                        Estimate Std. Error z value Pr(>|z|)
(Intercept)             -2.77889    0.33069  -8.403   <2e-16 ***
height                  -0.09984    0.04466  -2.235   0.0254 *
factor(Year)2010         0.11267    0.45323   0.249   0.8037
factor(Year)2018        -0.47509    0.51415  -0.924   0.3555
height:factor(Year)2010  0.03472    0.05173   0.671   0.5021
height:factor(Year)2018  0.08253    0.05486   1.504   0.1325
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Correlation of Fixed Effects:
             (Intr) height f(Y)2010 f(Y)2018 h:(Y)2010
 height      -0.827
 fctr(Y)2010 -0.520  0.458
 fctr(Y)2018 -0.446  0.397  0.388
 hgh:(Y)2010  0.625 -0.749 -0.862   -0.400
 hgh:(Y)2018  0.589 -0.715 -0.413   -0.866    0.613

Answer: A couple of comments:

The estimated variance of the random effect is extremely low. This could indicate that you do not need to include the random effect (i.e., there are correlations in the measurements within each group) or could be an artifact of the estimation procedure. In particular, glmer.nb() fits the negative binomial mixed model using the Laplace approximation, which is known not to be optimal. As an alternative, you can try fitting the same model using the GLMMadaptive package, which uses the adaptive Gaussian quadrature rule; for example, check here.
In mixed models with nonlinear link functions, as in your case with the negative binomial mixed model, you have to be aware that the estimated coefficients you obtain have an interpretation conditional on the random effects. Most often this is not the interpretation you are looking for, but instead, the interest most often lies in a marginal / population interpretation. For more on this, you may check the discussion in this question. When you fit the model with GLMMadaptive you can obtain the coefficients with a marginal interpretation using the function marginal_coefs(); for example, check here.
Comment: @IsabellaGhement yes, you're right. Nonetheless, AFAIK it is also used with non-integer response variables. An example I know of is RNAseq data, which are normalized counts (i.e., originally you have integer RNA counts, but then they normalize them to account for what is called library size). In standard software for RNAseq (e.g., https://bioconductor.org/packages/release/bioc/html/edgeR.html) they still use the negative binomial distribution. I thought of this case to be something similar.
Comment: Indeed, also in my **GLMMadaptive** package, this version is programmed, and hence it also works for the "continualized" negative binomial distribution.
Comment: I think the motivation is that is has a specific mean-variance relationship that you will not have if your fit it as a normal distribution.
Comment: Maybe I am missing something, but doesn't a mixed effects negative binomial regression model need a response variable which is a count variable (possibly with inclusion of an offset)? The response variable in this model is log density, which is a continuous rather than a count response.
Comment: Thanks, Dimitris! As always, I'm learning a lot from you! ❤
Comment: I found a link on this website which discusses the "continualized" (i.e., continuous version of the) Negative Binomial distribution: https://stats.stackexchange.com/questions/310676/continuous-generalization-of-the-negative-binomial-distribution. I guess my original comment came from not knowing if the glmer.nb function is smart enough to use a "continualized" NB distribution when being fed continuous data rather than counts (?).
Comment: Wouldn't it be cleaner to just use lmer on the log density and then exponentiate the lmer coefficients and interpret results in terms of % increase/decrease in density for an extra unit of height in a specific year?
Comment: Just trying to understand the benefit of using continualized NB over normal distribution when modelling log density? When would we be justified in using one versus the other? Also, how does one interpret the coefficients from a continualized NB?
Comment: Thanks for your comments, guys! @DimitrisRizopoulos, would you be able to explain why the GLMMadaptive is superior, and how to report the marginal co-efficients it reports (would I just exponentiate them as suggested by Isabella)?
Comment: **GLMMadaptive** implements the adaptive Gaussian quadrature rule to approximate the integrals over the random effects, which is known to be a better algorithm for evaluating the likelihood of the model. Regarding the coefficients, yes, you would need to exponentiate them to bring them to the scale of the mean of the negative binomial distribution.
Comment: Thanks @Dimitris! In the end I ran the model again, but used length as an offset and counts as the response (since this was independently suggested to me at the same time). The variance explained by the random effect is now healthier-looking. Just wondered if you could advise on the interpretation of this. I've edited the question to include this. Thanks.

Reporting glmer.nb Results


Python subprocess.Popen() not working in a docker container - works fine locally

Question: I have created a Django REST framework project that I want to deploy on a server. I do not have admin access to the server, and so, the only way I found to ensure that all the project dependencies (such as Anaconda distribution) will be available on the server, is to create a docker image for my project , then create a corresponding container on the server, then run it from there.
In my project, I have a python script (mymain.py) that gets called using subprocess.Popen().
This works fine locally, and subprocess.Popen() does everything it is supposed to do.
However, when I try to do it from the docker container, it seems as if the line subprocess.Popen() was completely skipped [mymain.py is not called].
For docker, I have created a docker-compose.yml file, and in command prompt I type:
docker-compose up

I do not see any error, and everything seem to be working fine, however subprocess.Popen() does not seem to be working.
mymain.py first line is:
print('Testing if subprocess called mymain.py!!!')

In a different file, I call subprocess.Popen().
I tried printing out the error, but unfortunately, both stdout and stderr return nothing:
p = subprocess.Popen(['python', mymain_path, args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
print('SUBPROCESS ERROR: ' + str(err))
print('SUBPROCESS stdout: ' + str(out.decode()))

And this is what I get:
SUBPROCESS ERROR: None
SUBPROCESS stdout:

As you can see, the first line of my main.py was never printed...
However, when I do this locally by typing in command prompt:
python manage.py runserver 9000

everything works with no issues (the line 'Testing if subprocess called mymain.py!!!' gets printed).
I even tried to open the docker container shell and type the same 'python manage.py runserver 9000' command in there, but that did not work unfortunately.
Now the question is, how do I get subprocess to work remotely (in a docker container)?
Any help on this is very appreciated!
I am using:
Docker version 18.09.2, build 6247962
docker-compose version 1.23.2, build 1110ad01
Python 3.7.0

Answer: Looks like a way to get rid of this issue is to:
1. use 'shell=False'
2. Not have a return value for the 'subprocess.Popen()'
subprocess.Popen(['python', mymain_path, args], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Comment: This helped me very much!
Looks like shell=True seems to hide stdout, especially on error!
I suggest to mark this as the accepted answer.

P.S.adding -u to python call solved my case (I needed shell=True), since it seems the shell didn't flush the output if an exception happened!
Answer: Had exactly the same problem, none of previous fixes worked for me.
Finally I tried
print("Hello world!", flush=True)

which seems to work in my environment (docker, python3.7)


How to show/hide single div only with jquery .slidetoggle

Question: How to show/display a single one div only when user click with jquery
For example when user click the "Promo" the promo content will show,
and when user click "Sports" the sports content will display and the promo content will hide... so on

I have this working code but when I click it shows all the content at once.
HTML

Promo

 Content for promo

Sports

 Content for Sports

News

 Content for News

CSS
.showcontent {
    display: none;
}

JS
  $('.clickto_showme').click(function() {
        $('.showcontent').slideToggle('slow');
        return false;
    });

A working JSFIDDLE is here http://jsfiddle.net/jowa513p/2/
Answer: Use $(this) to manipulate the required element relative to the current element clicked; and next() to get the sibling.
$('.clickto_showme').click(function() {
    $(this).next('.showcontent').slideToggle('slow');
    return false;
});

Updated Fiddle
Comment: nice. its perfect @ShaunakD
Comment: Use `$(this).closest('.promotion_item_container').next('.show_promotion').slideToggle('slow');` as the promotion element is not the direct sibling/next element. http://jsfiddle.net/9yafbbh8/1/ Also `#details_pane` ID occurs multiple time s and duplicate IDs are invalid. Use class=details_pane
Comment: you are right because of ID "#details_pane" causing trouble.


puzzle in derivation of entropy of sum

Question: I was reading through a derivation of an entropy of a sum example, and cannot understand one step.
The statement to be proven is if $Z=X+Y$ then $H(Z|X) = H(Y|X)$, where H() is discrete Shannon entropy.
The derivation:
$Z = X+Y$, Hence note $p(Z=z|X=x) = p(Y=z-x|X=x)$.
\begin{align}
H(Z|X) &= \sum p(x) H(Z|X=x)
\\
 &= -\sum_x p(x) \sum_z p(Z=z|X=x) \log p(Z=z|X=x)
\\
 &= -\sum_x p(x) \sum_y p(Y=z-x|X=x) \log p(Y=z-x|X=x)
\\
 &= \sum p(x) H(Y|X=x)
\\
 &= H(Y|X)
\end{align}
My issue is the step introducing probability $p(Y=z-x|X=x)$.
First, I think this probability is always $1$,
because $Y$ is defined to be $z-x$, so how can it be anything else?
Second, an expression $\sum_y p(Y=z-x)$ bothers, because in summing over the index $y$, $y$ is supposed to be an independent thing, but here $Y$ depends on $x$ through $Y=z-x$.  Actually the notation in the derivation does not clarify $y$ verus $Y$ also.
Answer: The notation convention here is that the capitalized letter denotes a random variable, and the lower-case letter denotes a possible value for the corresponding random variable. For example if $X$ and $Y$ are the respective results of two rolls of a die, then $x$ would be any one of $1, 2, 3, 4, 5, 6$. Similarly $y$ stands for any one of those same six values.
In your derivation, for a given $x$ the quantity $P(Y=z-x\mid X=x)$ is not always $1$, since $Y$ and $X$ (and $Z$) are random variables and can take a variety of values. Try plugging values like $x=3, z=8$ in the die-rolling example.  If you know that $X=3$, the conditional probability is not $1$ that $Y=8-3$.
For your second question, the expression $\sum_y p(Y=z-x\mid X=x)$ has a typographical error. It should be $\sum_z p(Y=z-x\mid X=x)$. To get the next line you realize that for a given $x$, summing over all possible values of $z$ is the same as summing over all possible values of $y$, so the inner sum is  just $H(Y\mid X=x)$.
Comment: And I think I understand the second. To restate, you are saying that, although with x fixed, Y and z differ by an offset, in evaluating the all possible probabilities (1-6 for the dice), Y must take on the 1-6 range, or z takes on the range 1-x .. 6-x, so the sum is equivalent, just with different start end points.
Comment: I briefly thought I understood the first point, but decided no.

Z is _defined_ to be X+Y, so all the randomness in Z is due to X,Y. It does not add any extra randomness.

Thus if Z is known, and X is known, Y can be exactly determined as Z-X.

If this is correct, I guess the clue is that z is different from Z?  z is taking on all values during the sum, which in turn forces Y to take on its range of values, all conditioned on X=x.

Does this sound like I understand?
Comment: @isolatedstudent Yes, your understanding is correct: $Z$ is different from $z$.

puzzle in derivation of entropy of sum


Caixa flutuante com CSS e HTML

Question: Eu gostaria de saber como criar uma caixa flutuante que escurecesse a tela atrás e aparecessem informações no centro da pagina , procurei no stackoverflow br e não encontrei algo semelhante.
Queria algo tipo a opção que o uol ou a folha de são paulo usam de aviso para desativar o AdBlock.
So que não consigo copiar o código pra fazer funcionar.
Comment: Vc está usando algum Framework tipo Bootstrap ou algo do tipo?
Comment: Não amigo , somente html e css , você me recomendaria alguma?
Answer: Basicamente são criadas duas divs, uma que é a responsável por escurecer o conteúdo e que fica entre o conteúdo da página e o modal. E a outra que vai conter as informações.

function fecharModal()
{
  document.getElementById('fundo').style.display = 'none';
  document.getElementById('modal').style.display = 'none';
}

function abrirModal()
{
  document.getElementById('fundo').style.display = 'block';
  document.getElementById('modal').style.display = 'block';
}
#fundo {
  opacity: 0.8;
  background-color: #000;
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 98;
  top: 0;
  left: 0;
  display: none;
}

#modal {
  width: 150px;
  height: 150px;
  left: 50%;
  top: 50%;
  margin: -75px 0 0 -75px;
  position: fixed;
  background-color: #fff;
  z-index: 99;
  display: none;
}
abrir

  fechar

Comment: beleza era isso que eu queria , so que eu consigo colocar botões de fechar e abrir essa página?
Comment: Pra isso tu precisa usar JS. Editei minha resposta com essas duas ações.
Comment: Obrigado amigo, dei a reposta pra você.

Caixa flutuante com CSS e HTML


Hypothesis space of Naive Bayes and kNN

Question: I am confused about the hypothesis space of those two classifiers.
In the case of linear regression, it's pretty straightforward ; the possible hypothesis are equations of lines, that is, linear combinations of the features. Therefore, the hypothesis space is the space of all possible coefficient values.
But for kNN and NB, I don't clearly see what is the space of parameters you can act upon, and therefore I cannot define any hypothesis space. In the case of NB, I have seen it can correspond to a linear separator as well, therefore the hypothesis space would also be all the linear combinations of odds ratios? But in the case of kNN, it is totally unclear to me.
Answer: In KNN, your hypothesis space depends on the density according to your $k$ neighbors (in a 2 dimensional feature vector picture a circle encircling all your $K$ neighbors). Then the density is $P(x) = \frac{k}{NV}$, where $k$ is the number of observations inside the volume $V$, and $N$ is the total number of observations.
Answer: You can think of hypothesis space of linear regression as the set of linear functions of your features. For simplicity assume the feature space is the entire $\mathbb R^d$. Then, the hypothesis space of linear regression is
$$
\mathcal F = \{f: \mathbb R^d \to \mathbb R :\; f(x) = \beta^T x, \quad \forall x \in \mathbb R^d,\; \text{and some $\beta \in \mathbb R^d$}\}.
$$
This class is a parametric family and can be equivalently described by the set of coefficients $\{ \beta:\; \beta \in \mathbb R^d\}$.
The k-NN regression is a nonparametric approach. The hypothesis space is  the class of all functions that are piecewise constant on the cells of the $k$th order Voronoi diagram of some set of $n$ points in $\mathbb R^d$.
To be more precise, for a collection of points $\{x_i\}_{i=1}^n \subset \mathbb R^d$, let $V_j^k(\{x_i\}_{i=1}^n)$ be the $j$th Voronoi cell in the $k$th order Voronoi partition of the space by points $\{x_i\}_{i=1}^n$ (let us say we order these cells in some way in order to index them). This means that all the points in each of these cells have the same $k$-nearest neighbors among $\{x_i\}_{i=1}^n$. Then, the class of functions underlying $k$-NN can be written as
\begin{align}
\mathcal F_{\text{$k$-NN}}^{(n)} = \Big\{f: \mathbb R^d \to \mathbb R:&\; \text{There exists $\{x_i\}_{i=1}^n \subset \mathbb R^d$ and $\{a_j\} \subset \mathbb R$ such that} \\ &f(x) = \sum_j a_j \cdot 1_{V_j^k(\{x_i\}_{i=1}^n)}(x), \quad \forall x \in \mathbb R^d. \Big\}.
\end{align}
Here, $1_{A}(x) = 1\{x \in A\}$ is the indicator function of set $A$. As you can see, this is a rather large class of functions. There are many ways to pick $n$ points in $\mathbb R^d$ and each one defines a potentially different Voronoi partition. If you consider all such partitions and all functions that are constant over cells of those partitions, you would get the $k$-NN class.
You can also take the union of $F_{\text{$k$-NN}}^{(n)}$ over all $n \in \{1,2,\dots\}$ to define all possible $k$-NN functions.

Hypothesis space of Naive Bayes and kNN


Using the Files.move creates a new "file" file type rather than moving the file to a directory

Question: I am trying to make a program that extracts multiple MP4 files from there individual folders and places them in a folder that is already created (code has been changed slightly so that it doesn't mess up any more of the MP4s, rather dummy text files).
I have managed to get so far as to list all folders/files in the specified folder however am having trouble moving them to a directory.
static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");

static void showFiles(File files[]) {
    for (File file : files) { // Loops through each file in the specified directory in "dir" variable.

        if (file.isDirectory()) { // If the file is a directory.

            File[] subDir = file.listFiles(); // Store each file in a File list.

            for (File subFiles : subDir) { // Loops through the files in the sub-directory.
                if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
                    source = subFiles.toPath(); // Set source to be the abs path to the file.
                    System.out.println(source);
                    try {
                        Files.move(source, target);
                        System.out.println("File Moved");
                    } catch (IOException e) {
                        e.getMessage();
                    }
                }
            }
        } else {
            source = file.toPath(); // abs path to file
            try {
                Files.move(source, target);
                System.out.println("File moved - " + file.getName());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args) {
    showFiles(dir.listFiles());
}

The problem is when I go to move the file from the source folder to the target, it removes or converts the target.
Answer: Files.move isn't like the command line. You're programming. You have to spell things out. You're literally asking Files.move to make it so that target (here, G:\GoHere) will henceforth be the location for the file you are moving. If you intended: No, the target is G:\GoHere\TheSameFileName then you have to program this.
Separately, your code is a mess. Stop using java.io.File and java.nio.Path together. Pick a side (and pick the java.nio side, it's an newer API for a good reason), and do not mix and match.
For example:
Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
  for (Path child : ds) {
    if (Files.isRegularFile(child)) {
      Path targetFile = targetDir.resolve(child.getFileName());
      Files.move(child, targetFile);
    }
  }
}

resolve gives you a Path object that is what you need here: The actual file in the target dir.


AFNetworking issue with JSONRequest

Question: I am using AFNetworking to get a JSON from a server.
My problem is that in case the session is expired the server is replying with a string "NOSESSION".
This is my code:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

                                  success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){

                                      NSArray *jsonArray =[JSON valueForKey:@"posts"];

                                        //DOING SOMETHING WITH jsonArray
                                        // in case that the response is NOSESSION do something

                                  }

                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){

                                       }];

[operation start];

My problem here is that this is request is failing because the response is not string.
The error message:
Failed Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

Is there any way to know the response string? (I dont mind to catch it in failure I just want to know when the session is expired)
Answer: You could check the statusCode of your NSHTTPURLResponse. When your server encounters such an error, he typically returns a statusCode.
Example:
403: forbidden
404: page not found
500: internal server error.
You could check that the HTTP statusCode is between 200 & 400. ==> no errors
if(response.statusCode < 400 && response.statusCode > 200) {
    // do normal stuff
} else {
    // handle error
}

You can find more info on HTTP statusCodes here:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Comment: My problem is not with error code. My problem is that I want to know what the server respond. Maybe the database is down. How I will understand if the database is down or the user has expired session/

AFNetworking issue with JSONRequest


show that $x^2e^x-\ln{x}-1>0$

Question:
For $x>0$ show that
  $$x^2e^x-\ln{x}>1$$

x^2e^x-lnx-1
if $x\ge 1$,we have
$$x^2e^x>2x^2>x\ge\ln{x}+1$$
But  for $0<x<1$ then It is hard.so How prove it?
Comment: What is the question?
Comment: Try to write **exactly** what your question is, and enhance your english in the middle to make things clearer. So far, it's hard to say what you mean.
Comment: and Now do you understand?
Answer: Rewrite the inequality to be proved as
$$\left(1+u\over2\right)^2e^{(1+u)/2}-\ln\left(1+u\over2\right)-1\gt0$$
for $-1\lt u\lt1$.  This can be rewritten as
$$(1+u)^2\sqrt ee^{u/2}-4\ln(1+u)+4\ln2-4\gt0$$
Now $e^{u/2}\ge1+{u\over2}$, so
$$(1+u)^2\sqrt ee^{u/2}\ge(1+2u)\sqrt e\left(1+{1\over2}u\right)\ge\left(1+{5\over2}u\right)\sqrt e$$
Also, $\ln(1+u)\le u$, so
$$-4\ln(1+u)\ge-4u$$
Putting these together, we have, for $|u|\le1$,
$$\begin{align}
(1+u)^2\sqrt ee^{u/2}-4\ln(1+u)+4\ln2-4
&\ge\sqrt e+4\ln2-4+\left({5\over2}\sqrt e-4\right)u\\
&\ge\sqrt e+4\ln2-4-\left|{5\over2}\sqrt e-4\right|
\end{align}$$
It remains to compute $\sqrt e+4\ln2-4\approx0.4213$ while ${5\over2}\sqrt e-4\approx0.1218$.
There might be some slicker way to do this that avoids the messy numerics at the end.  I'd like to see it.
Added later:  Oh, here's a way to avoid the messy numerics.  Note first that $e\gt2.56=1.6^2=(8/5)^2$, so ${5\over2}\sqrt e-4$ is positive.  This simplifies things to showing $4\ln2\ge{3\over2}\sqrt e$.  If we now allow ourselves to know that $\ln2\gt{2\over3}$, it suffices to show that ${16\over9}\gt\sqrt e$, or ${256\over81}\gt e$, which is clear, since ${256\over81}\gt3\gt e$.
If you want a quick proof that $\ln2\gt{2\over3}$, note that that inequality is equivalent to $8\gt e^2$, which follows from $8\gt{196\over25}=\left(14\over5\right)^2=2.8^2\gt e^2$.
And just to leave no numerical stone unturned, here's why we can confidently say that ${14\over5}\gt e\gt{64\over25}$:
$$e\gt1+1+{1\over2}+{1\over6}=2+{2\over3}\gt2+{14\over25}={64\over25}$$
since $2\cdot25\gt3\cdot14$, and
$$e^{-1}\gt1-1+{1\over2}-{1\over6}+{1\over24}-{1\over120}={11\over30}\gt{5\over14}$$
since $11\cdot14\gt5\cdot30$.
Comment: if we can't know $\sqrt{e},\ln{2}$ How to do?
Comment: @functionsug, funny you should ask.  I was just adding that!
Answer: There's an ad-hoc solution at least going something like this:
You can use taylor expansion to show that (or the convexity of the function). Consider the function $f(x) = x^2e^x-\ln x - 1$ and you have:
$$f'(x) = (x^2+2x)e^x - 1/x$$
$$f''(x) = (x^2+4x+4)e^x + 1/x^2 = (x+2)^2e^x + 1/x^2$$
We see immediately that $f''(x)\ge 0$. This means that the expansion around any point we will have:
$$f(a+h) = f(a) + f'(a)h + f''(\xi)h^2/2 \ge f(a) + f'(a)h$$
This means that it will be above every of it's tangent. Now one only needs to pick a tangent sufficiently close to the right of it's minimum such that either of them are positive which will prove that $f(x)$ is positive (since it's above both tangents).
The rest is ugly computations. You have that $f(1/2) > 1/10$ and that $0<f'(1/2)<1/10$ (you can find this by Taylor expansion - or if you're lazy by using calculator). This means that we have:
$$f(x) = f(1/2 + x-1/2) \ge f(1/2) + f'(1/2)(x-1/2)$$
Which means:
$$f(x)\begin{cases}
\ge 1/10 + 1/10 (x-1/2) = (1+2x)/10 \ge 0 & \text{when } x\le 1/2
\\ \ge 1/10 \ge 0 & \text{when } x \ge 1/2
\end{cases}$$
Comment: But $x^2(x+1)-x$ do now all postive .such $x=0.1$
Comment: @functionsug You're correct. My answer was premature, I've updated my answer - my approach still holds, but the solution becomes a bit more ugly...
Comment: we can't know $\sqrt{e}$
Comment: @functionsug We know for example that $\sqrt e\approx 1.648721$. The point is that we don't need the exact value, we get by with estimates of the value. One can for example show that $\sqrt e > 206/125$.

show that $x^2e^x-\ln{x}-1>0$


Hide title if 404 error

Question: I have a custom 404 error page, and I just want a quick module that hides the 404 page title, if the user arrives at a 404 error.
I've found a D7 function that looks like it would work, checking for '404 Not Found' in the http header, and adding a class that I can target with CSS. But I'm not sure how I'd do something like this for D8.
Here's what I've got:
function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}

Comment: One way to do this is add twig template suggestions for a 404 response, create that twig file and not print the region that normally has the title block. I'm on mobile so o have no code in front of me.
Comment: Hiding the title with CSS isn't hiding it from search engines or screen readers.
Answer: I don't think you need a custom module for something like this...
This should be as easy as:

Go to Configuration -> System -> Basic Site Settings, get the page URL you have for the 404 page.
Go to Structure -> Block Layout, edit the 'Page Title' block, and exclude it under the Visibility section, by page URL from step1.
Comment: You can do it this way in UI, but you need a contrib module for the visibility condition: https://www.drupal.org/project/block_in_page_not_found
Comment: already tried. it doesn't work. because the page doesn't load the 404 page URL. It simply replaces expected content with the 404 content. If I go to website.com/randompagename , it drops in the 404 error, but still has the same url.
Comment: @4k4 ..ah! dang it! I know the module, but forgot that it has a 'negate' option! That did the trick.
Answer: This should work:
/**
 * Implements hook_preprocess_HOOK().
 */
function modulename_preprocess_html(&$variables) {
  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if($status && $status->getStatusCode() == '404') {
    if(!$variables['attributes']) {
      $variables['attributes'] = new Attribute();
    }
    $variables['attributes']->addClass('page-404');
  }
}

credits go to: How to check if the current page is a 404 error from a module/template?

Hide title if 404 error


Can I pull data from Localytics API into google sheets?

Question: Using the script editor? How do I go about it? I'm not a coder but I work with data and would like to automate funnel data right into my google spreadsheet. Detailed explanation would be appreciated.
Answer: Not sure if you figured it out but you can use Google Sheets to pull data from Localytics. You just need to reach out to Support @ Localytics.com requesting the sheet, and they can get a link sent out to you. They'll also provide the instructions on how to utilize it as well, so you're not confused.
Answer: Ya, you can pull the data via the API provided by Localytics or the AWS dump provided by Localytics.
API Method:
You can write a python script with get requests in order to fetch the data from Localytics API. You can store the same in a Relational Database or populate in a csv file. Go ahead and explore the requests library in python which can help you get the required data. You can write the output in a csv file to open it in excel.
Localytics even provides daily dump to your AWS s3 bucket. For that, you need to get in touch with the Localytis customer care so that they can set up daily dumps for your app/web. You can fetch the data from S3 as csv files directly.


create a data set with only the NA rows in R

Question: How can I create a new data set based on NA value.
                      Date Symbol     Close
1      2005-01-03 01:20:00      A 115.87094
2      2005-01-03 01:25:00      A 115.88168
3      2005-01-03 01:30:00      A 115.88168
4      2005-01-03 01:35:00      A        NA
5      2005-01-03 01:40:00     NA 115.87094
6      2005-01-03 01:45:00     NA 115.87094
7      2005-01-03 01:50:00      A 115.86020

i just want to keep the rows with NA in the row
                    Date   Symbol     Close
4      2005-01-03 01:35:00      A        NA
5      2005-01-03 01:40:00     NA 115.87094
6      2005-01-03 01:45:00     NA 115.87094

Comment: `subset(df, is.na(Symbol) | is.na(Close))`
Answer: We can use complete.cases
df1[!complete.cases(df1),]
#                 Date Symbol    Close
#4 2005-01-03 01:35:00      A       NA
#5 2005-01-03 01:40:00   <NA> 115.8709
#6 2005-01-03 01:45:00   <NA> 115.8709

Answer: I'm relatively a beginner but you could iterate through the rows (not sure about how you might do it with apply or other vectorized functions) using anyNA() on the row and then if it is true keep the row.
EDIT:
e.g.
a <- rep(NA, nrow(df))

for (i in 1:nrow(df)) {
  a[i] <- anyNA(df[i, ])
}

newdf <- df[a, ]

Generally style guides recommend against over using loops, but the anyNA() and is.na() functions are super useful so worth knowing anyways.
Comment: Is that better?
Comment: `df[apply(df, 1, anyNA),]`


Mudar aparência da AlertDialog para a antiga

Question: Tenho esse código que cria uma AlertDialog
public void mostrar_popup(){
    AlertDialog.Builder dlg = new AlertDialog.Builder(getActivity());
    dlg.setCancelable(false); //impede que a janela seja fechada ao clikcar fora
    dlg.setMessage("É preciso digitar um texto para continuar ");
    dlg.setNeutralButton("OK",null);
    dlg.setPositiveButton("sim",null);
    dlg.create();
    dlg.show();
}

E o resultado é esse

E esse é o resultado que eu gostaria que saísse
Answer: Você pode setar o tema por parâmetro no AlertDialog.Builder(Context context, int themeResId), da seguinte maneira:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert);

*Antes era usado o tema: AlertDialog.THEME_HOLO_LIGHT, de acordo com a nova documentação esse tema está obsoleto.
Caso queira dar uma olhada nos temas disponíveis.
Também é possível criar o seu prório tema customizado, conforme esta resposta.


Whenever i enter a new url and press click a new image is displaying but the previous image is still there i need to clear the previous image using js

Question: Bhtm

  enter your url<input type="url" id="image">

  <button type="button" onclick="display()">click</button>

Answer: Seen as the only thing that changes each time is the URL, you could just use a global var to store a reference to the image element, and then just change it's url.
eg.


Why does loadMultiple load 1000 nodes 9.2 times faster than loading each node one by one?

Question: I have always known that loading multiple nodes at the same time is faster than loading them one by one.
What I wasn't aware of, is the huge performance difference between the two ways of loading nodes.
I made an example to see the difference. Here's my result:
Load 1000 nodes one by one:
$start_time = microtime(TRUE);
foreach (range(1, 1000) as $nid) {
  $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
  if ($node) {
    print_r($node->id());
  }
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);

Execution time: 10.7266 seconds.
Load 1000 nodes at the same time:
$start_time = microtime(TRUE);
$nids = [];
foreach (range(1, 1000) as $nid) {
  $nids[] = $nid;
}

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

foreach ($nodes as $node) {
  if ($node) {
    print_r($node->id());
  }
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);

Execution time: 1.1664 second.
How can loadMultiple be 9.2 times faster than loading the nodes one by one?
Is it the connection between Drupal and the database? What other factors are slowing down the process when loading the nodes one by one?
I have cleared the cache after every request to avoid the loaded nodes being cached.
I used the microtime function to calculate the exact execution times.
Comment: @leymannx This is definitely a Drupal-specific question, and there's actually quite a bit more to it than the current question/answer have gone into. For example, the premise of the multiple load being 20x quicker simply isn't true if relevant static caches have been primed. That, and other related, architectural decisions are, while not unique to or invented by Drupal, the result of specific decisions made by the core devs when this was built, so we should expect to cover it here IMO
Comment: I really like your efforts on this site and I'm really happy about your activity here so please don't understand this wrong, I definitely don't want to scare you off. But while this question involves Drupal functions it's actually a question about PHP in general. It's up to you then to have a look a these functions and understand the bare PHP code which is being executed in there. If that's unclear you are better off asking on SO, in my opinion.
Comment: I think it's Drupal related - the question is on how these two Drupal functions operate in the backend.
Comment: Hi @leymannx, first of all thank you for the nice comment, I really appreciate. I just have a question. Imagine I'm going to ask this question on SO, I would have to tag the question `drupal` because PHP experts that doesn't know anything about Drupal would think `\Drupal::entityTypeManager()` that's definetely not a PHP function I know... So while it might be related to PHP code, I still think it's on topic here, because it's about some of Drupal's core functions and how they operate.
Comment: Well, I'm probably a bit more strict when it comes to flagging than others. Since I like how well-curated this site is and want to keep it that way. Asking on SO and tagging it [tag:drupal] doesn't automatically make a question on-topic for here. Experts on SO probably answer: Well, what's happening in that function, have you had a look, what exactly is unclear about it? Maybe it's even more obvious to them that a `foreach` always takes longer than loading one large chunk of data at once.
Comment: Thanks @all for the fruitful discussion. Close-vote retracted.
Answer: It's likely that when you are loading individual nodes, you are loading the entity type manager, then for each node retrieve the storage, do a query to get the node data, and build the node. With the multiple process, some of the DB queries are likely combined, and the processing will be in a batch rather than having to run through the code multiple times.
Comment: Side note: EntityTypeManager won't be initiated multiple times. It's a service and therefore always the same instance will be used. The main performance difference between the two is definitely the db query(ies).
Comment: Did you notice that load() is a wrapper function for loadMutliple() in EntityStorageBase?
Comment: Yes but it will be called one thousand times - once for each node.
Answer: This actually has nothing to do with the storage or entity type manager itself.
However, it is true that loadMultiple is faster in this case.
The slowness comes from \Drupal\Core\Entity\Sql\SqlContentEntityStorage::getFromStorage to be exact.
As a matter of fact, even if you do call load, it will call loadMultiple.
For the reason why loading entities individually is slower is because how the data is queried from database. In most usual scenario entity has base table, data table and possible revision tables. With node, you often have also extra fields, of which have separate table as well.
So as bare minimum on every load, you will be querying node, node_field_data, node_revision and node_field_revision.
When you load multiple entities, under the hood these tables are called only once including all entity IDs. Total of 4 queries.
When you load individually entities, under the hood these tables are also called for every entity. That's total of 4000 queries in your example.
If you have 20 extra fields for node, that would mean 44 queries vs 44000 queries.
Here's snippet you can utilize to see the difference in action.
<?php

$entityType = 'node';
$storage = \Drupal::entityTypeManager()->getStorage($entityType);
$ids = $storage->getQuery()->range(0, 1000)->execute();
$storage->resetCache();

$startTime = microtime(TRUE);
foreach ($ids as $id) {
  $entity = $storage->load($id);
  unset($entity);
}
$endTime = microtime(TRUE);
$runTime = $endTime - $startTime;
echo "Individual: {$runTime} seconds" . PHP_EOL;

$storage->resetCache();

$startTime = microtime(TRUE);
$entities = $storage->loadMultiple($ids);
unset($entities);
$endTime = microtime(TRUE);
$runTime = $endTime - $startTime;
echo "Multiple: {$runTime} seconds" . PHP_EOL;

Comment: `So as bare minimum on every load, you will be querying node, node_field_data, node_revision and node_field_revision.` Not after the first load, as the node will be cached after that point.


What can I use on the document to apply a function from time to time including future elements?

Question: I have pieces of HTML that are added as the user clicks a button, and I want from time to time to make changes on the pieces that are being added. I can't use $(document).ready() because when the page is ready / loaded, those parts of the code are not there yet.
What can I use on the document to apply a function from time to time to the DOM including future elements? Something like:
$(document).atEach(3000, function() {
    // As the user clicks a button, a field is added to the page with a class.
    // The "window" applies every 3 seconds the given function within the scope of all the DOM,
    // (It updates the elements that were inserted)
    if ($(".class").val().length) {
        $(".class").removeClass("input-red").addClass("input-green");
    } else {
        $(".class").addClass("input-red").removeClass("input-green");
    }
});

Answer: To execute a function in regular time intervals you can use setInteval
setInterval(function() {
    // As the user clicks a button, a field is added to the page with a class.
    // The "window" applies every 3 seconds the given function within the scope of all the DOM,
    // (It updates the elements that were inserted)
    if ($(".class").val().length) {
        $(".class").removeClass("input-red").addClass("input-green");
    } else {
        $(".class").addClass("input-red").removeClass("input-green");
    }
}, 3000);

http://jsfiddle.net/ma7p3hcr/1/
I'm not sure what your function is supposed to do but I guess it's some kind of input validation. If that's the case you should just listen to oninput event and execute it then. Event delegation makes it possible to listen to events on dynamically added inputs:
$(document).on('input', '.class', function(){
   if( $(this).val().length ){
        $(this).removeClass("input-red").addClass("input-green");
    } else {
        $(this).addClass("input-red").removeClass("input-green");
    }
});

http://jsfiddle.net/tnc84mhf/
Comment: @EricsonWillians `setInterval` answers your question, but the other method probably solves the underlying problem ;)
Comment: Oh, I see! I just have to use setInterval() on "global scope". Thank you very much!


5-position switch in an HH Strat set up for a killswitch

Question: I am about to purchase a Strat-style guitar.  It has two humbuckers, and a 5-way switch.  It only has one tone and one volume.  I'd like to modify the 5-way switch so that one of the positions kills the neck humbucker.
Is this even possible?  What's the best way to do this?
Ideally, I'd like the second bottom-most position to be the killswitch.  (the one next to Bridge only)
Comment: The simplest way to achieve this would be to have a separate switch to interrupt any signal from any pup. It makes more sense, as you may want to use it from a different pup combination. Doing what you suggest will lose one pup combination - for what benefit?
Comment: There's plenty of room in the scratchplate without cutting into the body.
Comment: 'kills the humbucker'? You mean make it run single-coil? The pickup would need to be wired to allow that. We'd need the original schematic to be certain.
Comment: I think we need clarification on the term 'kill' because with only 2 pups, a standard 5-pos switch would already be wired "weird"
Comment: I'm not sure how killswitch can be interpreted other than how @Tim described it.  I do understand that ideally a separate control would do this.  I really don't want to drill a hole in the body for a button or switch to do this.
Comment: @Tetsujin I've seen people do 5-way switches on HH configurations where the intermediate positions are coil taps or splits.
Comment: It would be helpful if someone could attach a diagram of a 5 position switch. Perhaps there are several types? Also, from my experience some switches (or some position of switches) are more or less suitable to be a kill switch, depending on the cut off point. If you want to try to repeat what e.g. Buckethead is doing you need a kill switch that will respond well.
Comment: @Tim this is a Charvel.  I don't believe it's got the same façade that a true Strat has.
Comment: Extra information usually helps - as here!
Comment: "I'm not sure how killswitch can be interpreted other than..." – well, you described it as killing specifically one of the PUs, when what you actually mean is kill the whole guitar output.
Comment: @leftaroundabout You're right.  I was inarticulate.
Answer: A standard 5-way switch is a simple evolution of the old Strat 3-way switches, which consists of two linked 3-way selectors. The in-between positions just select two of the positions simultaneously, i.e. they put the inputs in parallel. In the standard Fender configuration, one of the linked switches is used only to select the separate tone pots, which may not be all that relevant to you, so you could use that sub-selector as the kill switch by repurposing one of the in-between positions as a short to ground. Just ignoring any tone pots for now (you can wire them independent of the PU selection somehow), and assuming you don't want any coil splitting, you can set up a kill switch for example like this:

Of course, whether you want the kill position on the NeckH + MidS slot or the MidS + BridgeH one is trivial to change.
That said – I wouldn't do it this way. As Tim already commented, it's no problem installing a small dedicated kill switch in the scratch plate, no woodwork needed. Or you could replace one of the tone pots with such a switch. (A pull pot will likely be too slow for the kind of stuff you want to do with a kill switch.)
Comment: Cool.  This gives me hope.  Thanks for the theory.
Comment: Like the animation! Clever.
Answer: There's the option of changing a volume pot. for a piggyback type (push/pull). With nothing connected to one position (up or down) it will work as a kill switch - and save any woodwork.
Comment: "Nothing connected" is not a good way to do this, because it makes the line very sensitive to interference. Shorting to ground is much quieter.
Comment: @leftaroundabout - fair enough - but that's easily solved using a tandem pot.


Positional audio triggering (HTML, CSS, skrollr, JS)

Question: I am making a digital storytelling which is a website containing images and audio tracks. I came across skrollr today and found it interesting. Now I am wondering if anybody knows a solution to using skrollr with audio tracks - so that the audio will stop and start based on the scroll-position. I appreciate all ideas and creative thoughts.
Link to skrollr: https://github.com/Prinzhorn/skrollr
Comment: Cool idea, but you're more likely to get advice if you post something you've tried yourself.
Answer: Skrollr only animates changes in CSS. You'll need to use javascript to do what you want.
This is easy enough to do with jQuery. Set an event handler to watch for scroll events, then check if the document is scrolled within particular bounds, then do whatever you want (e.g. play/pause audio). There are a million solutions for playing audio. I'd recommend howler.js.
Comment: Thank you! I found a solution with Howler, "window.onscroll()" to check for movement and "document.body.scrollTop" to find placing on page. Not sure if this is the most efficient way to do it but it seems to be working well =)
Comment: That's pretty much how I would do it. There might be a better solution, but it sounds like you've already figured it out well enough.


Mega drop down menu onhover flickering

Question: I've got a problem with a mega drop down menu that I found online. It is perfect for my purpose but it acts weird sometimes and it has a flickering and flashing problem. The link where I found it is here: http://bootsnipp.com/snippets/featured/mega-menu-slide-down-on-hover-with-carousel .
The author already knows that problem, but essentially it could work just fine for mobile if it will be hide. On desktop version I think is a really good idea and I'm using on a website that I build: http://napoleon.larchedigitalmedia.com/.
The problem as I told you before is the flirking and I guess that the problem is here in jquery:
$(".dropdown").hover(
    function() {
      $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,true).slideDown("400");
      $(this).toggleClass('open');
    },
    function() {
      $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,true).slideUp("400");
      $(this).toggleClass('open');
    });

I don't understand if it is a bootstrap problem (bootstrap use mostly an onclick event for the mega drop down menu) or the problem is in this snippet. Essentially the class open is added (toggle) too fast to a div and sometimes it is applied to two divs at the same times. Could anyone help me to fix this problem?
Answer: As far as I can see, in your project, the animation doesn't have time to finish and JS is trying to animate both at the same time. I just changed a little bit of your code and the flickering stops.
$(".dropdown").hover(
function() {
  $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,false).slideDown("400");
  $(this).toggleClass('open');
},
function() {
  $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,false).slideUp("400");
  $(this).toggleClass('open');
});

Just by changing the second parameter of the stop() function, the animation executes itself. If you want more info, there is always the Jquery documentation on the fuction.
Answer: This occurs due to hover event. Just change the hover event to mouseenter and mouseleave to resolve this problem.
Change this
   $(".dropdown").hover(
       // content here
   );

To
$(".dropdown").mouseenter(
  function() {
    $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,false).slideDown("400");
    $(this).toggleClass('open');
  },
);

$(".dropdown").mouseleave(
  function() {
    $('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,false).slideDown("400");
    $(this).toggleClass('open');
  },
);

Hope this will help!

Mega drop down menu onhover flickering


Recognising objects in images using HAAR cascade and OpenCV

Question: (This came out a bit long, but it's mostly an hardly hard to understand explanation :)
For a project I have I need to recognise objects that, in general form, look like this -

Inside a bigger image that contains different shapes, like this one -

As you can see, the object I'm looking for is a red line with crosses on each side (there's 5 of them in that last picture).
I have a bank of around 4,000 images in which I need to find the object, some of them contain these objects, and some of them don't, like this image -

After doing some research, I've figured using haar cascades and openCV is the way to go, so I wrote a script that goes through all of the aforementioned 4,000 images and extracts separates contours, like the first image in this question.
Then, I went through the many contours, grabbed around 150 of them (that is, 150 files that contain just the object I need, similar to the first image) and around 180 images that do not contain the object I need (similar to the third picture here).
Then I started the training process, using several tutorials, but mainly this one.
While doing so, I encountered a problem - as you can see, the images of the desired double-crossed object are not the same size, and don't even have the same scale (as they can appear in any angle - horizontally, diagonally, etc..).
At first I tried using the images with the different dimension, but that caused errors in the training process, so, to work around that, I've changed all of the positive images' dimension to be 350x350 (the biggest scale of one of the objects). Just to be clear - I did not resize the images - I just added white space around to make all of the images to be 350x350 pixels.
Then I went through the training process, as suggested in the tutorial - I created samples (width - 24, height - 24) and created a cascade xml file, which turned out to be not very big (45kb).
Now, I know that 150 positive images and 180 negative ones are not a lot, but I wanted to at least get a proof-of-concept working before I filtered more images and put more time into it.
When the cascade.xml file was done, I tried to use it to locate some objects in some images (using cv2.CascadeClassifier('cascade.xml') and cascade.detectMultiScale(img) but every try returned zero results.
At last I even tried to locate an object in one of the positive images (which contained nothing but one of the desired objects), but it too returned zero results.
I tried tweaking the parameters of cascade.detectMultiScale(img) and currently I'm training a cascade file with 36x36 samples, but I'm not confident it will work.
Since I'm pretty new to this stuff, I was wondering what I'm doing wrong, and I thought I'll ask here.
More specifically:

Do you think the use of haar is right in this context? Should I use other method of objects recognition?
Could the positive images dimensions be the source of problem? If so, how can I go about it?

If I didn't include some important data, please let me know I'll post it.
Thank you very much for your help,
Dan
Answer: i guess, you won't get good results from haar (or hog) cascade classifiers here.

your 'needle' does not have enough features/corners (it's just 2 crosses and a line)
cascade classifiers are quite sensitive to rotation. it seems your object can take any arbitrary rotation here.
if you train a classifier with many different rotations, it will just overfit.
if you train many classifiers(one per rotation), - the same. ;(

so, imho, not much hope for that approach.
i would go for contours/shapeMatching instead:
void findNeedles( const std::vector<cv::Point> & needle_contour, const cv::Mat & haystack_binarized)
{
    int nfound = 0;
    std::vector<std::vector<cv::Point>> contours;
    cv::findContours(haystack_binarized, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
    for (size_t i = 0; i < contours.size(); i++)
    {
        // pre-filter for size:
        if ( ( contours[i].size() < needle_contour.size()/2 )
          || ( contours[i].size() > needle_contour.size()*2 ) )
          continue;

        double d = cv::matchShapes(contours[i],needle_contour,CV_CONTOURS_MATCH_I2,0);
        if ( d < 8.4 ) // heuristic value, experiments needed !!
        {
            cv::drawContours(haystack_binarized, contours, i, 128, 3);
            nfound ++;
        }
    }
    cerr << nfound << " objects found" << endl;
    cv::imshow("haystack",haystack_binarized);
    //imwrite("hay.png",haystack_binarized);
    cv::waitKey();
}

int main()
{
    // 1. get the contour of our needle:
    Mat needle = imread("needle.png",0);
    Mat needle_b;
    threshold(needle,needle_b,120,255,1);
    imshow("needle",needle_b);

    std::vector<std::vector<cv::Point>> needle_conts;
    cv::findContours(needle_b, needle_conts, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
    if ( needle_conts.size() == 0 )
    {
        std::cout << " no contour Found" << std::endl;
        return -1;
    }
    std::vector<cv::Point> needle_contour = needle_conts[0];

    // 2. check a positive sample:
    Mat haypos = imread("hay_pos.png",0);
    Mat haypos_b;
    threshold(haypos,haypos_b,120,255,1);
    findNeedles(needle_contour, haypos_b);

    // 3. check a negative sample:
    Mat hayneg = imread("hay_neg.png",0);
    Mat hayneg_b;
    threshold(hayneg,hayneg_b,120,255,1);
    findNeedles(needle_contour, hayneg_b);

    return 0;
}

--------------
> haystack.exe
5 objects found
0 objects found

Comment: I agree, haar it is not you would like to use here.
Comment: First of all - thank you very much. You solution was very helpful and explained exactly what I needed to do. I also appreciate very much the time you took to write the code. Because of people like you SO is as great as it is. So again - thank you. Secondly, for general knowledge - the solution recognised some long lines that passed the size filter as needles, so to go about it I matched a given contour to the needle and to another contour of a line, and compared the grades to deduce which kind of object it is.


How to save binary byte array from C# as file in PHP?

Question: In C# (ASP.NET MVC) I have method which opens one file and put all the file content into the byte array like this:
byte[] bytes = File.ReadAllBytes(filename);

On PHP side I have PHP Slim Framework API method which is called from C# and I do a POST JSON object that contains this file byte array -> it has these properties:

myObjectId - int - id of my object
filename - string - file name
fileBytes - array - byte array of this file

You can get the demo of this JSON content here: https://justpaste.it/1d8jq
On PHP side I do json_decode of what I received like this:
$fileObject = json_decode($app->request->getBody());

And I get the same array of bytes in member:
$fileBytes = $fileObject->fileBytes;

The question now is how I can save this byte array into the Word file (it is a Word file). I used this method and it saves but it is some very strange content/strange symbols inside (not the original content)...
$binStr = '';
foreach ($fileBytes as $fileByte)
{
  $binStr .= pack('i', $fileByte);
}
$binStr .= "\n";
$fileTemp = '/tmp/'.$filename;
file_put_contents($fileTemp, $binStr);

So, how I can properly save these bytes (this byte array has the same elements/integers in PHP like in C# - looks like it is correctly sent))?
If this matters, C# part is on Windows Server and PHP is on Linux/CentOS server.
Answer: Seems like you have a simple array of bytes as integers, so instead of using pack, you could just use chr. With some array_map magic, this could be written as this.
$fileObject = json_decode($app->request->getBody());
$data = implode(array_map('chr', $fileObject->fileBytes));
file_put_contents('/tmp/' . $fileObject->filename, $data);


Get Roles with UserId

Question: Is there a way to get all the roles a user is in using their UserId (uniqueidentifier)? I know that I can use Roles.GetRolesForUser(string username), but I don't have the username at that point, but do have the UserId. I could get the username, but was hoping I could circumvent that if possible.
Answer: Well, came up with my own solution, not sure if it is the best and haven't tested it yet, but theoretically it should work. If anyone has something better, please do share.
string userName = Membership.GetUser(userGuid).UserName;
var roles = Roles.GetRolesForUser(userName);

Get Roles with UserId


django-rq Redis Client sent AUTH, but no password is set

Question: I had my django-rq working a few days ago, but I restarted my computer and now it's not working. I can confirm redis is running with:
brew services start redis

Here is what I try to run to start redis:
python manage.py rqworker

And here is the error I get:
Traceback (most recent call last):
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/casey/PycharmProjects/green_brick_django/code/pricecomparison_project/pricecomparison/maps/views.py", line 231, in get_backend_maps
    django_rq.enqueue(tasks.map_diffbots_backend, alexa_site_id=alexa_site.id)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 226, in enqueue
    return get_queue().enqueue(func, *args, **kwargs)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 327, in enqueue
    at_front=at_front, meta=meta
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 70, in enqueue_call
    return self.original_enqueue_call(*args, **kwargs)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 66, in original_enqueue_call
    return super(DjangoRQ, self).enqueue_call(*args, **kwargs)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 277, in enqueue_call
    job = self.enqueue_job(job, at_front=at_front)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 353, in enqueue_job
    pipe.execute()
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/client.py", line 3514, in execute
    self.shard_hint)
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 994, in get_connection
    connection.connect()
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 502, in connect
    self.on_connect()
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 570, in on_connect
    if nativestr(self.read_response()) != 'OK':
  File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 642, in read_response
    raise response
redis.exceptions.ResponseError: Client sent AUTH, but no password is set

I had this issue before and following this fixed it:
https://cmupinkypiggy.wordpress.com/2015/02/28/redis-password-after-installing-with-homebrew/
However, the password is still uncommented in /usr/local/etc/redis.conf so now I officially am stuck. Any ideas?
Comment: For some reason, killing the old redis processes that we're running on the port fixed it.
Answer: For some reason, killing the old redis processes that we're running on the port fixed it.
Comment: can you tell more? what exactly did you do?


Notepad++ syntax highlighter bug - how to fix and/or report

Question: I am trying out Notepad++ and have encountered an error with the syntax highlighter within minutes of using it.  In JavaScript, a comment starting with // is handled correctly, but not /// (it shouldn't matter what follows the first 2 slashes, so what is wrong with another / ?).  This does not appear to be a problem with PHP.
A few of questions:
1) Anyone know how to fix this?
2) Is Notepad++ syntax highlighting reliable (I know this could be a matter of opinion).
3) Where can I report a bug? (I looked at their forum but I am spending more time figuring it out than the time it took to find the bug.)
Answer: Its not a bug. You can check out What does the three slashes in javascript do? to see. I wasn't sure what it did either but apparently some doc generators use /// to annotate docstrings which is why its coloured differently.
Cheers


Poor model fit but significant and high path coefficient values in Structural Equation Modeling

Question: I wonder if it is possible to have a poor model fit and at the same time strong significant and high path coefficient values among the latent variables?
How would be interpret this? Also, what if we obtained strong model fit but non-significant/low path coefficients. Can someone elaborate on this?
Answer: Yes, it's easy.
Let's say that this is your population model:
<code>+---+    0.5       +----+
| X +------------> | Y  |
+-+-+              +-+--+
  |     +----+       ^
  +---->+ M  +-------+
    0.5 +----+   0.5
</code>
And you fit this model:
<code>+---+              +----+
| X |              | Y  |
+-+-+              +-+--+
  |     +----+       ^
  +---->+ M  +-------+
        +----+
</code>
You've omitted the direct path from X to Y.
This omission will make the model fit, very badly.
However, the parameters from X to M and M to Y will be high - higher than they should be, and (for any reasonable sample size) highly significant.
Model fit comes first. If your model doesn't fit, you don't trust the parameter estimates.
(That doesn't mean that if your model does fit, you do trust them.)


How do I make a TeamCity build appear in the TFS Build Explorer?

Question: We are using TFS 2010 for source control and project management, and TeamCity 6.0 for performing builds and build reporting (CI and daily deployments for testers).  Setting up TFS source labeling in TeamCity to match the build number was very straightforward, but I cannot find a way to link this back to TFS Build Explorer.
We want link these to be able to assign bugs to particular builds through TFS for the daily tester deployment builds.
Comment: By "TFS Build Explorer" you mean the Build folder in Team Explorer?
Comment: The Build Folder and/or the "Found in Build"/"Integrated in Build" fields on the work items, as well as the links in Microsoft Test Manager, I'd think.
Comment: For us, in particular the "Found in Build"/"Integrated in Build" fields have been the main issue.
Answer: I don't know if you can, at least without some heavy VSX work or direct manipulation of the database, get the TeamCity builds to show up in the TFS Build Explorer.
However, the "Found in Build:" drop down on in the bug workitem is a populated by a global list which you can add to pro grammatically using http://blogs.microsoft.co.il/blogs/shair/archive/2010/03/08/tfs-api-part-23-create-global-list-xml-way.aspx .
Comment: looks like the referred-to site is down? any alternative link?
Answer: This isn't an awesome answer as I don't know Team City, but you may ask the Team City group if they have a TFS build process template that delegates to Team City.  Final Builder has this in which TFS does the monitoring and scheduling of builds and some details, but Final Builder does the actual work.  This gives you a mixed bag in my opinion, but it doesn't what you are intending.
Answer: Concerning the Team Explorer :
Microsoft never open the customization of the Team Explorer by providing corresponding API in the Object Model. You're not supposed to add/modify/change nodes there. But people succeeded by doing some reflection tricks.
I still don't think it's a good idea to customize the Team Explorer, especially when you see Visual Studio 2012: they revamp everything there.
Microsoft Test Manager :
Looks like the data is pulled from the Team Build API directly, so you won't have the possibility to plug Team City there.
The Work Item field is a different story :
The values present are built from a Global List which is updated by Team Build. So you can maintain the list content instead of Team Build if you use Team City, Sean Lynch gave you the pointer to update a global list. This point is not hard at all, it's pretty straightforward.
All in all what you need the most if the Work Item field and you can do that. If you still need a list of all your Team City builds in Visual Studio, write a Visual Studio .vsix to add a custom View showing your Team City Build. I have less hope for MTM.
Last comment: stay away from the TFS Database, Microsoft is clear that you're not allowed to read/touch it. It's tempting, but you'll lose all MS support if you do it. But note it would be the only way to achieve what you want...
Answer: Here is a blog post as a starting point to create an app that records in TFS the results from your TeamCity build. Then you could run your app as part of your TeamCity build.
http://blogs.msdn.com/b/jpricket/archive/2010/02/23/creating-fake-builds-in-tfs-build-2010.aspx


When is Satorra-Bentler applicable?

Question: I have a dataset (n = 200) with several observed variables (answers to a 5-point Likert scale) and would like to perform CFA on that dataset (let's say it's a one-factor model with reflective indicators).
Before the actual evaluation, I assessed univariate normality of every variable (using the tests of Shapiro-Wilk and Anderson-Darling) and had to deny the hypothesis of normality in every single case. I also denied multivariate normality on the ground of Mardia's test with a high z-value.
Consequently, I checked several references and found (at least for me) divergent answers regarding the "requirements" for Satorra-Bentler test-statistics. One paper reported the following: "The variables in the data were multivariately nonnormally distributed, with normalized Mardia's multivariate kurtosis of 6.03 (p < 001). We employed a maximum likelihood estimation method with robust standard errors together with the Satorra-Bentler rescaled chisquare statistic (Satorra and Bentler 1994), which compensates for nonnormality of variables." (Stern, Katz-Navon, Naveh, 2008, p. 1558)
I also checked Kline (2010, pp. 176-177) in which it is stated that in the case of non-normality of continuous endogeneous variables (the section is also termed "Corrected Normal Theory Methods for Continuous but Non-normal Outcomes"), corrected test statistics, such as Satorra-Bentler, are applicable.
At least from my understanding, both answers differ as Kline argues on the ground of the endogenous variables while Stern et al. simply analyze the raw data. Which of the two is correct and on the ground of which test would I normally argue for the use of Satorra-Bentler in a paper?

Kline, R. B. (2010). Principles and practice of structural equation modeling (3rd ed.). Guilford publications
Stern, Z., Katz-Navon, T., & Naveh, E. (2008). The influence of situational learning orientation, autonomy, and voice on error making: The case of resident physicians. Management Science, 54(9), 1553-1564.
Answer: If you are doing CFA, all your variables are endogenous.
The Satorra-Bentler correction is a sandwich estimator in regression (also called Huber-White, and confusingly also called robust). Hence it doesn't just account for non-normality, but is also corrects for heteroscedasticity.
But, like a sandwich estimator in regression, if you didn't violate any assumptions, it has almost no effect. And if you did violate any assumptions, it gives you better standard errors.
There is almost no cost to using it. So go ahead and use it.
(Although the Yung-Bentler T2*, which is more commonly known as MLR, is extremely similar and can handle missing data - so I almost always use that instead.)
Comment: I assume that I have a misunderstanding here; could you please give me a hint why the variables are considered endogenous? Is it because they are reflective indicators of the latent variable and thus, "the presumed causes of endogenous variables are explicitly represented in the model" (Kline, 2011, p. 96)?
Comment: Exogenous measured variables don't have arrows pointing at them.
Comment: Alright, just to make (really) sure that I understood it correctly (as you mentioned "if you are doing CFA" in your answer): is it correct that the same would hold true for the measured variables even if "their" reflective latent variable would predict another factor (as in the example [here](https://en.wikipedia.org/wiki/Structural_equation_modeling#/media/File:Example_Structural_equation_model.svg)?

I remember that I once read a question that was also answered by you. The questioner mentioned that he had hoped that you would respond to the question - I do totally understand why.
Comment: Yes. From the page: http://davidakenny.net/cm/basics.htm: Exogenous Variable - A variable that is not caused by another variable in the model.  Usually this variable causes one or more variables in the model.
Comment: Your measured vars are effects, not causes.
Comment: @JeremyMiles, within ML CFA, would you apply Satorra–Bentler-scaled likelihood ratio test also in case of categorical data? Thanks

When is Satorra-Bentler applicable?


Strange "x" in front of notehead

Question: I was reading some piano sheet music and came across a type of note that looked like a sharp. Here is how it looked:

What is this type of note called? What is its pitch?
Answer: Probably already answered elsewhere.  But see if this explanation helps.
It's a Double-sharp.   Raises the pitch by 2 semitones (a normal sharp raises it by one).
You're most likely to find it as the sharpened 7th note of a minor scale in a key with lots of sharps!  For instance, Fx is the seventh note of G# (harmonic) minor. Not an impossibly remote key, a piece in B major might well pay it a visit.
Why not just write G natural?   Well, a scale needs to LOOK like a scale, with one of each note,  And a triad needs to LOOK like a triad, visibly spaced in thirds.
(You can have double-flats too.  We just use two flat symbols for that.)
(And I can't tell you the pitch of your example, because there's no clef.)

Strange "x" in front of notehead


Why is $f(x)=1$ for $x\in\mathbb{Q}$ not integrable, but $f(x)=1$ for $x=1/n$ is?

Question: Consider two functions.
First function:
$$f(x)=\begin{cases}1 & x\in\mathbb{Q}\\0 & x\notin\mathbb{Q}\end{cases}$$
Second function: Let $E=\left\{1/n, n\in\mathbb{N}\right\}$, then
$$g(x)=\begin{cases}1 & x\in E\\ 0 & x\notin E\end{cases}$$
Are these functions integrable on $[0,1]$?
The answers says that the first is NOT integrable, but the second is. I don't understand why this is true. they seem to be the same function in my mind.
Comment: There are very few numbers of the form ${1\over n}$, most of them in the immediate vicinity of $0$. On the other hand, the rational as well as the irrational rational numbers in $[0,1]$ are dense in in $[0,1]$.
Comment: Are you speaking of Lebesgue or Riemann integration ?
Comment: Why do you think they are the "same function"? Not every rational number can be written $1/n$ for $n\in\mathbb{N}$.
Answer: The first function is discontinuous on a set that does not have measure zero $[0,1]\cap (\mathbb{R}-\mathbb{Q})$. You can see this by convincing yourself there is no suitable partition such that the lower and upper Darboux sums are the same. The upper will always be $1$ for any partition, the lower will always be zero.
The second function is discontinuous on what is called a set of measure zero. You can define a partition with the upper and lower sums both being zero with a little work. Having the same value for upper and lower Darboux sums for a suitable fine partition is what it means to be Riemann integrable.
Comment: Your first sentence is confusing because of the word "since" and your parenthetical about the irrationals being dense. Discontinuous on a dense set does not imply discontinuous everywhere. For example, there is a [function](https://en.wikipedia.org/wiki/Thomae%27s_function) that is discontinuous only on the rationals, which are dense. Besides, we don't need to know the first function is discontinuous everywhere to conclude it isn't integrable. It is enough to note it's discontinuous on the irrationals, for then the set of discontinuities does not have measure zero.
Comment: I added a dense set after and also wasn't sure if op was familiar with measure zero and guessed not. I'll delete the parenthetical though
Comment: But it doesn't really matter that the first function is discontinuous everywhere. That is more than you need to draw the conclusion. You only need that $f$ is discontinuous at the irrationals, as you said at first. You should state the key fact here, that a function is Riemann integrable iff the set of points where it's discontinuous has measure zero.
Comment: Fair enough. I will edit


Loading custom directive dynamically by assigning it to controller scope

Question: I am trying to load my custom directive dynamically on click of a button. On click, I would make an AJAX call to get the directive html. Once i get a response, i compile that response and assign it to a controller scope variable. I was expecting that the corresponding template of the custom directive to display properly but that is not the case. Please help.
Below is a sample of code which has the same issue.
In my HTML file:

 <md-button class="md-raised md-primary" ng-click="DemoCtrl.getDirective()">Click to get directive</md-button>

My module and corresponding controller / directive:
angular.module('sampleApp',['ngMaterial'])

        .directive('test',function(){
            return {
                restrict: 'E',
                template: 'Hello World'
            };
        })

        .controller('DemoController', function($compile,$scope,$sce) {
            var vm = this;
            vm.getDirective = function(){
                //Here I make a service call to get the directive. In this case I get a response as <test></test>
                var directiveCode = $compile("<test></test>");
                var directiveHTML = directiveCode($scope);
                $scope.test = $sce.trustAsHtml(directiveHTML);
                $scope.$apply();
            }
        });

Comment: You could add `.html()` to `directiveHTML` to get the html of the compiled template. Then it should work. Please have a look at this [fiddle](https://jsfiddle.net/awolf2904/29g4597s/). ($scope.$apply() is not needed in the fiddle)
Comment: Thanks @AWolf. It worked. But my custom directive is much more complex than what I have shown here.  I actually have a nested custom directive inside  in this case. Would that make a difference?
Comment: I think that should also work. But that depends on your directive definition object. With `transclude: true` you can make nested directives. See updated fiddle (same link from above).
Answer: Thanks for your help @Awolf and @wasiq. Your code snippet worked fine.
Issue in my case was that i was assigning the template of the directive to the controller scope even before the AJAX call has been resolved.  Because of that, i was not getting the directive's template in the DOM. Now i moved the scope variable assignment inside the success block and this fixed the issue.
Answer: Try this
angular.module('sampleApp',['ngMaterial'])

        .directive('test',function(){
            return {
                restrict: 'E',
                template: 'Hello World'
            };
        })

        .controller('DemoController', function($compile,$scope,$sce) {
            var vm = this;
            vm.getDirective = function(){
                //Here I make a service call to get the directive. In this case I get a response as <test></test>
                var directiveCode = $compile("<test></test>");
                var directiveHTML = directiveCode($scope);
                console.log(directiveHTML.html());
                $scope.test = $sce.trustAsHtml(directiveHTML.html());
                //$scope.$apply();
            }
        });


Evaluate the limit $\lim\limits_{n\rightarrow \infty}(\frac{1}{6}+\frac{1}{24}+\frac{1}{60}+\frac{1}{120}+\dots+\frac{1}{n^{3}-n})$

Question: $$\displaystyle\lim_{n\rightarrow \infty} \left(\frac{1}{6}+\frac{1}{24}+\frac{1}{60}+\frac{1}{120}+\dots+\frac{1}{n^{3}-n}\right)$$
I am not able to find any technique to proceed. It might be simple but I am not able to understand. If the hint and the concept used is explained it will be very helpful.
Thanks in advance
Answer: Since:
$$
\frac{1}{2}\left(\frac{1}{(n-1)n}-\frac{1}{n(n+1)}\right)=\frac{1}{n^3-n}
$$
We have:
$$
\sum_{n=2}^M\frac{1}{n^3-n}=\sum_{n=2}^M\frac{1}{2}\left(\frac{1}{(n-1)n}-\frac{1}{n(n+1)}\right)=\frac{1}{4}-\frac{1}{M(M+1)}
$$
So the limit is $\frac{1}{4}$.
Comment: Also worth to mention is that this is a **telescoping** sum. An important concept that can be used to simplify the calculations of many series.
Answer: To complement Ákos' answer:
$\begin{align}&\sum_{n=2}^\infty\frac 1 {n^3-n}=\sum_{n=2}^\infty \frac{1}{2}\left(\frac{1}{(n-1)n}-\frac{1}{n(n+1)}\right)\\
&=\frac 1 2 \left[ \left(\frac 1 2 +\frac 1 6 + \frac 1 {12} + \cdots \right)-\left(\frac 1 6 +\frac 1 {12} + \cdots \right)\right]\\
&=\frac 1 2 \times \frac 1 2=\frac 1 4
\end{align}$


Como copiar os filhos de um nó para outro nó - Android com Firebase

Question: Tenho um banco X que contém categorias de empresas e  quero que ao inserir os dados manualmente  em Categorias,  envia uma cópia para AllEmpresas.

Estou utilizando esse código porém não estou encontrando uma forma de pegar apenas os filhos
private void copyRecord(DatabaseReference fromPath, final DatabaseReference toPath) {
        ValueEventListener valueEventListener = new ValueEventListener()  {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

               toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isComplete()) {
                            Log.d(TAG, "Success!");
                        } else {
                            Log.d(TAG, "Copy failed!");
                        }
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };

        fromPath.addListenerForSingleValueEvent(valueEventListener);
    }

Answer: Sugiro que você faça essa cópia através de uma Cloud Function. Isso porque as Cloud Functions são executadas na Cloud, enquanto que o seu código irá correr no dispositivo do utilizador. E se o utilizador fechar a app antes da cópia terminar? Você terá o banco com dados em falta ou incorrectos.
Veja Como começar a utilizar as Cloud Functions e a sua função ficaria assim:
const admin = require('firebase-admin'); //Importar o Admin SDK para escrever dados na database
admin.initializeApp(functions.config().firebase);

exports.copiarEmpresas = functions.database.ref('/Categorias/{categoria}/{empresa}')
    .onWrite((change, context) => {
        var snapshot = change.after;
        return admin.database().ref('AllEmpresas').child(snapshot.key).set(snapshot.val());
});

Comment: essa função vou ter que criar para cada empresa? ou vai copiar todos os filhos de academia, alimentação etc?
Comment: Vai copiar todos filhos de cada categoria. Essa é a única função que você vai criar.
Comment: Tu é o cara! Muito obrigado!


Do Drupal 8 / backbone.js have conflict when using AngularJS on top?

Question: I've just pulled D8 HEAD for my website and I want to use AngularJS instead of backbone.js to create a web app but realized D8 have already embedded backbone.js on every page.
I can disable modules that depends on it like edit or ckeditor if needed.
Even if I could disable it on a specific custom path I create with my module is still a good alternative for now.
There is also a conflict with Twig and AngularJS double curly braces in Drupal 8.
Comment: The admin toolbar uses backbone, not sure if that's going to affect your decision
Comment: So does it mean I can never use AngularJS in a Drupal 8?
Comment: Well no...I haven't tried it but both should be able to co-exist on the same page, but even if not, you just need to disable the component(s) that use underscore. Do bear in mind D8 is still in dev and modules like Admin Menu (which would provide an alternative) aren't ported yet
Answer: Seems like Backbone.js and AngularJS don't have conflict if used in the same page.
So one can ignore Backbone.js existence and do stuff with AngularJS.
Still there might be better ways doing this in future since D8 is still in development as I post this.
And for curly braces conflict with Twig in AngularJS we can config interpolateProvider service explained here
Answer: It's not a perfect solution but you can use hook_library_alter(array &$library, $name) and just set css, js or dependencies of the library to empty arrays(since it's not possible to really just remove the library from the list). Though libraries depending on the one you are altering wll break so I wouldn't recommend it.
Comment: Yea, disabling or removing libraries depending on backbone is definitely not a recommended solution.


Saving data from axios request in a global variable

Question: I'm fetching data from an api through axios post request as shown below:
useEffect(() => {

Axios.post("http://localhost:3001/getRoomDetails", {
  roomname: roomname,
}).then((response) => {
  details = response.data;
  return details

}) }, []);

Here I declared the details variable globally before useEffect so that I can display data from it on my react page. But I can't access the details variable outside of the promise.
Any solution?
Answer: In react, it is customary to store the state of a component in variables that useState provides (if we are talking about functional components). It is a bad idea to declare variables and assign values to them directly. react won't be able to track changes to them. Therefore you need to use useState hook.
const [details, setDetails] = useState();

useEffect(() => {
  Axios.post("http://localhost:3001/getRoomDetails", {
    roomname: roomname,
  }).then((response) => {
    setDetails(response.data);
  })
}, []);

// and use details variable in jsx

While the above code will solve your problem, it is not good practice. I recommend using some kind of state manager for react to store the data that was received from side-effects. It can be mobx or redux.


Bulk insert into 4000+ tables from 4000+ files with corresponding name

Question: I have a folder with 4000+ pipe delimited files of which are named the same as tables in a schema.
I'm trying to do this
DECLARE @tableName varchar(max)
DECLARE @sqlCommand varchar(max)
DECLARE @path varchar(20)
SET @path =  'x:\xfer\'

DECLARE tNames CURSOR
FOR
    SELECT table_name FROM information_schema.tables
    WHERE TABLE_TYPE='BASE TABLE'
    AND TABLE_NAME = 'sales_time_pd'
    ORDER BY TABLE_NAME

OPEN tNames
    FETCH  FROM tNames
        INTO @tableName

        WHILE @@FETCH_STATUS = 0
            BEGIN

               SET @sqlCommand = 'BULK INSERT @tableName
               FROM @path + @tableName
               WITH
                  (
                     FIELDTERMINATOR ='' |'',
                     ROWTERMINATOR ='' |\n''
                  );'

                EXEC(@sqlCommand)

                FETCH NEXT FROM tNames
                into @tableName
            END
CLOSE tNames;
DEALLOCATE tNames;

I am looking for the concept roughly please excuse my incorrect use of apostrophes
As a test I am targeting a single file/table to do the bulk insert.  I have learned that table names need to be static.
So how can I bulk insert into a collection of tables from a directory of files with a corresponding name?
Comment: is is possible that you are not properly building the dynamic SQL? try something like: `SET @sqlCommand = 'BULK INSERT '+@tableName+' FROM '''+@path + @tableName+''' ...`  verify you have a properly concatenated the sql command by replacing `EXEC(@sqlCommand)` with `print @sqlCommand`
Comment: Alternatively, if you want to try the batch file route, you can check out this link: http://stackoverflow.com/questions/4663928/batch-script-loop-through-file-names. And google something like 'dos batch commands' for more info.
Comment: if all else fails, you could try to use command line BCP and not use your tsql loop code
Comment: What part of this code in specific are you having trouble with?
Comment: @KM He could accomplish the same thing with a batch file and bcp, but I don't know that it would be any less work.
Comment: Thanks guys.  I cannot dynamically set table names such as BULK INSERT #myTable or FROM #myTable
Comment: simple brute force method: in dos you can do: `dir > yourfile` to  create a file containing all your file names, use an editor to convert each line of "yourfile" into a BCP command, and then you can run that edited "yourfile" to BCP everyhing
Comment: @BVernon I could use other tools.  I am exploring what I can and cannot do with MSSQLMS.  Moving from Informix AIX to SQL Server.
Comment: @KM Thanks, but I have learned from this very community that this is not possible.  See http://stackoverflow.com/questions/2838490/table-name-as-variable
Comment: @dotnetnewb the code you list in your question won't work, just like the code in your linked question.  The code in my comment will build a proper sql string that can be executed.  by building your SQL command in a string you make the table names static.
Comment: KM is right, the problem with your code is that you can't select from a variable table name. However, you can construct a query string that uses the variable name and execute that. (I know I'm just repeating what KM just said, but just wanted to make sure it was clear what he was saying).
Comment: @KM please leave an answer.  Thanks for clarifying guys and helping me understand.  Much appreciated.
Answer: You look like you are concatenating the SQL string incorrectly try something like:
SET @sqlCommand = 'BULK INSERT '+@tableName+' FROM '''+@path + @tableName+'''

If you use special characters within your tab;e name you can also try:
SET @sqlCommand = 'BULK INSERT ['+@tableName+'] FROM '''+@path + @tableName+'''

You can verify you have a properly concatenated the sql command by replacing EXEC(@sqlCommand) with print @sqlCommand.  Take the printed command and try running it, if you get an error, take the message and look into what it means and try to fix your syntax.
By dynamically building a SQL string you take the @Variable table name and make it a static literal that is concatenated into the command.


How to open VS code terminal on Mac with PC keyboard?

Question: To open the terminal you would press ctrl+˜ on PC and on Mac.
However to write tilde/backtick on Mac, using a PC keyboard, the only solution I found is to press Alt+space+n.
but trying to open the VS code terminal with ctrl+alt+space+n won't work.
Is it possible then to open that terminal with the keyboard, on Mac, using a PC keyboard?
Answer: If you use a Mac keyboard, you can use the `^+ shortcut to open the terminal in VS Code.
If you use a PC keyboard, you may need to change the shortcut to something else that works on your PC keyboard.
To change the shortcut, you need to open Keyboard Shortcuts panel (⌘K ⌘S or Windows+K Windows+S or View > Command Palette > Preferences: Open Keyboard Shortcuts) and search for Terminal: Toggle Integrated Terminal, and then set a new key combination.
Comment: I'm glad you solved the problem. : )


C++ fstream: More signs readen than intended

Question: this issue is really strange to me.. I'm creating and writing into a simple file.
When I'm reading with this code:
return_chars = new char[10];

file.read(return_chars, 10);

The result simply contains 4 characters more! It's 14 signs long.
This happens only when reading 10 characters and some certain other numbers (24 for example).
At a length of 8 it doesn't happen.
The signs it adds are always the same at 10 characters: CE=0
This is the code I use for example to show what I read from the file:
MessageBoxA(NULL, return_chars, "title", 0);

Where is the issue? o.o
Lots of thanks in advance!
Comment: `file.read()` doesn't null-terminate the string. If `showText()` expects a null terminator, it will be disappointed.
Comment: You're using C++, use std::string instead of C strings and you won't have problems like this.
Comment: Maybe it's a bug with your showtext method?
Comment: sorry, the showText method is irrelevant. The second code part is how I am displaying the text! Can the issue be there?
And how do I use c++ strings with file.read? It doesn't accept a string..
Comment: it accepts a `char*`, and `&mystring[0]` is (unfortunately) the best way to get a `char*` out of a `std::string`.
Answer: Just a guess from the limited information you gave, maybe the showText method doesn't handle the return_chars array correctly because it isn't a null terminated string? You could try,
return_chars = new char[11];

file.read(return_chars, 10);
return_chars[10] = '\0';

showText(return_chars);

Comment: Ahh, okey! Thank you, yes that was the issue! (will mark you answer as the right one in 6 minutes when I can, lol)


How to create Newsletter in drupal?

Question: I want to create a newsletter in drupal. What i want is the ability to subscribe the users that are not registered to the site. I can use the third party or any contrib modules available . Any help ..?
Comment: check this https://www.drupal.org/node/645108
Answer: Check out Simplenews module.

Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.

How to create Newsletter in drupal?