How to pass additional information to a callback of a 3rd party module in node.js

Question: It is a simple node.js application. I'm using Browser.visit(url, callback) provided by Zombie module (http://zombie.labnotes.org), Browser.visit() will call the callback as (error, browser, status) in uncertain future with different context. And my callback need some extra information to finish its job.
So far I can make it "working" as:
function test(title, url) {
    var browser = new Browser();
    browser.visit(url, function (e, browser, status, thetitle)
    {
         // generate info using the title if browser visited url successfully
    }
    .bind(undefined, browser, undefined, title);
}

test("foo", fooUrl);
test("bar", barUrl);

But there is a problem, the bind() just bypassed the error and status parameters. It seems not the right way. How could I pass the additional info to this callback?
FYI: Just got confirmed, the API doc of Zombie.js is for 1.4.x, 2.0.0-Alpha API is not finalized yet. https://groups.google.com/forum/?hl=en#!topic/zombie-js/qOS0W_cMCgQ
Answer: It's a little difficult to understand your question, I'm not sure why you are using bind, but perhaps this is what you are trying to achieve?
Javascript
function Browser(url) {
    this.url = url;
}

Browser.prototype.visit = function (url, fn) {
    var self = this,
        error = 'error',
        status = 'status';

    setTimeout(function () {
        fn(error, self, status);
    }, 1000);
};

function test(title, url) {
    var browser = new Browser(url);

    browser.visit(url, (function (theTitle) {
        return function (theError, theBrowser, theStatus) {
            // generate info using the title if browser visited url successfully
            console.log('theError: ', theError);
            console.log('theBrowser: ', theBrowser);
            console.log('theStatus: ', theStatus);
            console.log('theTitle: ', theTitle);
        };
    }(title)));
}

test('hello', 'world');
test('goodbye', 'mum');

Output
theError:  error
theBrowser:  Browser {url: "world", visit: function}
theStatus:  status
theTitle:  hello

theError:  error
theBrowser:  Browser {url: "mum", visit: function}
theStatus:  status
theTitle:  goodbye

On jsFiddle
Comment: I just add the link to Zombie.js module. You are almost there, except visit will call fn as fn(error, this, status), all these 3 parameters are important for the callback.
Comment: I've updated my answer, although I'm still unclear as to what you are trying to achieve.
Comment: Sorry, as I have mentioned I'm using node.js, when my callback is called, it is async running in not-the-same context, which means title parameter of test() is no longer available for access.
Comment: In my case, the context of calling Browser.visit() is different than   the one invoking the fn/callback because Browser invokes it when some event appears but the visit() call returns immediately. Sorry it is my bad not to explain more details about node.js background and thanks for the information anyway.
Comment: Not sure exactly what you mean without you providing some further code example of your problem. But updated again showing the `title` captured locally to the function that you are providing to `visit`
Comment: you are right, wrapping in a closure works. I got some misunderstanding or misleading on Zombie.js API, the value of callback parameters are undefined instead of those described in API doc.
Answer: There is no need to use bind just to make the anonymous function passed to browser.visit access title. This would work:
function test(title, url) {
    var browser = new Browser();
    browser.visit(url, function (e, browser, status) {
        console.log(title);
    });
}

The value of title in console.log(title) is the same as the value of the title parameter of the test function.
Note that this works whether the callback passed to browser.visit is called synchronously or asynchronously.
Comment: This was an example that I demonstrated previously, and believed would work also, but the OP is saying that it doesn't?
Comment: It is my first version indeed, but it is not right here. If I call test() multiple times, title will be always the last one.
Comment: That should not be the case with the latest example that I have given.
Comment: @pinxue Either you are not testing the code correctly or there is something you have failed to tell us in your question. Because if what your question shows is complete then using `bind` like you show in your question would suffer from the *exact same problem* you claim my answer suffers from.
Comment: As I said, this would seem to work for me too and was my first suggestion, [jsFiddle](http://jsfiddle.net/Xotic750/a68GU/). There has to be some information that we are missing.
Comment: @Xotic750 Yes, something is missing.


How do I connect to a node.js(keystone) app on a remote host? 0.0.0.0:3000

Question: I want to play around with node.js a bit so I launched an Amazon ec2 micro instance. I set up node and keystone, it appears to be running:
<code>------------------------------------------------
KeystoneJS Started:
My Project is ready on http://0.0.0.0:3000
------------------------------------------------
</code>
I've tried connecting to my app via: my-remote-ip-address:3000 but it just keeps timing out. I'm very inexperienced with the server side, what am I forgetting?
Comment: It's not clear what you're trying to do and where this server is running. Is this a server on your local machine that you are trying to access from another machine? Is this deployed and running on AWS?
Comment: Yeah, this is deployed and running on AWS. I'm just trying to access it from a web browser. Keystone is a Node.js CMS, it should be accessible from a browser.
Answer: By default AWS only allows incoming HTTP requests on port 80
So your request to port 3000 will time out.
You have two options:

Open port 3000 in the AWS console
Login to AWS console > goto EC2 instances > at the extreme right under security  groups click on the group to open the group linked to that particular instance. > in the tabs below select inbound > edit > add rule > type - HTTP, port - 3000, IP - anywhere or you own > save
In your EC2 instance use a server like nginx to internally point requests that come to port 80 to the port your node server is running on i.e. 3000
So you will only need to got to my-remote-ip-address and nginx will internally redirect the request
Comment: Thanks. This fixed it!


$x^{\log_b{a}}=2$ ; find $x$.

Question: I was solving one problem in which I had to find the value of $x$ and at the last step my result came out to be $x^{\log_b{a}}=2$ but I was not able to get to the correct answer after this. Here's what I did:
$$\begin{align}
&x^{\log_b{a}}=2\\
\Rightarrow\; & \log_b{a}\cdot\log_b{x}=\log_b{2} \rightarrow \text{Taking log to the base }b\text{ on both side}\\
\Rightarrow\; & \log_b{x}=\frac{\log_b{2}}{\log_b{a}}\\
\Rightarrow\; & \log_b{x}= \log_a{2}
\end{align}$$
But as you see I was not able to proceed ahead and I tried other ways to get to the solution but I was not able to.
The correct answer that has been provided is $x=2^{\log_a{b}}$. Can someone please help me as to how to get to this form of the answer?
Comment: Also, instead of writing `$log$` for logarithms, which ends up looking like $log$ which looks like $l$, multiplied by $o$ multiplied by $g$, write `$\log$` which typesets it as $\log$. Same for $sin,cos,arctan$ and so on which are all better as $\sin,\cos,\arctan$. And one final thing, use `$\cdot$` for the multiplication sign instead of a period. $a\cdot b$ looks much nicer than $a.b$.
Comment: Note the edits I made to your question. In general, it is better to use double dollar signs to format multiline equations. The `\begin{align}\end{align}` environment helps to further typeset it so it looks nicer. I advise you review all my edits to see how they improve the post :)
Comment: @5xum : Thanks! I will take care of these things from the next time.
Answer: In the reals, if $\beta > 0$, the solution to the equation $$x^{\alpha} = \beta$$ is $x=\beta^\frac{1}{\alpha}$ which is also sometimes written as $x=\sqrt[\alpha]{\beta}$.
Note that this is the same solution as the provided answer, because in your case, $\beta=2$ and $\alpha=\log_b a$, which means
$$x=2^{\frac{1}{\log_b a}} = 2^{\log_a b}$$
the last equality being true because, in general,
$$\frac{1}{\log_b(a)} = \frac{1}{\frac{\ln a}{\ln b}} = \frac{\ln b}{\ln a} = \log_a(b)$$
Answer: Take $\rm\log$ w.r.t. $\rm \, base\,2$ so that $$\rm\log_ba \log_2x=1\implies \log_2x=\frac 1{\log_ba}=\log_ab\implies x=2^{\log_ba}$$
The first implication assumes $\rm a\ne 1$.
Comment: $a\ne 1$ follows from $x^{\log_b a} = 2$ as $a= 1$ implies $ 1 = x^0 = \ne 2$
Comment: @martini: yes, I just wanted to emphasize and justify the division by $\log_ba$. :)

$x^{\log_b{a}}=2$ ; find $x$.


Bind data from outside of Itemsource of listView in xamarin Forms

Question: Hello I'm working on Xamarin.Forms, I'm facing a problem of data binding in ListView. There's a string value in model and a list in model, the list is the ItemsSource of ListView and string value should be shown in every cell row.
XMAL View
<ListView ItemsSource="{Binding StudentList, Mode=TwoWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>

                     //// Not present in Itemsource. Should bind from Model. It does not render.
                 </Stacklayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C#
public ObservableCollection<PagingButtons> _lstPagingButtons { get; set; }
public ObservableCollection<PagingButtons> lstPagingButtons
{
    get { return _lstPagingButtons; }
    set
    {
        _lstPagingButtons = value;
        OnPropertyChanged();
    }
}
string _ConstantName {get; set;} = "Xamarin";
public string ConstantName
{
    get { return _ConstantName; }
    set { __ConstantName = value; OnPropertyChange();
}

I know that I can add ConstantName to PagingButtons class but I do have this scenario for 30-40 class and it will be tedious to do that and wont be effective way to do that.
Answer: I'm going to assume that there is a ContentPage around your ListView, but this can be any page (or even element).
Give that page a name, if it doesn't already have one, like this: <ContentPage x:Name="MyAwesomePage" ...>
Now, change your Label to this:
This way, you refer the binding to your page's BindingContext, effectively changing the scope.
Answer: You can simply do
<Label Text={Binding Source={x:Reference root}, Path=BindingContext._ConstantName}

Comment: Note that `_ConstantName` is the private field, so the code as presented here will not work. Also, I am not aware of the `root` keyword, but that may be missing knowledge on my part
Comment: Indeed, I didn't notice it was private. I've used in the past syntax like this.
Comment: Cool, I'd have to try it. Didn't know that was possible :-) thanks!
Comment: I tried it but it didn't worked, even made that field as public


xml parsing error syntax error line number 1 column 1 in jquery ajax

Question: Following is the code I use for an ajax call. While executing this it gives me an error xml parsing error syntax error line number 1 column 1 in fiebug. I viewed some questions stating the same problem and they suggested that there was some syntactical problem. I checked again but couldn't find out the real culprit. Please tell me what I am doing wrong.
<code>  $.ajax({type: "GET",
            cache: false,
            url: 'url',
            data : 'param1='+ param1val+ '&param2='+param1val,
            dataType: 'json',
            success: function(Obj){
                if(Some Condition){
                   //Some Code
                }else{
                  //else code
                }
            },

        });
</code>
Here goes some controller code.
<code>   @RequestMapping(value = "url", method = RequestMethod.GET)
    public @ResponseBody SomeObject url(@RequestParam(value="param1val") String  abc ,@RequestParam(value="param2val") String xyz)
   { //some code}
</code>
Edit
I added some debugging code to JS and the controller code as well. To my surprise, control executes successful first comes (in JS) and then goes into controller. Is it supposed to happen like this?
Comment: Are you sure you don't getting json instead of xml? Could you post an example of your data, which produces the error?
Comment: What format is used for the object, and what format is set in http-header? Anyway, without an exapmle of data which produces the error, it will be just hit-and-miss guessing.
Comment: You should URL encode the req params in your javascript. See http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript & http://xkr.us/articles/javascript/encode-compare/
Comment: Reading the link,gives me impression that encodeURI is use in js.I am using jquery ajax,do I need to do that?
Comment: From controller I do return a custom object.Shouldn't I use json than.Though I've tried with datatype=xml as well.It was no help either.:(
Answer: Firefox shows this error if the response type is not set correctly. It tries to parse the response as XML. To fix it, set the response type for what you are sending back to the client, for example for JSON with Spring:
<code>@RequestMapping(value = "url",
                method = RequestMethod.GET,
                produces = "application/json")
</code>


Expressions for standard error

Question: Most of the statistics textbooks claim that point estimator $\hat\theta_n(\mathbf{X})$ is asymptotically normal if
$$\sqrt{n}(\hat\theta_n - \theta) \, \overset{d}{\longrightarrow} \, \mathcal{N}(0, \sigma^2(\theta)), \qquad \forall \theta \in \Theta$$
where $\sigma^2(\theta)$ is called asymptotic variance of $\hat\theta_n$.
Moreover, if $\sigma(\theta)$ is a continuous function of $\theta$ ($\forall \theta \in \Theta$), we can write that
$$\frac{\sqrt{n}(\hat\theta_n - \theta)}{\sigma(\theta)} \, \overset{d}{\longrightarrow} \, \mathcal{N}(0, 1), \qquad \forall \theta \in \Theta$$
But Larry Wasserman in his book "All of statistics" give the following definition of the asymptotically normal estimator:

An estimator is asymptotically Normal if
  $$\frac{\hat\theta_n - \theta}{\mathrm{SE}} \, \overset{d}{\longrightarrow} \, \mathcal{N}(0, 1)$$

So we have that $\mathrm{SE} = \frac{\sigma(\theta)}{\sqrt{n}}$.
Also Wasserman previously defined standard error as $\mathrm{SE} = \sqrt{\mathrm{Var}_\theta(\hat\theta)}$.
Therefore, for any asymptotically normal estimator $\hat\theta_n$ I concluded that $$\mathrm{SE} = \sqrt{\mathrm{Var}_\theta(\hat\theta)} = \frac{\sigma(\theta)}{\sqrt{n}} \qquad (*)$$
I know that $(*)$ is true when $\hat\theta_n$ is a sample mean (in that case $\sigma(\theta) \equiv \sigma = \sqrt{\mathrm{Var}(X)}$)
But is $(*)$ true for any asymptotically normal estimator ?
P.s. In some sources I have seen that quantity $\frac{\sigma(\theta)}{\sqrt{n}}$ is called "asymptotic standard error" and actively used in building confidence intervals. Also please keep in mind that I am not talking about the estimated standard error $\widehat{\mathrm{SE}}(\hat\theta_n) = \sqrt{\widehat{\mathrm{Var}}(\hat\theta_n)}$ which is an observed value.

EDIT. mpiktas's answer seems to be the truth.
Indeed, the equality $(*)$ is correct only for sample mean $\overline{X}$. If we get another asymptotically normal estimator, for example sample variance $S^2 =\frac{1}{n-1} \sum_{i=1}^n (X_i - \overline{X})^2$, then the equality $(*)$ will not hold. It is easy to show.
On the one hand,
$$\mathrm{SE}(S^2) = \sqrt{\mathrm{Var}(S^2)} = \sqrt{\frac{1}{n} \left(\mu_4 - \frac{n-3}{n-1}\sigma^4\right)}, \qquad (1)$$ where $\mu_4 = \mathrm{E}[(X_1 - \mu)^4]$ (see wiki, for example).
On the other hand,
$$\frac{\sigma(S^2)}{\sqrt{n}} = \frac{\sqrt{\mu_4 - \sigma^4}}{\sqrt{n}}, \qquad (2)$$
where $\sigma(S^2)$ is a square root of the asymptotic variance of $S^2$ (see proof here).
Expressions (1) and (2) are not equal, i.e. $\mathrm{SE}(S^2) =\sqrt{\mathrm{Var}(S^2) } \neq \sigma(S^2)/\sqrt{n}$.
But we have the following convergence:
$$\sqrt{n} \, \mathrm{SE}(S^2) \, \overset{n \to \infty}{\longrightarrow} \, \sigma(S^2) = \sqrt{\mu_4 - \sigma^4}.$$
Answer: The answer is no.
Your definition is wrong. SE is calculated from data, $\sigma(\theta)$ is not observed and is a theoretical concept. So there cannot be a equality.
The correct conclusion which you should have made is the following
$$\sqrt{n}SE \to \sigma$$
for the asymptotically normal estimator $\hat\theta$. This is correct for all asymptotically normal estimators. (Note there might some weird cases when this does not hold related to intricacies of CLT, but since I cannot recall them at the moment I am putting this disclaimer just in case).
Comment: Thanks for the answer. I want to clarify - correct definition of SE is the following: $\mathrm{SE}(\hat\theta_n) = \sqrt{\mathrm{Var}(\hat\theta_n)}$, and generally $\sqrt{\mathrm{Var}(\hat\theta_n)} \neq \frac{\sigma(\theta)}{\sqrt{n}}$, right? (we can only say that $\sqrt{n}\, \mathrm{SE}(\hat\theta) = \sqrt{n \cdot \mathrm{Var}(\hat\theta_n)} \,\longrightarrow \, \sigma(\theta)$ when $n \longrightarrow \infty$)
Comment: It seems that you are correct! I investigated sample variance $S^2$ to check you idea (see my edit to the post above).
Comment: Note that SE should be an estimate too for the definition to be useful. The whole point of asymptotic normality is to have a quantity which can be calculated which is approximately normal.

Expressions for standard error


redirection in htaccess file

Question: I'm working on Drupal7.
I want to redirect all the URl's to external domain except some.
Below rewrite I have added in .htaccess file and its working fine.
RewriteCond %{REQUEST_URI} !/user.*$
RewriteCond %{REQUEST_URI} !/testurl.*$
RewriteRule .* https://abcxyz.com [R=301,L]

But then, homepage also redirecting to https://abcxyz.com
How to stop homepage redirection or how to add homepage in the exclude list like user, testurl?
I have tried below to exclude the homepage in the redirection.
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !/index.php$
RewriteCond %{REQUEST_URI} !/homepage$

But nothing worked.
Can you help me on this please?
Comment: This is more an Apache question than a Drupal one, but try `RewriteCond %{REQUEST_URI} !^/$` (i.e. exclude when the first character is `/` followed by end of line)
Comment: I tried this: RewriteCond %{REQUEST_URI} !^/$ but not worked
Comment: I just verified that `!^/$` works on my dev Drupal 7. Perhaps there is a RewriteRule before yours that conflicts with it. Is it located immediately after the `RewriteEngine on` directive? Is there a `RewriteRule` in your `` or `` directive? Maybe using a permanent redirect (`301`) before you had the correct condition causes your browser's cache to redirect without contacting the server again. Change your rewrite rule to use a temporary redirect: `[R=302,L]`, and use incognito/private mode for testing. By the way closing all incognito mode windows should clear its cache.
Comment: Got the result. In the rewriterule, insted of *, need to add + symbol which is the domain url.  RewriteRule (.+) https://abcxyz.com [R=302,L]
So, now domain, I mean homepage is not redirecting :)
Answer: I had the same problem migrating to a new domain but needed to keep the services endpoints active on old domain since they were externally active. The key was including a RewriteCond for index.php:
RewriteCond %{REQUEST_URI} !^/services/active/endpoint$
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{HTTP_HOST} ^old-domain\.org$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://new-domain/$1 [L,R=301]

redirection in htaccess file


Token insert with CKEditor doesn't work

Question: I'm using the CKEditor Module in combination with the Token insert (ckeditor) to show a user property in my body.
It looks like this:

But the results shows just the static text instead of the user property. What am I doing wrong?
UPDATE:
I've also tried to add the Token insert button to my editor like this:

But every time I save this and check again it is switched back.
These modules are enabled:

Entity Tokens
Token insert (ckeditor)
Token insert (text)
Token insert UI
Token

UPDATE:
The test gave me a result like this:

I tried to add a random number in my text field but the result just gave me the static text <code>[random:number]</code> instead of a random number...
Comment: Is the [Token Module](https://drupal.org/project/token) Installed??
Comment: Yes, The Token module is installed. Also Entity Tokens, Tokens insert (ckeditor), Token insert (text) and Token insert UI.
Comment: Are you using one of the [core tokens](https://drupal.org/node/390482)?  I'm trying to determine if it's your addin module, or a misconfigured Drupal Core...
Comment: I've tried it with for ex.: [current-page:url] and with a user property like: [current-user:name]. Both just gave the exact text back.
Comment: What does [this test](https://drupal.org/node/1327676) yield?
Comment: Updated my topic with the test.
Answer: You need to install the token filter module for the token insert to work.
Download the module.
Configure the tokens you want to use by role or globaly.

and add the filter in the Text Format:

Then you can use the ckeditor plugin to add the token in the Fields that have this Text format, and thats all.
I've just test and it works perfect.
Answer: You can try the Advanced Text Formatter module.
It has Token Replace feature. Personally, I like the idea replace the tokens using Field Display, you can choose to replace any fields in whatever (display) mode you want.
It's more flexible and good for performance. The con is it works only for field :)
Answer: token_filter was not installed for me. It's not a dependency but it is required for this to work. "Replace tokens" filter is not available without it.

Token insert with CKEditor doesn't work


What Adds "Cream" to a Guitar Tone?

Question: I've got an American ESP, 2 humbuckers through a tube screamer and Fender Hot Rod Deluxe tube amp. Though I can get a great tone with just these, my tone lacks a bit of cream audible when this guy rocks an over driven bend or vibrato. The sounds he gets is a bit creamy, almost on the mid range sound while my tone with the above gear is a bit more edgier/trebly.
There must be a certain element to his tone that adds this cream and boosts those bends as if someone were singing almost. Wah?
Comment: @Time4Tea, You beat me to it.
Comment: @ggcg I was going to answer 'Eric Clapton', but thought better of it ...
Comment: @Time4Tea, my first thought was Clapton, no joke.  Because a lot of famous guitarists have signature series guitars or electronics.  Milk came second.
Comment: When you say 'cream', are you referring to the band or the dairy product?
Comment: @Time4Tea a sort of warmth combined with clear mid-range  tones sounding almost vocal (my approximation to a definition). In other words, imagine the sound of a distorted tube amp from humbuckers and compare to the one in the video.
Comment: @user3704920, vocals aren't necessarily "creamy".  I think it would help if you could be a little more objective in your post.
Comment: I'd try to find the make model of the guitar the guy plays and check the regulator (middle one) he turns to get the sound.
Answer: It might seem obvious, and I'm sure you know it already, but the choice of pickup can have a big effect on the tone of an electric guitar sound (one of many factors, of course). The neck pickup tends to sound noticeably fuller and warmer; whereas the bridge pickup, by comparison, tends to be thinner and a little 'colder' (but also 'tighter'). I have 3 pickups on mine - if I'm playing a clean-ish tone then I often use neck/middle, but if I'm playing something very distorted and metally, I tend towards the bridge pickup for more tightness.
To use your milk analogy: neck pickup is full fat/cream and bridge is skimmed ;-)
So, to get a a richer sound like that, he may using more of the neck pickup. He is switching pickups and tweaking the tone control knobs quite frequently as he is playing, so it seems likely that is at least part of the answer.
Have you tried asking him through YouTube what gear he is using? Also, it might help if you post a sample of the sound you are getting, so we can hear the comparison.
(btw, that guy is really good - wish I could play like that! :-) )
Comment: I was not criticizing the use of the terms by @Time4Tea, but a general mismatch between music jargon and physics jargon.  I've heard others do the same, and being a musician and a physicist I get to each group butcher the vocabulary of the other group.  Just an OCD pet peeve of mine.  An item of interest.
Comment: That is a thoughtful answer, +1.  Though the use of adjectives "rich", "full" and "thin" always confuse me in this context.  From a physics point of view the neck pickup cannot "pick up" as many overtones as the bridge pickup.  So the bridge pick up raw spectrum usually has more frequency content which I would call "rich" and "full".  Whereas the neck pickup I would call empty or dull (dull being "smooth").  It has more fundamental.  This also depends on where you apply the pick.  Pick closer to the bridge = twangy, closer to the neck = warm and smooth.  It is a very complex system.
Comment: "he may be switching the pickup mix" he is switching the pickups, adjusting volume and tone knobs and fiddling on the amp controls almost constantly.
Comment: @ggcg I agree those terms are a little subjective. I was trying to answer more from the point of view of the sound I hear, as opposed to the physics, and was trying to link it to the 'milk' analogy that the OP used.
Comment: @Yorik good point, I will adjust my answer. Thanks
Answer: I'd say the guy in the video gets his "cream" by digging in hard with his pick, pressing fairly hard with his fretting fingers and synchronising his hands well. Plus his bends and vibrato are grounded in good technique involving not just the wrist, hand and fingers but the forearm as well.
After all, tone IS in the fingers (and other body parts).
Answer: I would disagree with the first answer.  It is clear that he's using effects, either pedals or channel switching in the amp.  He seems to be picking the same on clean sounds and "digging in hard" can have the effect of killing the sound.  That depends on a lot of factors.  I think the unique sound the OP is searching for is in the electronics.  I doubt that the OP doesn't know how to vibrato or end a string.  The question is why can't I get the same tone (tone is the creamy part).  While tone is somewhat determined by the hands (on a clean guitar it is determined more by the hand than electronics and on a classical guitar it is more in the hand and the quality of the guitar), with such an over processed sound the electronics start to take over.
I think a better wording of the question is "Can someone identify how to get the tone this guy has in the video at time = 1:30 min" or elsewhere.  Since there are so many sounds it isn't fair to have us watch the video and guess what tone the OP is referring to.
Comment: Shouldn't this be a comment to the first answer, since it doesn't answer the question?
Comment: Perhaps but I disagree.  I did posit that the tone was due to the electronics.  If you're suggesting that I should identify the electronics then you have a point.  That I cannot do.  But I'm at least offering the advice that the OP author play with effects to achieve that tone.
Comment: You are right. Maybe split it into a comment to the first answer, an actual answer, and a comment to the question (last paragraph)? Would this be clearer?
Comment: Thanks.  I'll think about it.  I did use my critique of answer one as a lead in to my thoughts.  I'll apply some deconvolution later.
Answer: Everything in the chain starting from his technique and the strings on his guitar, the pick-ups, the tone settings, the amplifier, the stomp boxes, the type of loudspeakers and more. It all affects what you hear in the end. If you're looking for a quick easy answer, I wish you luck in finding one.

What Adds "Cream" to a Guitar Tone?


What is the entropy of a composition of Gaussian Processes?

Question: I have a very basic understanding of Gaussian Processes.  From what I understand, a Guassian process for a set $X$, is the assignment of a Gaussian distribution to every element of the set.  This is meant to expand the idea of a function to the case where we don't have total information about a function.
I have a question about how we compute the entropy of a Gaussian Process over here.  I also asked about whether or not we can compose Gaussian Processes and that question is here.
This question combines those other ones.  Suppose we have entropies, $S_f$ and $S_g$, for two Gaussian Processes, $\mathcal{G}_f, \mathcal{G}_g$.  Next, suppose we can compose two Gaussian Processes, $\mathcal{G}_f \cdot \mathcal{G}_g$.  Is the entropy for the composition a simple function of the individual entropies?
ie
$$S_{\mathcal{G}_f \cdot \mathcal{G}_g} = F(S_f, S_g)$$
Answer: Based on my other two answers to your questions, I do not think that such an expression exists because the entropy of the composition $f \circ g$ will explicitly depend on values of the function $g$, which is random.
One way to estimate the entropy for a fixed set of indices $t_1, ..., t_m$ value is by simulating the $\log(p_{f \circ g}(t))$.
Note that:
$$ p_G(g) =  |2 \pi \Sigma_G(t_1, ..., t_m)|^{-1/2}exp(-0.5*g^T \Sigma_G^{-1}(t_1, ..., t_m)g)$$
$$ p_{f \circ g | g}(f) =  |2 \pi \Sigma_F(g_1, ..., g_m)|^{-1/2}exp(-0.5*f^T \Sigma_F^{-1}(g_1, ..., g_m)f)$$
... and so, the joint density can be obtained by multiplying these. If we simulate a bunch of $g$s and $f$s and plug them into the log joint density and obtain a sample mean, we can obtain an estimate for the entropy.
Side note: 'training' a GP usually means working out the posterior distribution given a set of observed values. This posterior has a different covariance matrix (see this link) than a GP prior, hence a different entropy.


Declaring an NSDictionary with an NSString as its name

Question: Ok, so I would like to create an NSDictionary, but the pointer should be followed by the value of an NSString that has been put in by the user. Is this possible? I imagine it would be something along the lines of this...
someNSString = _someTextField.text;
NSDictionary * {someNSString} = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:someUnimportantVariable], @"someUnimportantKey",...nil]

Thanks in advance, I realize that this is either completely not possible or there is a pretty simple solution. Either way, I'm sorry if I wasted your time.
Comment: After testing this, it didnt work for me.
Comment: I'm really just trying to see what the syntax is for the curly braces portion of my code. The rest is just further description.
Answer: you could try creating a "dictionary of dictionaries". something to the effect of:
someNSString = _someTextField.text;
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setObject:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:someUnimportantVariable], @"someUnimportantKey",...nil] forKey:someNSString];

and if you wanted to get back that dictionary
NSDictionary someNSStringDictionary = [myDictionary objectForKey:someNSString];

let me know if it helps in any way.


How to identify if a Type is a custom struct?

Question: For a Type, there is a property IsClass, but how to know a Type is a struct?
Sorry, I have to add some more information.

I am using C#.
Although IsValueType is a necessary condition, it is obviously not enough. For an Integer is a value type also.
Comment: possible duplicate of [How to decide a Type is a custom struct?](http://stackoverflow.com/questions/2296288/how-to-decide-a-type-is-a-custom-struct)
Answer: t.IsValueType && !t.IsPrimitive && !t.IsEnum;

Comment: Sometimes in C# we count them as such, because they're value types, but `struct` comes from "structured", referring to structs' composite nature (normally having more than one field, though 0 or 1 is permissable) and the origin of the keyword back in C, though C# and C structs are different in several ways. It's clear from the question that the OP was thinking the latter way rather than the former. This view doesn't take a "turtles all the way down" perspective, but takes the units that can't be broken down any further, to not be structs.
Comment: I dont' get the reason of `!t.IsPrimitive`. `Boolean`, `Byte`, `Char`, `Double` (etc...) are not structs?
Answer: If you are talking about c#, you can use the IsValueType property.
Answer: If it's a value type (e.g., a struct), use Type.IsValueType.
Answer: You can use IsValueType.
Answer: Well then, I guess for your requirement then this comes close:
bool isStruct = myType.IsValueType && !myType.IsPrimitive;

but still DateTime isn't covered by that for example. Maybe you would have to add further types you want to exlude manually.
Comment: DateTime gives the correct result of true with this code. It's enums that it doesn't handle correctly.
Answer: use this:
 x.GetType().IsValueType();

From help:
Type::IsValueType Property
Gets a value indicating whether the Type is a value type.
Value types are types that are represented as sequences of bits; value types are not classes or interfaces. Value types are referred to as "structs" in some programming languages. Enums are a special case of value types.
Comment: Types have different meanings when applied to storage location than when applied to heap objects. Under the hood, every value type has an associated heap type.  Casting a value type to `Object` or to an interface that it implements will create a new heap object whose fields are copied from the value-type instance being cast. Calling `GetType` on a value type will cast it to `Object` first, since value types don't have the type-destrictor field required by `GetType`.


Java Modelmapper: Converter doesnt get used

Question: im working on a little java-program that synchronizes active directory users with users in my db. therefor, i am using modelmapper. seems to be working fine and is also pretty fast.
anyway i added a converter to my mapping configuration. shows no markers, and i checked the syntax, so it should be fine. but when i fire the syncer to see if hes mapping everything correctly, nothing happens. i mean, the objects get mapped correctly but not the property i set the converter for.
i already went into debug-mode, the convert method is not even entered, not once
so heres my modelmapper-propertymapconfiguration
private PropertyMap<ActiveDirectoryUser, User> createUserMap = new PropertyMap<ActiveDirectoryUser, User>() {
    protected void configure() {
        map(source.getCn(), destination.getFullName());
        map(source.getsAMAccountName(), destination.getLoginName());
        map(source.getMail(), destination.getEmail());
        map(source.isEnabled(), destination.isActive());
        using(new ModelmapperMemberOfToIsAdminConverter(Arrays.asList(ConfigApp.get(ConfigKeys.AD_DISTINGUISHEDNAME_ADMINS).split(";")))
                ).map(source.getGroupMembership(), destination.isAdmin());
    };
};

and theres my converter:
package ch.itp.absencemanagersync.synchronize;

import java.util.ArrayList;
import java.util.List;

import org.modelmapper.AbstractConverter;

public class ModelmapperMemberOfToIsAdminConverter extends AbstractConverter<ArrayList<String>, Boolean>{

    private List<String> comparisonList;

    protected ModelmapperMemberOfToIsAdminConverter(List<String> blablablist){
        comparisonList = blablablist;
    }

    @Override
    protected Boolean convert(ArrayList<String> source) {
        //empty for now, will do some logic here later
        //for testing, always return true
        return true;
    }

}

so if i run the syncer, in theory, every user in my db should turn admin, but that doesnt happen
i dont know what im doing wrong here, any help is appreciated^^
ps: dont worry about the Arrays.asList shit in the config, thats working just fine
greetings,
mike
Answer: working code:
mapping config:
private PropertyMap<ActiveDirectoryUser, User> createUserMap = new PropertyMap<ActiveDirectoryUser, User>() {
    protected void configure() {
        using(myConverter).map(source.getGroupMembership()).setAdmin(false);
        map(source.getCn(), destination.getFullName());
        map(source.getsAMAccountName(), destination.getLoginName());
        map(source.getMail(), destination.getEmail());
        map(source.isEnabled(), destination.isActive());
    };
};

and converter:
package ch.itp.absencemanagersync.synchronize;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.modelmapper.AbstractConverter;

import ch.itp.absencemanagersync.util.ConfigApp;
import ch.itp.absencemanagersync.util.ConfigKeys;

public class ModelmapperMemberOfToIsAdminConverter extends AbstractConverter<List<String>, Boolean>{

    private List<String> comparisonList = Arrays.asList(ConfigApp.get(ConfigKeys.AD_DISTINGUISHEDNAME_ADMINS).split(";"));

    protected ModelmapperMemberOfToIsAdminConverter(){
    }
    @Override
    protected Boolean convert(List<String> source) {
        if (!Collections.disjoint(source, comparisonList)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}

is now mapping the desired users to be admins, working correctly


No Method Error but i defined it

Question: I got a NoMethodError when i called <%= @post.admin_user.name %>, don't know how to fix it.
Extracted source (around line #4):

<%= @post.title %>

<%= @post.body %>

Post created at <%= @post.created_at.strftime('%b %d. %Y') %>

<%= @post.admin_user.name %>

Category: <%= link_to @post.category.name, category_path(@post.category.id) %>

<%= link_to 'Edit Post', edit_post_path %> | <%= link_to 'Go Back', posts_path %> |     <%= link_to 'Delete Post', @post, :confirm => "Don't do it man!", :method => :delete %>

Showing c:/Sites/blog/app/views/posts/show.html.erb where line #5 raised:
undefined method `name' for nil:NilClass

This is my posts_controller.rb
  class PostsController < ApplicationController
     def index
 @post = Post.all

  end

  def new
 @post = Post.new
 @category = Category.all
  end

  def create
  @post = Post.new(post_params)
   if @post.save
   redirect_to posts_path, :notice => 'Your post has been posted!'
   else
   render 'new'
   end
  end

  def post_params
      params.require(:post).permit(:title, :body, :category_id, :admin_user_id, :admin_user, :name)
  end

  def edit
  @post = Post.find(params[:id])
  end

  def update
  @post = Post.find(params[:id])
  if @post.update_attributes(post_params)
     redirect_to post_path, :notice => 'Your post has been updated.'
     else
     render 'new'
    end
  end

  def show
  @post = Post.find(params[:id])
  @user = AdminUser.all
  end

  def destroy
  @post = Post.find(params[:id])
      @post.destroy
      redirect_to posts_path, :notice => 'Your post has been deleted.'
   end

   end

This is my post.rb
class Post < ActiveRecord::Base

  belongs_to :category

 belongs_to :admin_user

end

My admin_user.rd
class AdminUser < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

   has_many :posts

end

Comment: Its giving you error cuz @post.admin_user is nil. Did you create any admin_user associated with post
Answer: The @post you're looking at doesn't have an admin_user associated, so @post.admin_user is nil.
Either put it in a conditional so you only print out the name if the user is present, or use something like try (eg. @post.admin_user.try(:name)).

No Method Error but i defined it


How to change Search API index field machine name?

Question: I am using Search API and Search API Solr modules on drupal 7. I have also drupal 8 and drupal 9 sites, and all those sites are indexed on the same solr index. So I need the same machine name for indexed fields on Solr index. For this purpose, I need to change marked machine names.
Solr index field names are generated from those machine names.

For drupal 7 I can't find a field mapping solution like Search API field map module for drupal 8, 9.
Is there any solution to override those fields' machine names in index creation?
Thanks.
Answer: My answer I found in search_api_solr module search_api_solr.api.php file. I used hook_search_api_solr_field_mapping_alter
<code>/**
 * Change the way the index's field names are mapped to Solr field names.
 *
 * @param SearchApiIndex $index
 *   The index whose field mappings are altered.
 * @param array $fields
 *   An associative array containing the index field names mapped to their Solr
 *   counterparts. The special fields 'search_api_id' and 'search_api_relevance'
 *   are also included.
 */
 function hook_search_api_solr_field_mapping_alter(SearchApiIndex $index,
                                                               array &$fields) {
   if ($index->entity_type == 'node' && isset($fields['body:value'])) {
    $fields['body:value'] = 'tm_text';
   }
 }
</code>
Here you can add required Solr index field name('tm_text') for according field('body:value').


Xcode Animations complete instantly - CAAnimations call didStop - flag = FALSE

Question: I'm getting some weird bugs.  I thought I had a handle on this.  I copied code from one of my other projects.  I'm wondering if it could be something to do with my custom class.
I have a view controller initialize my custom class called "TitleCardView"
Inside there I have a bunch of animations like this one:
CGPoint startPointb = borderMaskLayer.position;
    CGPoint endPointb = CGPointMake(borderMaskLayer.position.x, borderMaskLayer.position.y-1000);
    CABasicAnimation* bmoveAnim = [CABasicAnimation animationWithKeyPath:@"position"];
    bmoveAnim.delegate=self;
    [bmoveAnim setValue:@"borderMaskAnim1" forKey:@"id"];
    bmoveAnim.fromValue = [NSValue valueWithCGPoint:startPointb];
    bmoveAnim.toValue = [NSValue valueWithCGPoint:endPointb];
    bmoveAnim.duration = 1;
    [bmoveAnim setBeginTime:CACurrentMediaTime()+.4];
    bmoveAnim.fillMode = kCAFillModeForwards;
    bmoveAnim.removedOnCompletion = NO;
    bmoveAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    [self.borderLayer.mask addAnimation:bmoveAnim forKey:@"position"];
    [self.borderWhiteLayer.mask addAnimation:bmoveAnim forKey:@"position"];

The animation works fine but when I try to implement AnimationDidStop{, as soon as the view loads, all the animations get logged by the delegate method with the FALSE (did not finish) flag.
I added a button and tried to use:
[UIView animateWithDuration:6 animations:^{
    continueButton.alpha = 1.0f;
 }];

and this code with the delay parameter....
Same problem.  As soon as the view loads, its like the animation gets run immediately with a duration of 0.
Are you not supposed to add animations in your init method?  I feel like there must be a rule I'm breaking that I don't know about.
This code does work:
this button is the last thing in the init method
continueButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [continueButton addTarget:self
                             action:@selector(titleNext)
                   forControlEvents:UIControlEventTouchUpInside];
    [continueButton setTitle:@"Click to Continue" forState:UIControlStateNormal];
    continueButton.frame = CGRectMake(0.0, 390.0, 320.0, 75.0);
    [self addSubview:continueButton];
    continueButton.alpha = 1.0;

then this is the method it calls
-(void)titleNext{
    // proceeds to the motto page from the title page

    [UIView animateWithDuration:.6 animations:^{
        continueButton.alpha = 0.0f;
    }];

}

So can anyone tell me why my animations are acting weird???
Answer: I recreated the project and found the animationDidStop delegate worked when the animations were created in -(void)viewDidAppear{ instead of -(void)viewDidLoad{
Answer: For swift it works if the animations are in
 override func viewDidAppear(_ animated: Bool)


How to get date object prior 3 months from current date in Typescript

Question: I am trying to get the date object before 3 months from current date like this.
toDate = new Date();
fromDate  = this.toDate.getMonth() - 3;

But fromDate is coming as just a number. Every time i want to get the date before 3 months from current date. But this shows only a option like this.
this.fromDate = (this.toDate.getMonth() - 3).toLocaleString()

Is it possible to get the date object before 3 months?
Answer: Maybe i can help
toDate = new Date();
month = toDate.getMonth() -3;
newDate = new Date(toDate.setMonth(month));

Comment: what happen if years are different when i am deducting 3 months like `toDate`  year - 2017 & `fromDate`   year - 2016
Comment: It can, you can test
Comment: toDate = new Date();
->> Wed Jan 06 2021 09:55:54 GMT+0700 (Indochina Time)
newDate = new Date(toDate.setMonth(toDate.getMonth()-3));
-->> Tue Oct 06 2020 09:58:13 GMT+0700 (Indochina Time)
1/2021 -> 10/2020
Answer: The reason you are getting a number from getMonth is because it returns the integer value, or "index", of a month. January is 0, December is 11. See the getMonth docs for more details.
To get a new Date 3 months in the past, you should use the built in Date setMonth function.
function monthsBackFrom(date: Date, n: number): Date {
  // Create a new date so the original is not modified
  const result = new Date(date);

  // Careful, setMonth modifies the date object in place
  result.setMonth(result.getMonth() - n); // Set to n months back from current
  return result;
}

const now = new Date();
const threeMonthsBack: Date = monthsBackFrom(now, 3);

console.log(now.toString()) // Current date and time
console.log(threeMonthsBack.toString()); // Date three months back, same time

Note that setMonth modifies your date in place. It does not create a new one. You will most likely need to create a new Date object when setting fromDate so your toDate is not affected.
setMonth also supports negatives and values greater than 12. Setting the month to -1 will set the date to December of the previous year. Setting the month to 12 will set the date to January of the next year*. Day and time information remains the same.


atop 2.4.0 time interval

Question: In latest version atop 2.4.0 (Repository - epel, CentOS 7) I can't change time interval through config file.
I set "INTERVAL=60" in /etc/sysconfig/atop, restart service, but no effect, interval stay on default value 10min (600sec)
In version 2.3.0 change interval work perfectly through config file.
How to change time interval?
Answer: https://bugzilla.redhat.com/show_bug.cgi?id=1712241
The default /etc/sysconfig/atop has "INTERVAL" defined not "LOGINTERVAL"
Change it to  use "LOGINTERVAL" and atop is started with the correct interval.
Can the default config file be changed to use LOGINTERVAL.
Answer: I have encountered same issue in CentOS Linux release 7.5.1804 (Core) and atop Version: 2.4.0 (also from epel)
My workaround is to use this command directly:
/usr/bin/atop -R -w /var/log/atop/atop_log [time intervel(s)]
For example, this will record data every 10 seconds:
/usr/bin/atop -R -w /var/log/atop/atop_20190810 10
Another way is to edit the script /usr/share/atop/atop.daily which will be executed by /usr/lib/systemd/system/atop.service when service start.But, I choose to use workaround.
Answer: Find the appropriate file to override the interval from the running service or set it from LOGOPTS.
<code># systemctl cat atop |grep -i environmentfile
EnvironmentFile=/etc/default/atop
</code>
For example, here it shows /etc/default/atop as config file.

atop 2.4.0 time interval


Replacing multiple items(commas, periods, etc.) in SQL code

Question: Here is the code that I am using currently, I am trying to replace commas and periods in my database but right now it is only doing one or the other. Thanks
(Case when dim.obligorname like '%,%' then Replace(DIM.[ObligorName], ',', ' ')
           Else case when dim.obligorname like '%.%' then Replace(DIM.[ObligorName], '.', ' ')
            Else Dim.ObligorName end end) as Obligorname,

Answer: Why not just try something like this:
UPDATE myTable DIM
  SET DIM.[ObligorName] =
    Replace(Replace(DIM.[ObligorName], ',', ' '), '.', ' ')

Comment: Thanks for the help!
Answer: How about something like this:
Replace( Replace(DIM.[ObligorName], ',', ' '), '.', ' ')


Vue SSR (Server Side Rendering) with parcel?

Question: I am wondering whether anyone can point me to resources or examples on how to set up parcel for vue SSR (Server Side Rendering).
Or is Vue SSR not possible with parcel?
Comment: I would look to see if Parcel does any kind of Server Side Rendering. They I would see if that can apply to Vue.
Comment: Gatsby.js is SSR React + Webpack. Not what you're looking for obviously, but it's setup and is fantastic.
Comment: Maybe you can try to use Nuxt.js with your project ? Under this link you can read a lot about this problem maybe you will find sth usefull: https://github.com/parcel-bundler/parcel/issues/3464
```"If you meant that Parcel should try and support it by itself(e.g via @parcel/react-ssr), i don't really think it's Parcel's job to support them."```
Answer: Should be as simple as installing the various libraries needed:
# Yarn
$ yarn add parcel-bundler parcel-plugin-vue @vue/component-compiler-utils babel-preset-env -D

# NPM
$ npm install parcel-bundler parcel-plugin-vue @vue/component-compiler-utils babel-preset-env --save-dev

Now you can run npx parcel and you'll be ready to go.
For more detail see: https://alligator.io/vuejs/vue-parceljs/
Comment: I've [tried](https://github.com/chriscalo/vue-ssr/tree/alligator.io-tutorial) the linked tutorial and it doesn't address SSR.
Comment: @cdstamper Maybe you can help me. Look at this : https://stackoverflow.com/questions/59524595/how-can-i-implement-server-side-rendering-ssr-on-the-vuetify-project-that-is-1


Date vs Timestamp field-type

Question: My new project involves the requirement of manually setting a time of creation of nodes because they're looking into manually migrating parts of their old website into their new one. The date will mainly be used to sort the nodes, only 2 out of 6 content types will have the date printed in the frontend.
In D8 you can select between a date and timestamp field. Both output options seem to be the same. The only difference I noticed is the HTML output.
The timestamp output looks like this

Mon, 03/18/2019 - 18:00

Date output looks like that
<time datetime="2019-03-18T18:00:17Z" class="datetime">Mon, 03/18/2019 - 18:00</time>

I found a documentation page for D7 on the matter: https://www.drupal.org/node/1455576 but I have the feeling that this information doesn't apply for those two field types in D8.
Which one should I choose for this purpose? And what's the difference in D8 between those two field types?
Comment: The difference is how they are stored in the DB. [Drupal core uses timestamp](https://i.stack.imgur.com/qtv7W.png). The answer to your question is... depends who you ask. See [Should I use the datetime or timestamp data type in MySQL?](https://stackoverflow.com/questions/409286/should-i-use-the-datetime-or-timestamp-data-type-in-mysql)
Comment: Thank you for the link to this question. This gives a very good overview on the database side, but I was more interested in how Drupal deals with it, especially Views. There seem to be problems with both formats. since I found an issue on datetime [Views treats datetime fields like strings when filtering](https://www.drupal.org/project/drupal/issues/2848908) and a SE question about timestamp [Views timestamp not recognized as date?](https://drupal.stackexchange.com/questions/230523/views-timestamp-not-recognized-as-date)
Comment: @NoSssweat Timestamps are really just ints, and datetime are ISO strings.  Neither use native datatypes in storage because they types (and functions over them) aren't portable across database backends.
Comment: Re the close vote, The "Which one should I choose for this purpose?" is option based, but the "And what's the difference in D8 between those two field types?" is perfectly fine here.
Comment: Aren't they stored as VARCHAR in the database? What if someone builds a field that uses native date type?
Comment: @Kevin Yeah, took some liberty for simplicity.  A `DateTimeItem` is a `VARCHAR(20)` and a `TimestampItem` is an 'INT'.  I am not sure if I played with trying to make them the native types.
Answer: In Drupal 8, timestamps (and created and updated) are stored as integers in the database.  They do not use the native datatype.  Timestamps can be added via the UI, but created and updated can only be used as basefields.
Datetime and daterange fields are stored as ISO strings: date-only as Y-m-d and date+time as the full ISO8601 format (currently without the UTC offset).  These are store as plain strings, not as a native type, since the date/time handling in the default database backends is not portable.
The reason you are seeing different HTML, is that the two field types use different formatters.  Your timestamp is using TimestampFormatter and it looks like your datetime is using DatetimeDefaultFormatter.  It is possible to get both fields to output the same if you use the DatetimePlainFormatterformatter. You can also write your own formatter for timestamps to output HTML5 time.  For various reasons, they formatters between the two types are different.
Answer: From a Drupal perspective, timestamp has issues with Views Filters.
In a recent D7 project, I went with timestamp just to keep things consistent since I was doing custom module date field queries.
In D7 I noticed that View filters only works if you enter a timestamp rather than a date, this is silly! Which makes me think most people use date, since it did not a have this filter issue.
I got around this issue by utilizing views query alter and converting the date string to timestamp.
D8 might also have this issue. So perhaps the safest, most traveled, road is to use date.

Date vs Timestamp field-type


Is this string properly installed?

Question: A friend of mine lend me his 5-strings bass for me to practice for a fill-in.
The instrument feels absolutely flaweless, and the sound is perfect. However when taking a close look at the bridge, I noticed the low B string was slightly higher than the other strings. It even seems it is going to pop out from the bridge at any given time (although it doesn't feel like it, and I have been playing it all day long without any troubles).
When lowering the B string tension, I cannot push the ring any deeper, which worries me a lot. I'm just hoping it will not pop out during the gig ..
Is this a normal state ? Should I get a thinner B string for it to fit deeper in the bridge ?
EDIT : This is a Warwick Streamer LX 5
Comment: That's why you'd need to file it open!   If it was adjustable, you could adjust it.  But don't do that.  Particularly as it isn't your instrument.
Comment: If it hasn't popped out yet, it's unlikely to do so.  If I owned this axe, I would file the anchor points open so the string could fit thru -- looks like it's the string diameter, not the end loop, which is the problem.
Comment: Okay, if it is unlikely to pop out, I'll just leave it as-is. I did not quite understand your tip though. What do you mean "to file the anchor points open" ? The narrow space through which the string goes is not adjustable, it looks like a fixed space
Comment: Have you ever taken a shop class dude?
Comment: @Tama, if you are addressing to me, no I haven't.
Comment: When saying I did not understand the tip, I meant i **really** did not understand the meaning of "to file sthg open"
Answer: I'd prefer to just comment on your question, but I still don't have enough rep...
As others commented, it seems the string is stable in that position. But it really seems to be incorrectly installed - it seems the ring was supposed to be horizontally aligned with the bridge, instead of vertically as it looks in your picture. Take a look at this picture:
You could try to play a little more vigorously just to see if the extra tension will pop it out. If it doesn't, you'll be a little more comfortable to play without having to worry with it; if it does, you'll need to install it again and you can align the ring, but at least it happened out of stage and you'll have time to do it calmly.
Comment: Thanks for the tip ! What I have done is loose the string down, then using a plier to softly press the end of the string, to make it slimmer. Then it could fit deeper in the bridge, and it seems to be fine. I could not afford taking the risk of seeing it pop out during the performance (especially if it hits my face or something really bad like this ..)

Is this string properly installed?


Simulate Cordova plugins in browser

Question: To test a Cordova app I need to run it in an Emulator or on a physical device. That is a slow process so instead I test it in a browser when possible.
But the browser doesn't have a contacts database so the contact plugin doesn't work.
Is there any way to add mocks (contacts, date pickers, etc.) to the browser for fast testing?
Answer: 1) cordova platform add browser -force
2) cordova serve
3) in the browser:
http://localhost:8000
4) click "browser" link on screen. It will open your app.
Comment: first get into the project directory. and then run these commands. btw. address is .. http://localhost:8000 and it runs like a charm.. :)  simply awesome
Comment: Cordova browser will receive the actual device geolocation, contacts and SIM phone number? How?
Comment: this should be a selected answer. btw. use chrome Developer Tools for further simulations, as mobile view, touches and rotations etc. simply awesome
Answer: you can use http://incubator.apache.org/projects/ripple.html
installation process is simple
npm install -g ripple-emulator

then move to your cordova project directory and run.
cordova prepare

then run the following to start simulator
ripple emulate --path platforms/android/assets/www

you will get something like this

see the detailed explanation about ripple on raymondcamden's blog
Comment: Thanks, I tried it and it was kinda cool. But contacts had not phone numbers and it seems like it is not possible to edit the contacts. Besides that the date-picker plugin didn't work.
Answer: Access your plugins through a service with a clear and precise interface. That way you will be able to provide different implementations of this interface for testing or production.
Take a look at this very basic TypeScript example app. I built an interface for a service that tells you if your device is online. My implementation for "production" looks like this. For testing I could provide another implementation not depending on the cordova-network-plugin, but for example just returning true or false randomly.
You can transfer this to contacts as well: Build an interface and different implementations, returning the actual contacts (in production) or some (more or less) hardcoded contacts randomly (when testing).
Comment: Thanks, that seems like a lot of work though (I'm not sure). I was hoping for some ready made solution like a Chrome extension.
Comment: It is quite a lot, but it's a best practice as it also helps to write units of manageable and testable code. Many frameworks like angular provide support for [services](https://docs.angularjs.org/guide/services) and [unit testing services](https://docs.angularjs.org/guide/services)...
Answer: In my opinion the best option is to use phonegap serve. Ripple is ok but it lacks of native features management.
Some plugins have an implementation for browser, so full api will be available. The ones that doesn't have it, phonegap cli will manage it.
In order to use it, you must first install browser platform:
$ cordova platform add browser
$ phonegap serve

I've been trying to use cordova serve but it doesn't work as phonegap does in my case.
Once phonegap serve is launched, you can debug your app in browser.
UPDATE
From https://github.com/apache/cordova-plugin-contacts/pull/122/files you could implement your own callback responses. This is a very straight forward implementation that you can extend as you need (see create, find, pickContact and contact for implementation details):
var contacts = [];
var mockContacts = require('./mockContacts'); // This is a json mock file with your contacts

function Contact(contact) {
    var field;
    for (field in contact) {
        if (contact.hasOwnProperty(field)) {
            this[field] = contact[field];
        }
    }
}
Contact.prototype.clone = function () {
    // You can implement this methods if needed as well
}
Contact.prototype.remove = function () {
    // You can implement this methods if needed as well
}
Contact.prototype.save = function () {
    // You can implement this methods if needed as well
}

mockContacts.map(function (contact) {
    contacts.push(new Contact(contact));
};

function createContact(contact) {
    var newContact = new Contact(contact);
    contacts.push(newContact);
    return newContact;
}

function findContact(contactFields, contactSuccess, contactError, contactFindOptions) {
    contactSuccess = contactSuccess || function () {};
    contactSuccess(contacts); // You can filter the contacts if needed
    return true;
}

function pickContact(contactSuccess, contactError) {
    contactSuccess = contactSuccess || function () {};
    contactSuccess(contacts[0]);
    return true;
}

module.exports = {
    create: createContact,
    find: findContact,
    pickContact: pickContact
};

Comment: I tried it but it didn't work. I got an error when I tried to access the contacts database.
Comment: You're right, there is still a PR in progress you might follow https://github.com/apache/cordova-plugin-contacts/pull/122, meanwhile maybe you could use the branch from requester or just copy and paste the PR changed files in your local plugin folder
Comment: I'm not quite sure how writing 'Contacts is not supported' in the console will help testing in the browser. Maybe you can elaborate on this... To me it makes more sense to provide an own implementation for testing purposes.
Answer: You can simulate your plugin via Cordova-simulate
(https://cordova.apache.org/howto/2018/02/02/cordova-simulate.html)
This solution is browser based and allows quick tweaking of the more common device properties (geolocation, camera, device, network connection, accelerometer etc).
Can be run via command-line or integrated with VS code's debug. As far as I'm aware, this is an evolution of the Ripple emulator.

Simulate Cordova plugins in browser


Permute the factors of a Kronecker product

Question: Let two matrices $A$ and $B$ of size $m\times n$ and $p \times q$, respectively.
What is the expression of two matrices $F$ and $G$ such that
$A \otimes B = F ( B \otimes A ) G$?
Answer: The matrices $F$ and $G$ are called commutation matrices. A commutation matrix $K_{m,n}$ is the unique permutation matrix that satisfies $K_{m,n} \cdot {\rm vec}\{X\} = {\rm vec}\{X^T\}$ for any $X$ of size $m \times n$, where ${\rm vec}\{\cdot\}$ is the vectorization operator that stacks $X$ into a vector (column by column). These commutation matrices can be used to permute Kronecker products. They satisfy $$K_{m,p}^T \cdot(A \otimes B) \cdot K_{n,q} = B \otimes A,$$ where $A$ and $B$ are $m \times n$ and $p\times q$. Hence, your $F$ is $K_{m,p}$ and your $G$ is $K_{n,q}^T$. You can find a lot more details and properties about these matrices in [MN79, MN95].
[MN95] Magnus, Jan R.; Neudecker, Heinz, Matrix differential calculus with applications in statistics and econometrics,  ZBL07044055, 1995.
[MN79] Magnus, Jan R.; Neudecker, H., The commutation matrix: Some properties and applications, Ann. Stat. 7, 381-394 (1979). ZBL0414.62040.


Acessar uma mesma página em mútiplos "pathname"

Question: Estou criando umas páginas para um site que mostraria o perfil de uma determinada pessoa utilizando um caminho no url (pathname)
Exemplo:

demo.com/page/IagoBruno
demo.com/page/RodriggoDell

Todos esses domínios mostrariam a mesma página (em php) e nessa página seria colocado um código para buscar informações do perfil citado nesse caminho do url, no caso: IagoBruno ou RodriggoDell.
Comment: veja a resposta do Rodrigo, é bem nessa linha. Na verdade quem faz a mágica é o webserver
Comment: O que você pesquisou/tentou até aqui ?
Comment: Eu não sei como pesquisar isso, meio que sou novo em php, mas acho que é assim que redes sociais fazem com os perfis dos usuários: mesmas páginas e conteúdo diferente.
Answer: Use mod_rewrite. Como isso você poderá redirecionar as requisições de:
demo.com/page/IagoBruno para demo.com/page.php?username=IagoBruno
ou:
demo.com/page/RodriggoDell para demo.com/page.php?username=RodriggoDell
Nesse caso em especial, a configuração do mod_rewrite ficaria assim:
RewriteEngine On
RewriteBase /
RewriteRule ^page/([A-Za-z0-9_-]+) /page.php?username=$1 [L]

Obviamente o módulo deverá estar habilitado no Apache.
Comment: Pode ficar tanto na configuração do virtual host quando do .htaccess, desde que o AllowOverride esteja habilitado
Comment: De nada! Não se esqueça de validar a resposta. :)
Comment: Esse código ficaria no arquivo .htaccess?
Comment: Deu certo aqui, obrigado! =)


Is there a way to know how much time is spent in Gurobi usercuts?

Question: I am using JuMP Mathematical Optimization Interface user cuts Callbacks with Gurobi
MOI.set(m, MOI.UserCutCallback(), callback_benders_usercuts)

And I would like to know if there is a way to know how much time is spent in my usercut function callback_benders_usercuts?
usercuts_time = 0
callback_benders_usercuts(arguments)
    usercuts_time += time()
    # ... computing
    usercuts_time += time() - usercuts_time
    return

Doesn't work because, I think, callback_benders_usercuts is called at many nodes and my variable interconnects itself.
I get the following obviously incorrect:
 [ Info: Spent 1.614e9s in User cuts

Answer: You want instead
callback_benders_usercuts(arguments)
    t = time()
    # ... computing
    usercuts_time += time() - t
    return


OutBox pattern - is there a downside to reuse records

Question: I'm reading about OutBox pattern implementations which create records in a table and then a debezium connector read the bin-log to publish those changes to Kafka. This open an issue that after the record was added (and written to the bin log) it just taking storage and the table can get really big. There are several approaches on cleaning the old records like partitions drop by date, create followed by delete or DbTriggers to delete the records)
My suggestion is that, I will create in advance 1,000,000 records in this table and every time will just update one record randomly. The debezium functionality will remain and I will avoid the need to delete old records.
Except of paying a constant storage space for those 1M records. Is there other reason to avoid such approach?
Answer: You can delete the record right away, Debezium will just capture the insert of the event and ignore the delete. That way, your outbox table will always appear empty effectively, but Debezium still gets hold of the events from the binlog. This also is the default behaviour of the Debezium Quarkus extension for implementing the outbox pattern.


choose file from gallery

Question: In my application I want open only gallery application but when I did this
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    startActivityForResult(photoPickerIntent,PICK_FROM_FILE);

It's open dialog and ask me to choose from dialog, like shown in the picture.
I want show only gallery or open gallery directly. Is that possible?
Answer: Try out this one
Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                intent.setType("image/*");
                startActivityForResult(intent, SELECT_GALLERY_IMAGE);
                dialog.dismiss();

Answer: You can give the specific package to your intent. Try with:
// if this not work try with com.android.gallery3d
Intent photoPickerIntent = new Intent("com.android.gallery");
startActivityForResult(photoPickerIntent,PICK_FROM_FILE);

But remember: If the app is not installed on the users phone this will not work so it is very recommendable to use the chooser.
Comment: Try waht works for you. It is the package from the app you want to start
Answer: The following code works perfectly for me.

Intent i = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i,1);

Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_PICK);
                        startActivityForResult(intent, SELECT_PICTURE);

If you want to show the Gallery directly you can use
intent.setType("image/*");
intent.setAction(Intent.ACTION_VIEW);

Comment: This definitely wouldn't work if you have multiple apps installed handling the same intent filter.
Comment: @humblerookie comments absolutely true
Comment: @pmb: while Cilenco's answer solves your purpose , to use an implicit intent with the class of the gallery app some devices may not have the same/ may have custom app to display gallery
Comment: @hublerookie @ wouldn't work if you have multiple apps installed handling the same intent filter :- that's how android works.

choose file from gallery


Using Apache HTTP user in Tomcat?

Question: I need users to authenticate in Apache HTTP for some static resources (using mod_auth_openid. I also have a Tomcat application running. How can I accept the HTTP user as the Tomcat user, so the users don't need to login twice?
Clarification: I don't want to recheck credentials on the Tomcat side, but essentially trust that the user that has been identified by Apache HTTP is correct (whatever way that authentication happened - which is the main point: handing over username/password is **not* an option since there might not be a password, actually most likely there won't).
I want this to work with the Tomcat authentication system, but some pointer how it could work with a home grown authentication wouldn't harm.
Comment: Do you need to ensure that they have the correct credentials in Tomcat, or essentially just 'trust' the user as Apache received and authenticated it?  And do you need for this to work with Tomcat's auth mechanisms, or just with an authentication mechanism that you implement within Tomcat?
Comment: Hi Share Just trust / Tomcat's authentication. Clarified above
Answer: According to http://tomcat.apache.org/tomcat-5.5-doc/config/ajp.html just set the tomcatAuthentication to false to have the authorization propagated from the native webserver and used for authorization in Tomcat.
Comment: That was the missing piece: I need to use the ajp protocol instead of http. Thx

Using Apache HTTP user in Tomcat?


Backgrounds look bad in phones?

Question: My designer created some good looking designs but the problem is that when I apply them on the app I get a weird outcome... Here is the image he designed:

And here it is when I apply it on the phone:

Why are there like waves in the phone background?
Comment: Have a look at this [post](http://stackoverflow.com/q/2928101/593709). Specially last comment at the Romain Guy's answer.
Comment: i am not sure but use px instead of dp
Comment: @AdilSoomro I set the dithering to true but I still have the same thing, how can I override onAttachedToWindow? I keep getting "The method onAttachedToWindow() of type Main must override or implement a supertype method" in my Activity..
Comment: @Omar: which API level are you using. It was available in API 5.
Comment: @AdilSoomro my Project Build Target is 1.6 (API Level 4) .. Does that mean I have to increase the build target to 2.1 to have good backgrounds?
Comment: @Omar: hmmm, Just give it a try
Comment: @AdilSoomro how Do I set the dithering to an Activity?
Answer: Either use gradient in xml or try to increase api level ..
It may work..
Comment: You mean I dinamically create the gradient effect?  I increased the api to target android 2.1 but I still get the same behavior.
Answer: apply draw 9 patch to you image...this might help u.....

Backgrounds look bad in phones?


Como sincronizar o Github com o npm

Question: Existe alguma forma de atualizar o package no npm conforme vou mandando atualizações para a branch master do meu repositório?
Comment: Você pode usar GitHub Actions. Circle CI também é uma opção. Qualquer ferramenta de CI, na verdade... :-)
Answer: O que você precisa é um processo de build automatizdo, ou CI, integração contínua de código, esse processo é responsável por compilação ou transpilação, no caso de javascript, rodar testes e empacotar o artefato em um pacote npm, por exemplo!
Existem várias aplicações de integração contínua (continuous integration) ou build:

Jenkins

CircleCI

Azure DevOps

Github Actions
Se o seu repositório está no Github, usar o Github Action talvez faça mais sentido do que qualquer um outro.

Pode parecer trabalhoso mas com o tempo você irá perceber o valor de ter um pipeline automatizado, vai garantir que você não quebre um pacote por esquecer algo, já que o processo pode te dar algumas garantias; além é claro de a automação poupar um trabalho considerável de toda vez ter que gerar o pacote e fazer upload.

Como sincronizar o Github com o npm


Problems with indices and chain rule

Question: Is there way to handle $\sum_i\frac{\partial}{\partial p_j}p_i\ln p_i$ with the Einstein summation convention without getting troubles with indices?
$\frac{\partial}{\partial p_j}p_i\ln p_i=\delta_{ij}\ln p_i+\frac{p_i}{p_i}\delta_{ij}$
Answer: The Einstein summation convention is that any index which is repeated implies a summation over that index. For example
$$\eqalign{
p_i(\log p_i) \:&\equiv\: \sum_i p_i(\log p_i) \\
}$$
Extending the Kronecker delta symbol to three indexes
$$\eqalign{
\def\LR#1{\left(#1\right)}
\def\d{\vec\delta}
\def\o{{\tt1}}
\def\p{\partial}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\gradLR#1#2{\LR{\grad{#1}{#2}}}
\d_{ijk}
 &= \begin{cases}
  1 \quad&{\rm if\;} i=j=k \\
  0 \quad&{\rm otherwise} \\
\end{cases} \\
}$$
allows you to write the elementwise/Hadamard product of vectors using Einstein notation
$$\eqalign{
c = a\odot b \qiq c_j = a_i\,\d_{ijk}\,b_k \\
}$$
If $q$ is the Hadamard inverse of $p,\,$ then it satisfies
$$\eqalign{
\o = p\odot q \qiq \o_j = p_i\,\d_{ijk}\,q_k \\
}$$
and it can be used to write the elementwise derivative of $\log(p)$
in index notation
$$\eqalign{
\p_j(\log p_i) &= \d_{jik}\,q_k \\
}$$
Putting it all together
$$\eqalign{
\p_j\LR{p_i\log(p_i)}
 &= \LR{\p_jp_i}\log(p_i) + p_i \p_j\log(p_i) \\
 &= \delta_{ij}\log(p_i) + p_i \d_{jik}\,q_k \\
 &= \log(p_j) + \o_j \\
}$$
Answer: $\frac{\partial}{\partial p_j}(p_i\ln p_i)=\delta_{ij}(\ln p_i+\frac{p_i}{p_j})=0$ for all $i\neq j$, so we only need to consider the $j$-th term, which is $\ln p_j+1$.
Comment: The result is clear. My problem is that the Einstein summation convention doesn't work here.

Problems with indices and chain rule


SpriteKit collisions not getting detected

Question: Okay, I've been fighting this code for a couple days now. I can't figure out why the collisions aren't being detected.
I'm trying to draw a string along a circle which turns counter-clockwise, and I want a collider circle to orbit the string clockwise.
Here's my code:
class GameScene : SKScene, SKPhysicsContactDelegate {
var circleString:String = "some string to draw in a circle"

private struct ColliderType {
    static let Symbol: UInt32 = 0x1 << 0
    static let OrbitingBall: UInt32 = 0x1 << 1
}

override func didMoveToView(view: SKView) {
    self.physicsWorld.contactDelegate = self
    createSpinningText()
}

func createSpinningText() {
    //circleNode serves as a container node to simplify placing and rotating the symbolNodes
    let circleNode = SKShapeNode(circleOfRadius: self.size.width * 0.40)
    circleNode.position = CGPointMake(self.size.width * 0.5, self.size.height * 0.5)
    circleNode.strokeColor = UIColor.purpleColor()

    self.addChild(circleNode)

    //count elements and calculate rotation per character
    let l = countElements(symbolString)
    let charRotation = -(2.0 * M_PI) / Double(l)

    for x in 0..<l {
        let character = circleString.substringWithRange(Range<String.Index>(start: advance(circleString.startIndex, x), end: advance(circleString.startIndex, x + 1)))

        //charSprite is a container for charNode, to rotate the starting
        //position of each character. (because I can't set a frame or anchorPoint
        //on a SKLabelNode)
        let charSprite = SKSpriteNode(color: UIColor.clearColor(), size: circleNode.frame.size)

        let charNode = SKLabelNode(fontNamed: "Arial")
        charNode.text = character
        charNode.fontSize = 25
        charNode.position = CGPoint(x: 0, y: circleNode.frame.size.width / 2.27)
        charNode.fontColor = UIColor.purpleColor()

        charNode.physicsBody = SKPhysicsBody(rectangleOfSize: charNode.frame.size)
        charNode.physicsBody?.dynamic = false
        charNode.physicsBody?.categoryBitMask = ColliderType.Symbol
        charNode.physicsBody?.contactTestBitMask = ColliderType.OrbitingBall | ColliderType.Symbol
        charNode.physicsBody?.usesPreciseCollisionDetection = true
        charNode.physicsBody?.collisionBitMask = ColliderType.OrbitingBall | ColliderType.Symbol

        let rotate = SKAction.rotateByAngle(CGFloat(Double(x) * charRotation), duration: 0)
        charSprite.runAction(rotate)

        charSprite.addChild(charNode)
        circleNode.addChild(charSprite)
    }

    let turnSlowlyCCW = SKAction.rotateByAngle(1, duration: 20)
    let repeat = SKAction.repeatActionForever(turnSlowlyCCW)

    circleNode.runAction(repeat)

    let orbitingColliderContainer = SKShapeNode(circleOfRadius: self.size.width * 0.35)
    orbitingColliderContainer.strokeColor = UIColor.redColor()

    orbitingColliderContainer.position = CGPointZero
    let xy = CGPoint(x: orbitingColliderContainer.frame.size.width * 0.5, y: orbitingColliderContainer.frame.size.height * 0.25)

    orbitingColliderContainer.physicsBody = SKPhysicsBody(circleOfRadius: 70, center:xy)
    orbitingColliderContainer.physicsBody?.dynamic = false
    orbitingColliderContainer.physicsBody?.contactTestBitMask = ColliderType.Symbol | ColliderType.OrbitingBall
    orbitingColliderContainer.physicsBody?.collisionBitMask = ColliderType.Symbol | ColliderType.OrbitingBall
    orbitingColliderContainer.physicsBody?.categoryBitMask = ColliderType.OrbitingBall
    orbitingColliderContainer.physicsBody?.usesPreciseCollisionDetection = true
    circleNode.addChild(orbitingColliderContainer)

    let turnSlowlyCW = SKAction.rotateByAngle(-2, duration: 20)
    let repeat2 = SKAction.repeatActionForever(turnSlowlyCW)
    orbitingColliderContainer.runAction(repeat2)
}

func didBeginContact(contact: SKPhysicsContact) {
    println("Contact between \(contact.bodyA) and \(contact.bodyB) detected")
}
}

Here's what the app looks like when run (with .showPhysics on):

Everything is placed and moving exactly as intended, but I don't get any didBeginContact calls. So, what am I doing wrong here?
Answer: Got it to work by setting
self.physicsWorld.gravity = CGVectorMake(0, 0)

and...
orbitingColliderContainer.physicsBody?.dynamic = true

And then setting collisionBitMask to 0 for both charNodes and the orbitingColliderContainer.


how to display image after success ajax process

Question: i want to display an qrcode after i've submit data to the DB
and this is my code of submitting :
 $(document).ready(function(){
       $("input#submitmap").click(function() {
            var routedmap =
                {
                 destination :destinationDB,
                 point: addressRoute

                };

            $.ajax({
              type: 'POST',
              url: 'addroutedmap.php',
              data: routedmap,
            success: function(data){

            }
            });
        });

    });

in the success function after submitted, i wanna display image of qrcode, here is the code of the image :

i've tried using  .show .html (+data+ ) and it doesn't work.
is there any idea or suggestion?
Comment: what exactly is in data?  is it that  string?
Answer: Have you tried this:
$('body').append('');

or:
$('#container').html('');

where #container is some DOM element to harbor your image.
or the way I prefer:
$('#container').html(
    $('', {
        src: 'https://chart.googleapis.com/chart?cht=qr&chs=200x200&chl=http%3a%2f%2fwww.facebook.com',
        alt: ''
    })
);

Comment: The image tag ends with `/>` and not ``
Comment: @tgt, if this post was helpful you might consider [marking it as answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) by clicking on the tick next to it.
Answer: $('#div_where_you_will_sho_qr_code').append(data.toString());


Auto Filter a sheet list and delete marked sheets and create new updated sheet from a sample sheet

Question: I am taking a shot at VBA for the first time so hoping someone can help. I have a large model with lots of sheets which are from a template sample worksheet and with  value set to the serial number of the sheet on each one and the name of the worksheet set to  on the master sheet list.
The master sheet list has three columns
Sheet Number--Sheet Name--Delete Flag
1-- Baby_24-- Yes
2-- Baby_36-- No
3-- Baby_48-- No
4-- Baby_60-- Yes
Trying to write a macro that goes through the master sheet list (Columns A through C), filters for Delete Flag "Yes", deletes all the sheets in the filtered dataset.
After it does that then it should go through the same list and recreate the sheets again by copying the  sheet and renaming to  in the master list and updating cell value B$2$ on that sheet to the sheet number in the master list. This is what I have so far.
The code generates a debug error and deletes only the first filtered sheet market "Yes" in the set and never goes to the next sheet.
Sub DeleteSheets()
' Delete Sheets Marked as Yes on SkuGroup Worksheet

    Dim rRange As Range, filRange As Range, Rng As Range
    ' Turn off Alerts
    Application.DisplayAlerts = False
    'Remove any filters
    ActiveSheet.AutoFilterMode = False

    '~~> Set your range
    Set rRange = Sheets("SKU_Groups").Range("A1:C999")

    With rRange
        '~~> Set your criteria and filter
        .AutoFilter Field:=3, Criteria1:="=Yes"

        '~~> Filter, offset(to exclude headers)
        Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow

        Debug.Print filRange.Address

        For Each Rng In filRange
            '~~> Your Code
            ActiveCell.Value2 = Range("B" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Value2
            Sheets(ActiveCell.Value2).Delete
            Next
    End With

    'Remove any filters
    ActiveSheet.AutoFilterMode = False

    ' Turn on Alerts
    Application.DisplayAlerts = True

End Sub

Comment: which line throws which error?
Comment: What error and on which line?
Comment: Sheets(ActiveCell.Value2).Delete throws the error (Subscript out of range)
Answer: No need to filter . try this :
Sub DeleteSelectedSheets()
    Dim masterSheetName
    Dim sh As Worksheet
    masterSheetName = "master"
    Sheets(masterSheetName).Select

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Dim rowNum
    rowNum = 1
    Do Until Cells(rowNum, "B").Value = ""
        If Cells(rowNum, "C").Value = "Yes" Then
            For Each sh In Worksheets
                If sh.Name = Cells(rowNum, "B").Value Then
                    sh.Delete
                    Rows(rowNum).Delete Shift:=xlUp
                    rowNum = rowNum - 1
                    Exit For
                End If
            Next
        End If
        rowNum = rowNum + 1
    Loop
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub


Fitting multivariate linear mixed model in R

Question: I'm wondering how to fit multivariate linear mixed model and finding multivariate BLUP in R. I'd appreciate if someone come up with example and R code.
Edit
I wonder how to fit multivariate linear mixed model with lme4. I fitted univariate linear mixed models with the following code:
library(lme4)
lmer.m1 <- lmer(Y1 ~ A*B + (1|Block) + (1|Block:A), data=Data)
summary(lmer.m1)
anova(lmer.m1)

lmer.m2 <- lmer(Y2 ~ A*B + (1|Block) + (1|Block:A), data=Data)
summary(lmer.m2)
anova(lmer.m2)

I'd like to know how to fit multivariate linear mixed model with lme4. The data is below:
Block A B    Y1    Y2
 1 1 1 135.8 121.6
 1 1 2 149.4 142.5
 1 1 3 155.4 145.0
 1 2 1 105.9 106.6
 1 2 2 112.9 119.2
 1 2 3 121.6 126.7
 2 1 1 121.9 133.5
 2 1 2 136.5 146.1
 2 1 3 145.8 154.0
 2 2 1 102.1 116.0
 2 2 2 112.0 121.3
 2 2 3 114.6 137.3
 3 1 1 133.4 132.4
 3 1 2 139.1 141.8
 3 1 3 157.3 156.1
 3 2 1 101.2  89.0
 3 2 2 109.8 104.6
 3 2 3 111.0 107.7
 4 1 1 124.9 133.4
 4 1 2 140.3 147.7
 4 1 3 147.1 157.7
 4 2 1 110.5  99.1
 4 2 2 117.7 100.9
 4 2 3 129.5 116.2

Comment: Unfortunately, your question cannot motivate any decent answer as it stands. You might consider adding information about your design (crossed effects--random or not--vs. nested ones), what you qualify as multivariate (is this on the response variable(s) or the number of predictors), etc.
Comment: I've updated my question.
Answer: Fitting multivariate models with lme4 or nlmeis a bit fiddly, but solutions can be found in this document by Ben Bolker.
Else if you want to stay in a frequentist framework, the mcglm package can handle multivariate models, even with non-normal distributions. A detailed tutorial should be published soon. If you are not familiar with design matrices, designing the matrix of random effects can be a bit tricky though.
In a Bayesian framework, the MCMCglmm package is also very good at modelling multivariate traits incl. non-normal distributions, and handles random effects in a simpler way than mcglm does. Its use for multivariate models is also well described by Ben Bolker. But you first have to make yourself familiar with Markov chain Monte Carlo, as well as with the principles of Bayesian statistics.
So either way, there might be a slow learning curve at the beginning, depending on your familiarity with either methods!
Comment: The links in the document by Ben Bolker are broken, currently you can find those course notes at: http://cran.nexr.com/web/packages/MCMCglmm/vignettes/CourseNotes.pdf on pg. 90
Answer: Try the R package nlme
You can find some examples, theory and further documentation in:
http://cran.r-project.org/doc/contrib/Fox-Companion/appendix-mixed-models.pdf
The nlme package is able to calculate pooled estimates [or the so called BLUP= best linear unbiased predictor].
Once you've downloaded the package, type in R console: help(predict.lme)
For more information, look at page 17 in Fox's paper. There you can find an example on how to pool information across subjects.
Hope this helps :)
Comment: These are univariate BLUP. But I'm looking for multivariate BLUP.


Hidden markov model to detect Stock outs in Hourly sales Time series data

Question: I'm currently dealing with time series data about sales of beverages in a supermarket. I have data for each minute, but I'm aggregating by hour since the dataset is already huge with a daily granularity.
I would like to detect stock outs occurring to a product, where a stock out happens when all the items of a given product where sold and the product is not available until refilled. I was suggested to use a Hidden Markov Model, but having little knowledge about it I don't know how to set up the problem, so I ask for help with references and suggestions of the statistical and mathematical assumptions to use.
My idea would be something like:
$Y_i$ = hourly time series of sales, $i=1,...,n$,
$Y_i \in Z^+$
$Z_i $ = hourly time series of latent states, $i=1,...,n$
$Z_i \in {0,1}$, with $0$ corresponding to no items available/stock out
Basically I would like to infer the latent state given the observable sequence of sales.
I'm currently trying to find it using depmixS4 library in R:
<code>dep2 <- depmix(resp ~ xreg,nstates=2,family=poisson(),ntimes=length(resp))
hmm2 <- fit(dep2)
ba2 <- BIC(hmm2)
summary(hmm2)
</code>
Thank you in advance
Comment: Have you tried the approach I suggested as I believe it answers your question as nobody on the list has taken up the challenge for a bake-off .
Comment: @TommasoGuerrini: I am working on something very similar. If its not an issue could you share a snapshot of your data and code. I am also new to HMM and am not sure how to preprocess the data or implement HMM. Thanks.
Comment: Hi Yuvaraj, look at the code here (http://stats.stackexchange.com/questions/255697/semi-hidden-markov-model-with-parameters-of-the-emission-probabilities-depending?rq=1)

By the way, can I ask you which kind of problem? I am writing my final dissertation and whichever example could help
Comment: @TommasoGuerrini: Thanks, appreciate the help. Mine is inventory stock-out prediction. Much like the problem you have described above, only in my case i have the end-of-day inventory. I also have product flow information like daily inflow & outflow of inventory to and from the factory. Objective is to predict the probability of a stock-out a week or two in the future.
Comment: @Yuvaraj email@example.com write me there and let's chat!
Comment: @IrishStat Actually I'm implementing the hidden markov model, I'll give some more time to others before accepting your answer :)
Comment: I would like to see your results in terms of model adequacy i.e. tests of significance of included structure  ; validation of sufficiency i.e. critical examination of model residuals suggesting that they are free of remaining  structure . You might also share the data (it can be coded to mask the actual ) so as your results AND mine can be compared/criticized and improved.by other readers/practitioners. In this way we all learn even the teachers !
Answer: Build a Transfer Function model for hourly sales that takes into account hourly effects , daily effects, weekly effects, monthly effects, holiday effects , day-of-the-month effects, week-of-the-month effects, month-of-the-year effects , current level and trend effects , holiday effects, long-weekend effects , price effects , promotion effects , weather effects et. al.  while taking into account any ARIMA effects. This will allow you to identify anomalous behavior via Intervention Detection . If the predicted sales are non-zero for any identified Intervention Point in time and the observed sales are zero then you have identified a potential stockout as the observed zero was significantly different from the expected non-zero .
You might want to look at Seasonality in residuals ACF and PACF to review how you might build the 24 hourly models using empirically identified structure and user specified causal variables .
Hidden Markov Models deal with latent or hidden variables. What I proposed was a way of identifying the latent/hidden variables by appropriately layering in data-suggested effects (hourly,daily etc) in sufficient quantity and form without collapsing the solution. To form these (waiting to be discovered variables) takes aggressive heuristics employing a lot of trial and error . So you might conclude that intelligent time series modelling is just one very aggressive Markov Model reaching into the data to form sufficient structure to render a white noise error process.
I am not an expert in HMM but I would be very interested in a bake-off comparing HMM and Transfer Function Modelling for your data if someone else can come forth to provide a HMM solution.
Comment: After finding and studying much literature about supermarket sales forecast (https://www.researchgate.net/profile/Richard_Weber/publication/222568533_Improved_supply_chain_management_based_on_hybrid_demand_forecasts/links/567ab0d808ae19758381054b.pdf?origin=publication_detail)

or (http://www.sciencedirect.com/science/article/pii/S0377221706000737)

I found that:

1. Often the predictions are calculated only for high selling items (50 most selling in first paper, median(sales)>5 for 2nd)

2. Interval forecasts are used instead of too difficult point forecasts
Comment: Furthermore, In my case, the current unavailability of the SKU data and stock rotation levels made me focus on finding the most accurated point forecasts, while this could be unneccessary when I'll receive data about stock-outs and stock levels (so that missing by 10 items my prediction could not be a problem if I have 100 items stored in the supermarket warehouse).

I thought this could be interesting and hope that other users trying to predict supermarket sales will not spend so much time in trying to forecast in a very accurate way


Relationship between RMSE and RSS

Question: I'm working on simple linear regression, and I would like to understand the relationship between RMSE and RSS (residual sum of squares).
In another Stackexchange question, I found some explanations, but they didn't directly explain the answer to my particular question, and definitely not in a way I could understand.
What is the relationship between RMSE and RSS in linear regression?
Comment: RMSE = RSS/sqrt(# of residuals), I presume.
Answer:
The RSS is the sum of the square of the errors (difference between calculation and measurement, or estimated and real values):

$ RSS = \sum{(\hat Y_i-Y_i)^2} $

The MSE is the mean of that sum of the square of the errors:

$ MSE = \frac{1}{n}\sum{(\hat Y_i-Y_i)^2}$

The RMSE is the square root of the MSE:

$ RMSE = \sqrt{MSE} $
A bit of math shows:
$ RMSE = \sqrt{MSE} = \sqrt{\frac{1}{n} \cdot RSS} $
You can check it in the example that you posted:
$ RMSE = \sqrt{\frac{1}{32} \cdot 447.6743} = 3.740297 $
Note that for the mtcars dataset $n=32$.

Also see this question
Comment: @NoName  It was like that when I got here! ¯\_(ツ)_/¯
Comment: Wait wait wait, then why is MSE not called MRS (Mean of Residual Squared)???
Comment: While we're protesting naming conventions, why is RSS not called SSR (sum of square residuals)?!
Comment: @gwelter Because `sum of square residual` and `residual sum of square` mean the same thing. But `mean of squared error` and `mean of squared residual` can mean very different thing as in regression residual is used to estimate error. But to get back to the point I have the same question as @NoName.
Answer: Having the mathematical derivations, you might ask yourself why use one measure over the other to assess the performance of a given model? You could use either, but the advantage of RMSE is that it will come out in more interpretable units. For example, if you were building a model that used house features to predict house prices, RSS would come out in dollars squared and would be a really huge number. RMSE would come out in dollars and its magnitude would make more sense given the range of your house price predictions.

Relationship between RMSE and RSS


Azure table storage - where clause on column that may not exist

Question: I am adding a new column to my azure table. For ex., the table is called 'User' and the new column is called 'ComputationDate'. The 'User' table already exists with rows that do not have this new column 'ComputationDate'. I have a query over it as follows,
var usersDue = from user in Table.Query
                           where user.ComputationDate != <somedate>
                           select user;
I want this query to return all user rows that do not have ComputationDate set to 'somedate' and also user rows that do not have this new 'ComputationDate' column defined.
But the query doesn't return the latter set of users. It only returns rows that have 'ComputationDate' set and where the value is not equal to 'somedate'.
Is there any way to get the results I desire without having to get all users and filter it on the client?
Answer: It looks like you're trying to do a LINQ to SQL query.
This may serve your needs better:
var usersDue = from user in Table.Query
                 where user.ComputationDate != <somedate>
                    || user.ComputationDate == null
                 select user;

Comment: 'null' comparisons don't work with LINQ to SQL - http://stackoverflow.com/questions/4228460/querying-azure-table-storage-for-null-values. Any other ideas?
Comment: @user1198407, I think you meant to say that you cannot use a null comparison on a query to Azure table storage.

I took a look at the link you posted - I would suggest modifying your approach to follow the accepted answer's advice for that post.


Como retornar código de status da requisição Java RestEasy

Question: É bem intuitivo fazer um retorno da API com um objeto ou coisa do tipo, só que gostaria de fazer o retorno de um objeto juntamente com status code da requisição.
@Override
@GET
@Path("/{num}/{cod}")
public Foo getFoo(@PathParam("num") long numFoo, @PathParam("cod") long codFoo) {

    Foo f = new Foo();

    try {
        f = fooDAO.buscarFoo(numFoo, codFoo);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return f;
}

Dessa forma tenho o retorno do objeto, mas como retornar o objeto + o status code http para informar o resultado da requisição?
Answer: Você pode retornar javax.ws.rs.core.Response no seu método:
return Response
        .status(Response.Status.OK)
        .entity(f)
        .build();

Comment: Simples e objetivo. +1