Insert button in XTemplate Sencha Touch 2

Question: I am using the framwork Sencha Touch 2 and now i have a problem when create a List component because i create a XTemplate for this, but i need insert a button component in each element for the list
        {
            xtype: 'list',
            id: 'list_product',
            emptyText: '
No hay coincidencias
',
            store: 'Product',
            itemTpl: Ext.create('Ext.XTemplate',
                '
{name}
' +
                '[{xtype:"button"}]'//Here i tried insert a button
            ),
            items: [
                {
                    xtype: 'toolbar',
                    docked: 'top',
                    items: [
                        {xtype: 'spacer'},
                        {
                            xtype: 'searchfield',
                            placeHolder: 'Buscar...'
                        },
                        {xtype: 'spacer'}
                    ]
                }
            ]
        }

I read the documentation, but i not see a example or some code help.
Answer: You cannot use itemTpl and XTemplate in that manner. Templates are written as HTML, whereas you are mixing HTML and Javascript in your XTemplate
'
{name}
' + //This is HTML
'[{xtype:"button"}]' //This is Javascript

In order to do what you want, you will need to use dataview and dataitem. For examples of how to use them, consult the Dataview guide and docs
Comment: Using dataview,  i can create a searcher component as in the list component?
Comment: Probably. See how it's done for `list`; `list` is a child class of `dataview`. If you need more details, you should create another question.


Can't assign text to a const in Node

Question: I am trying to assign text from a txt file to a variable in node but it gives an 'undefined' error. What am I doing wrong?
const fs = require('fs');

const floor = 0;

const text = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
})

console.log(text);

Comment: You have already declared `const text`, so you cannot reassign it. I would use fs.readFileSync, and then use the value.
Comment: You probably don't know you are working with callbacks.
Answer: You are trying to assign the same const text twice. What you can do is:
const fs = require('fs');
fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    const text = data.toString();
    console.log(text);
})

Or, as @bhuvnesh pattnaik mentioned, you can do it like this:
let text = ``;
const textRead = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
});
console.log(text); //console output is ''

but be careful with this option, because the callback in readFile doesn't happen right away, and the value might still not be there when you need it.
Comment: But I won't be able to access text outside of the function. If i do a console.log outside of the readfile function, it gives error.
Comment: Yep, that is right. Could you elaborate on how do you want to use it outside?
Comment: If i do a console.log(text) outside of the function, it should be able to output the text.
Comment: The value won't be there right after you call `readFile`, because the assignment happens in the callback.
Comment: Take a look at @Dan Cantir 's suggestion with `readFileSync`. It might be what you're looking for.
Comment: Yeah, the readFIleSync option is better coz I dont get any value with your alternative option.
Answer: First of all, you're working with callbacks, so when you do console.log, the reading operation might not be finished yet.
Another problem is that you're trying to reassign text constant. You can't reassign constants.
I would suggest using fs.readFileSync which will read your file synchronously (Do not do this if you have a big file).
const text = fs.readFileSync('./aaa.txt', 'utf8');

If you have a big file, you would have to work continue your logic inside your callback like this:
fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    const text = data.toString();
    console.log(text);
})

Answer: in your code,
text is const type, so you cannot re-assign a value to it,
Either make text as let or var
OR
use another variable inside to assign the data.toString()
You should do something like below:
let text = ``;
const textRead = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
});

Answer: You should have to use it in async function only.
import fs from 'fs';
const text = await fs.promises.readFile('./aaa.txt');

Can't assign text to a const in Node


Proving Nested Sum and Product Identities

Question: Background
Essentially, I was playing around with some interpolation-related ideas using various sequences to try and derive existing identities. What I came across eventually was the alternating sum of binomial coefficients, which I've somehow derived to be equal to $0$. What I didn't realise was is that I had made a bad assumption, but had, in fact, arrived at the correct result (assuming that this sum was in fact zero).
After I attempted a similar thing as above with prime numbers and getting a nonzero sum, I got thinking, and applied the same methods to a general sequence with only distinct elements, let's say $\{a_n\}$, and arrived at the following two sums:
$$
A_n=\sum_{k=1}^{n}{\prod_{\substack{j=1\\j\neq k}}^{n}{\frac{1}{a_j-a_k}}}
$$
$$
B_n=\sum_{k=1}^{n}{\prod_{\substack{j=1\\j\neq k}}^{n}{\frac{a_j}{a_j-a_k}}}
$$
With the help of Mathematica, I conjectured that for $n\geq 2$, $A_n=0$ and that for $n\geq 1$, $B_n=1$ (since the empty product gives $1$).
Given the nature in which these sums simplify; that is, when combined into a single fraction so to speak, I'm fairly confident these patterns continue for all respective $n$... whatever those patterns might be.
Attempts
One of the most natural things to do in this context was to recognise these sums as being resultant of lagrange interpolation. Unfortunately, all my attempts to do this for both problems resulted in a situation where multiple values of $x$ were needed for the numerator of each fraction to be satisfied as in these sums. It may be possible that there exists a trick, such as multiplying and dividing by something specific, for which this method may be viable, but I haven't found it yet.
Another fairly obvious approach was to attempt induction on these problems. Only, instead, we run into a different problem - how does one even begin to factor $A_{n+1}$ in terms of $A_n$ with extra terms? One might consider separating the $k=n+1$ case for both sum and product; but then we're left with a coefficient we can't get rid of in the summands. An identically difficult method was to try and show that $A_{n+1}-A_{n}=0$, but no such luck again, especially with factoring.
Knowing induction, there's often a trick for which one might go about simplifying the problem, but I have again yet to find such a trick.
In the spirit of doing things by hand, I also attempted to make a common denominator with each of the terms. The problem with this approach is that generally speaking, I don't know of any ways to (in general) expand each factor, and secondly, the expressions ended up nesting yet another product inside. That is, given that the numerator $=0$ implies the expression overall is $0$ (since the denominator is nonzero). For $A_n$, it looked something like this:
$$
\sum_{k=1}^{n}{\prod_{\substack{j=1\\j\neq k}}^{n}{\prod_{\substack{m=1\\m\neq j}}^{n}{(a_m-a_j)}}}
$$
I also returned to how I had derived such sums. No such luck there, unfortunately.
Summary
How would one go about proving or disproving the following identities:
$$
\sum_{k=1}^{n}{\prod_{\substack{j=1\\j\neq k}}^{n}{\frac{1}{a_j-a_k}}}=0,\quad n\geq 2
$$
$$
\sum_{k=1}^{n}{\prod_{\substack{j=1\\j\neq k}}^{n}{\frac{a_j}{a_j-a_k}}}=1,\quad n\geq 1
$$
Or, where might one begin with these problems, seeing as we're dealing with a nested sum and product? Much more importantly, what might be some other techniques worth considering to show, or disprove the above?
(On a sidenote, if relevant, what exactly makes these problems so seemingly difficult?)
Answer: Welcome to MSE!
First, your idea regarding lagrange interpolation is a great one! The key insight is to look at particular coefficients in order to make your life easier.
So, let's let $a_1, \ldots a_n$ be some complex numbers. Then let's find a polynomial interpolating the points
$(a_1, 1), (a_2, 1), \ldots, (a_n, 1)$.
On the one hand, we know that this is the constant $1$ polynomial. On the other, we know it's some horrible linear combination:
$$
1 = \sum_{k=1}^n \prod_{j \neq k} \frac{x - a_j}{a_k - a_j}
$$
But now let's compare the $x^{n-1}$ coefficient of both sides! On the left hand side, we get $0$. On the right hand side, we get $\sum_{k=1}^n \prod_{j \neq k} \frac{1}{a_k - a_j}$.
Similarly, let's compare the $x^0$ coefficients! On the left hand side we get $1$, and on the right hand side we get $\sum_{k=1}^n \prod_{j \neq k} \frac{-a_j}{a_k - a_j} = \sum_{k=1}^n \prod_{j \neq k} \frac{a_j}{a_j - a_k}$.
To see why these are both true, let's separate the numerators and denominators of our polynomial:
$$
1 =
\sum_{k=1}^n
\left (
\prod_{j \neq k} \left ( \frac{1}{a_k - a_j} \right )
\prod_{j \neq k} \left ( x - a_j \right )
\right )
$$
Now, if we want the $x^{n-1}$ term, we need to get the $x^{n-1}$ term of each product. But imagine foiling out $\prod_{j \neq k} (x - a_j)$. The coefficient of $x^{n-1}$ is $1$. If we do this for each summand, we find
$$
0 x^{n-1} = \sum_{k=1}^n \prod_{j \neq k} \left ( \frac{1}{a_k - a_j} \right ) x^{n-1}
$$
which gives the claim.
Similarly, if we want the constant term, we need to get the constant term of each product. Again, if we imagine foiling out the $\prod_{j \neq k} (x - a_j)$, we find the constant term is exactly $\prod_{j \neq k} (-a_j)$. Doing this to each term of the sum shows
$$
1 =
\sum_{k=1}^n
\left (
\prod_{j \neq k} \left ( \frac{1}{a_k - a_j} \right )
\prod_{j \neq k} (- a_j)
\right )
$$
now if we recombine these products (and juggle some minus signs), we get the desired
$$
1 = \sum_{k=1}^n \prod_{j \neq k} \frac{a_j}{a_j - a_k}.
$$

Now, let's address some of your closing questions.

Where might one begin with these problems?

Exactly where you began! Working out lots of concrete examples, conjecturing something to be true, and then trying to prove it! Your idea to look at lagrange interpolation was an excellent one, and it was only the idea to look at the polynomials one coefficient at a time that you were lacking. I'm sure if you spent another day or two with this problem you would have gotten it.
As a slightly more productive answer, you need to know what's the right level of generality to use when working out "concrete" examples. For instance, it's probably best in this problem to keep the $a_i$ as symbolic constants, rather than considering the special case of, say $a_1 = a_2 = a_3 = 2$. That said, it is fruitful to work with the special cases $n = 1, 2, 3, \ldots, 5$, say. These can all be worked out without too much hassle (especially if you use a computer algebra system, as you mention you did), and can give you some useful information.
In particular, the notion of a normal form is extremely useful, and whenever you're working with two objects that you know are equal, you should try and put them into some kind of normal form and compare the pieces separately. For this problem, that means expanding the lagrange polynomial into its normal form
$c_0 + c_1 x + c_2 x^2 + \ldots + c_{n-1} x^{n-1}$. If you had done this for some small examples, you would have doubtless seen the pattern in the coefficients that later became the proof.

What makes these hard?

In an informal way, problems that involve both addition and multiplication simultaneously are "hard". This "prototheorem" can be made precise in a number of ways (see skolem and presburger arithmetic compared with robinson arithmetic, for instance), but informally it permeates lots of questions. There are lots of open problems whose difficulty lies, in some sense, in trying to see how addition and multiplication interact. This means that problems that blend addition and multiplication are necessarily trickier than problems which only feature one of the two. I'm sure that this is also accurate to your lived experience.
Of course, I'm sure there are some tricks for dealing with these things, but I'm far from an expert, so I don't know any off the top of my head. I tend to tackle these on a fairly ad-hoc basis, and would also love to hear about a more systematic approach!

I hope this helps ^_^
Comment: This is an amazing answer, thank you greatly for the amount of effort and insight you put into it.
Comment: Happy to help ^_^


Simple php framework to support multi-tenancy

Question: I am looking for a PHP based framework which is ready to go  with following features
1. Simple dashboard with login/logout
2. Multiple DB with each db representing a client
Just the basic framework.
3. Simple registration support
Use case:
I download from github and deploy on the server - Assume the server is all configured up with dns and stuff.
I create a user through registration - a new db is created and tenant folder created on the server
I can then access
tenant1.stckoveawesm.com
tenant2.stckoveawesm.com
each connecting to different db. Assume: *.stckoveawesm.com is mapped to the server I am hosting the framework on.
I know there is code igniter, Zend and Symphony that supports the framework. I m looking for a library/framework which is ready to go. A shell code which can just do the trick with min. config.
Answer: I finally managed to get something done using Laravel framework and is hosted on github for folks to help and improve. Any one wants to pitch in and help fork and let me know so I can collaborate.
https://github.com/sseshachala/laravel-multi-tenant


GH Pages + Jekyll: Images in subfolders?

Question: Is there any reason that images inside a subfolder wouldn't be available via GH Pages? I've got Jekyll building out the _site folder, and everything seems to be working fine, but a couple of my images won't show up. The structure:
_site
  /images
    /thumbnails
    /medium
    file.jpg
    file2.jpg
    etc...
The images inside the parent /images folder work just fine. When I try to call the /thumbnails or /medium images I get a 404.
Here is the repo, showing the images in place: https://github.com/clarklab/chowdown/tree/gh-pages/_site/images
Here is an image on GH Pages from the parent folder, working just fine, and here is a thumbnail, giving me a 404.
This isn't the usual "check your paths inside your templates" issue, these are actual images paths returning a 404. Anyone seen this?
Any ideas?
Answer: You are not accessing the content in _site directory. http://chowdown.io/images/broccoli-beer-cheese-soup.jpg refers to the top level images directory and not the images inside _site.
Comment: _site isn't part of the URL structure though. The image you linked worked, which means calling from that directory is correct, no?
Comment: On the gh-pages branch you only need to have the contents of the _site folder committed on top level. All the other content should not be on that branch because they are not what the github page is supposed to be displaying
Answer: Once you push your code to github, github pages generates you site and push the result on a web server. Uploading _site to your repository is useless as it's not used at all when serving http://chowdown.io/.
As I see that you have a plugins, you certainly need to generate you site locally and push the result (content of _site folder) to your repository.
In this case you'll have to store you code in master and the generated files in gh-pages. You also have to add an empty .nojekyll file at the root of your repository (gh-pages) in order to instruct gh-pages not to generate your site, but copy all your files as static files on the web server.
You can find a step by step versioning scheme here https://stackoverflow.com/a/28252200/1548376.
Comment: Aha! That's gotta be it. I was compiling and then commiting to gh-pages, didn't even realize I was supposed to let Github do it for me (put it in gh-pages).


Pressing Super key always shows shortcut keys

Question: When I simply press (not hold) Super I always see the shortcuts list. And after I release the button it stays on my screen. Normally pressing Super leads to Dash opening and to view the shortcuts list I need to hold Super. So to open the Dash I need press Super twice. I have ThinkPad T520i. I tried to disable shortcut list, but it didn't solve the problem.
Comment: Are You sure that Superkey on keyboard isn't somehow stuck when You press it?
Comment: Does it do it with a very quick tap?
Comment: I tried to press it million times in very different ways)) I gues I become like Flash soon)) the problem is not in my slowliness, the problem is somewhere in machine. Btw I have few virtual machines on other computers and everything works perfect there, so I know how it should really work.
Comment: @James see above
Comment: @zuberuber see above
Comment: Artem, just trying to narrow down the problem, not questioning your abilities. Anyway, any custom shortcuts defined under System Settings/Keyboard/Shortcuts?
Comment: @James no custom shortcuts
Comment: The same thing happens when I try to open HUD. When I press it for the first time nothing happens. Only when I press it second time HUD opens.
Comment: One more issue to add. I can't copy/paste in terminal using Ctrl+Shift+C/V. It simply doesn't work, however the shortcuts set by default in terminal.
Comment: @James I've found the solution. Check the problem description update. Thank you for trying to help me)
Comment: @Artem I am glad you found the solution. Can you add it as an answer instead of editing the question? Thanks.
Comment: @Artem Glad to hear you figured it out. You need to accept as the answer the solution you posted. You going through this may help someone else in the future who has the same problem.
Answer:
I finally found out the solution. The problem was I turned ON "Sticky keys" switcher, so I simply turned it OFF and everything works great now.
Artem

For reference, the Sticky Keys option is in the Typing tab of Universal Access in System Settings.


Emberjs - Event when new element is insert in template

Question: I have a function in my controller that refresh my model asynchronously to download images for a gallery.
I need to trigger a function that put my images in columns (3 images per column), but this function is triggered only once when I load the page and of course there is only one image loaded at this time because the event is too fast for the download.
Is there is any event that I could use to call this function every time I have a new images in my loaded ?
Is it possible to detect if the DOM has been updated ?
I am using a {{#each img in gallery}} to display my images.
[edit] My object is like this :
{
    images: [
        0: "url1",
        1: "url2",
        3: "url3"
    ]
}

But when it come to download images, it replace every element of the images array with an object like this :
{
    images: [
        0: {
            key: "key1",
            base64: "base64_1"
        },
        1: {
            key: "key2",
            base64: "base64_2"
        },
    ]
}

Answer: Set up an observer that detects changes in your gallery. In your controller:
galleryChanged: function() {
    // Perform logic here
}.observes('gallery.@each')

That should work for most situations. If you need something a bit more efficient, you can try using the arrayComputed function. It is a bit more complicated though.
Comment: It's kinda working, but only when its begin to load the first image. When the others images are added to the model and displayed on the template, it's not working.. its that observes is observing every time the @each is called ?
Comment: You might want to refine the dependent key so that it updates when it gets the data you want. For example, if your images have a `src` attribute, use `gallery.@each.src` instead. That should update you any time an item is added or removed, or the `src` attribute of an item changes.
Comment: I understand, I should have said that my array of images would be slightly more complicated than that. I have updated the main post for you to see what I'm doing. In images[] there is already all of the url as a single element, but I replace each element by an object with a key and a base64 of the images. How can I trigger the modification of the images array ?
Comment: I would say that _replacing_ the objects in the array is probably a bad idea. I would suggest having objects with empty `key` and `base64` properties, then fill them in. But either way, observing `gallery.@each.key` and `gallery.@each.base64` should still alert you of changes and long as the objects are Ember objects.


Deno - how to implement a 404 page

Question: I have been struggling to implement a 404 page in deno(oak server framework) - if i load any addtress that does not exist, i get just a blank page..

tried:
(page404MiddleWare.ts):
import {Context, exists, send} from "./deps.ts";
export const page404MiddleWare = async (ctx: Context, next: Function) => {
   ctx.response.body = "404 page";
   await next();
}

But that seems like a bad practise.
Answer: I would add a default route for all non existing urls and redirect user there:
router.get("/(.*)", async (context: Context) => {
    context.response.status = 404;
    context.response.body = "404 | Page not Found";
});

and all rest routes:
...
...

router.get(
  "/api/users",
  UserController.fetch,
);

router.get(
  "/api/me",
  UserController.me,
);
...
...

Checkout my Deno REST boilerplate project for more details:
https://github.com/vicky-gonsalves/deno_rest
Comment: Helped me. Keep up the job whilst helping!
Answer: The question's old, but this worked for me:
    const app = new Application();

    // add your middlewares here
    app.use(router.routes());
    app.use(router.allowedMethods());

    // and then redirect to 404, if there wasn't found any route earlier
    app.use((context: Context) => {
        context.response.type = "text/html; charset=utf-8";
        context.response.status = 404;
        context.response.body = "
404, Page not found!
";
    });

Essentially you add a custom middleware, which returns 404 after it goes through your earlier middlewares, without returning any response.
Hope it helps someone! :)
Answer: I've created this middleware. Use it as most first, may be after logger middleware.
    export const errorBody =
      (): Middleware =>
      async ({ request, response }, next) => {
        await next();

        const status = response.status;
        if (
          status >= 400 &&
          request.method === "GET" &&
          response.writable &&
          !response.body
        ) {
          response.type = "text/plain; charset=UTF-8";
          response.body = `HTTP ${status}`;
          response.status = status;
        }
      };

  const app = new Application();

  app.use(loggerMiddleware.logger);
  app.use(errorBody());
  app.use(loggerMiddleware.responseTime);

  app.use(router.routes());
  app.use(router.allowedMethods());

Deno - how to implement a 404 page


An Inequality Involving $\min(x, y)$

Question: The following problem is from Spivak's Calculus (4th ed., pg. 18):

Prove that if:
$|x-x_0| < \min(\frac{\epsilon}{2(|y_0|+1)}, 1)$ and $|y - y_0| < \frac{\epsilon}{2(|x_0|+1)}$ then $|xy-x_0 y_0| <\epsilon$.

What I've done so far is to say that the since the first inequality implies $|x-x_0| < 1$, combining this with the second inequality yields $|(x-x_0)(y-y_0)|<\frac{\epsilon}{2(|x_0|+1)}$, or $|(x-x_0)(y-y_0)|\cdot(|x_0|+1) < \frac{\epsilon}{2}$. We also know from the first inequality in the problem that $|x-x_0|<\frac{\epsilon}{2(|y_0|+1)}$, so $|x-x_0|(|y_0|+1)< \frac{\epsilon}{2}$. Combining yields:
$|(x-x_0)(y-y_0)| \cdot(|x_0|+1) +|x-x_0|(|y_0|+1) < \epsilon$. I've tried manipulating the left hand side to get $|xy-x_0y_0|$ with little success. Does this whole approach to the problem seem ill-conceived? And if so, how can I rectify it? Or should I try a totally different approach? Thanks.
Answer: My approach would have been:
$|xy-x_{0}y_{0}|=|(xy-xy_{0})+(xy_{0}-x_{0}y_{0})|\le|x||y-y_{0}|+|y_{0}||x-x_{0}|$
$<|x|\big(\frac{\epsilon}{2(|x_{0}|+1)}\big)+|y_{0}|\big(\frac{\epsilon}{2(|y_{0}|+1)}\big)=\frac{|x|}{|x_{0}|+1}\frac{\epsilon}{2}+\frac{|y_{0}|}{|y_{0}|+1}\frac{\epsilon}{2}<\frac{|x|}{|x_{0}|+1}\frac{\epsilon}{2}+\frac{\epsilon}{2}$
Then noting that $|x|-|x_{0}|\le|x-x_{0}|<1$ (using that $|x-x_{0}|<1$ since it is bounded by the min of $1$ and $\frac{\epsilon}{2(|x_{0}|+1)}$) so $|x|<|x_{0}|+1$. So the above is bounded by
$<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$
Comment: Yeah, now it's clear to me I should have started out by manipulating $|xy -x_0 * y_0|$ into a more amicable form, instead of trying to manipulate the given inequalities until I got something of the form $|xy - x_0 y_0|$, which is more or less stabbing into the dark.
Comment: Why is there an $\leq$ sign towards the end of your second line, instead of just a $<$?
Comment: I did that because there is already a strict inequality at the beginning of the second line so in the end I will have the strict inequality I desire anyway. But you are correct that it is in fact strict. I will edit it.
Comment: Great, thanks for the answer, this was a very clear solution.
Comment: Your welcome. Hope it helps you understand.
Answer: This is a standard trick to add and subtract a term so that you end up via triangle inequality with two quantities that you have bounds for:
The quantity you want to bound can be written
$|xy - x_0 y_0| = |xy - x_0y + x_0y - x_0 y_0 | \leq |xy - x_0 y| + |x_0y - x_0 y_0|$
to get you started. You will also need to do one more step to get a $y_0$ into the first piece.
Comment: For a geometric interpretation, think about the area added when you go from a rectangle $x_0$ by $y_0$ to a rectangle $x$ by $y$. The L shape added splits into the two pieces above.

An Inequality Involving $\min(x, y)$


Error message for "Invalid Username"

Question: As per "UX guidelines" what should be the error message for a dimmpley Login for having 2 basic fields "Username" & Password.
So if a User Enter a username with "Space or special characters[,/<>{}]", should the message be very general saying "Invalid Username" or "Please enter a valid username"? or should it be more specific by telling them the special charaters they have added are not acceptable for this filed?
Here is what I am doing right now!

Please suggest!
Comment: related: http://ux.stackexchange.com/questions/26173/what-is-best-practice-for-designing-form-error-messages
Answer: If your page clearly states what character are and are not valid when registering, then a generic message such as "Invalid Username" is just fine.
If not, then it would definitely be helpful to show the username guidelines when you give the error. Another option that you have is when the user is actually typing in a username, you could have a tooltip that pops up with the username guidelines (gmail does this). This way you could maintain a minimal design and keep the page aesthetically pleasing, while also giving important and relevant information.
I don't think it's ever necessary to specifically SHOW which characters that the user has used are invalid. That's a lot of extra code for something that doesn't add much value to the experience.
Attached are ways Amazon and GMail handle username error checking
Comment: Do you have the rules for a valid username elsewhere on the page? Like see with google, while you're typing it says "You can use letters numbers, and periods." And on the error screen it says "Please use only letters (a-z), numbers, and periods." Right now I don't see where the rules are to what DOES make a valid username on your screenshot. How am I, a user, supposed to know what is valid and what is not?
Comment: I agree with "If your page clearly states..." — I, too often, run into my email-as-username being rejected for unknown reasons with no explanation. Is it because I used a `+` in my email `firstname.lastname@example.com` or is it because my `.us` domain is not 3 or more characters? Both are bad reasons to reject my completely valid, working, and real email address, but without feedback on what you **think** is wrong, I have little chance to "correct" it. Tell me what part you think is invalid. ``"strange" email addresses are more valid than you think they are ``
Comment: Thanks for sharing the examples... Really appreciate it!!! I have also updated my question with my screenshot... n I think the generic message looks fine... what do you think?
Comment: @AnindyaBasu hits the nail on the head above.  'Valid' and 'Invalid' are ambiguous and potentially scary words.  Just tell the user what needs to go into the box.
Answer: Do as gmail does it.Instead of invalid username that does not answer the query completely, include a custom message in the tooltip asking your users to do as directed in case your label field value is somewhat complicated.
Answer: What is a valid user name? Is it a user name that was sent to the user from the application when he or she signed up? if so, you should indicate it instead of a generic "Please enter a valid username."
If the user name is what the user entered when signing up, you should have a link "forgot my user name."
Users are forgetful, and instead of making them try again and again you should make it easier for them to restore that user name and let them start working with your application.
Mailchimp.com is a great example of how to create a proper log-in page.
Comment: OP is specifically asking about **Error message** and how to handle them.  Your answer does not address OP's question.
Answer: I've actually found it a lot easier when websites i don't use frequently tell me "There is no account matching that username" when i give an incorrect username/email address
For example wix.com present a lovely little pop-up that says "This email address doesn't match any account. Double check and try again."

Error message for "Invalid Username"


Highlight.js Vue Plugin systematically ignores language value passed to it

Question: Whether I call the plugin directly from my template section or mount it programmatically while passing to it a language prop value, the language I specify always ends up being ignored by the plugin who instead chooses himself a language.
From template section:
<highlightjs language='javascript' code="var x = 5;" />

From script section (programmatically):
<template>

</template>

Here's how the plugin is imported in my main.js:
import 'highlight.js/styles/github-dark-dimmed.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from '@highlightjs/vue-plugin'
app.use(hljsVuePlugin)

app.mount('#app')

EDIT - updated version:
import 'highlight.js/styles/github-dark-dimmed.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from '@highlightjs/vue-plugin'
import hljs from 'highlight.js/lib/core'
import javascript from 'highlight.js/lib/languages/javascript'
hljs.registerLanguage('javascript', javascript)
app.use(hljsVuePlugin)

app.mount('#app')

Comment: where `mount(HighlightPlugin.component ...` is located? please share the whole script
Comment: @BoussadjraBrahim in a component - I edited my question to add more information.
Comment: I'm not good in this stuff still
`import 'highlight.js/styles/github-dark-dimmed.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from '@highlightjs/vue-plugin'
import hljs from 'highlight.js/lib/core'
import javascript from 'highlight.js/lib/languages/javascript'

hljs.registerLanguage('javascript', javascript)
app.use(hljsVuePlugin)

app.mount('#app')`
Answer: Beside the current highlightjs/vue-plugin issue 49, you have the 2021 highlightjs/vue-plugin issue 8 "language setting is not effective": there might be problems when different versions of Highlight.js are present in the project's dependency tree. A workaround suggested involved manually installing a specific version of Highlight.js (version 10.7.2), which resolved the issue for a user. But there might be compatibility concerns with newer versions of Highlight.js.
The a console.log(hljs.version);.
Make sure you import it explicitly in your main.js or wherever you configure Highlight.js:
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import 'highlight.js/styles/github-dark-dimmed.css';
hljs.registerLanguage('javascript', javascript);

Double-check if there is any code that might be overwriting the language prop or if the plugin has default behavior when it fails to recognize the specified language. That could happen if the language module was not imported.
import Vue from 'vue';
import App from './App.vue';
import 'highlight.js/styles/github-dark-dimmed.css';
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import hljsVuePlugin from '@highlightjs/vue-plugin';

// Register the JavaScript language
hljs.registerLanguage('javascript', javascript);

Vue.use(hljsVuePlugin);

new Vue({
  render: h => h(App),
}).$mount('#app');

It is still not working and there is nothing overwriting the language prop - just me passing value javascript to the language prop when calling the plugin.
I did not have highlight.js installed, only @highlightjs/vue-plugin.
I installed it (package.json: "highlight.js": "^11.9.0"), but it does not make any difference.

Then try and implement a diagnostic script in your Vue project:
import { onMounted } from 'vue';
import hljs from 'highlight.js';

export default {
  setup() {
    onMounted(() => {
      // Debug function to check language availability
      function debugHighlightJs() {
        // List of languages you want to check
        const languagesToCheck = ['javascript', 'python', 'html'];
        languagesToCheck.forEach((lang) => {
          if (hljs.getLanguage(lang)) {
            console.log(`Language loaded: ${lang}`);
          } else {
            console.error(`Language not found: ${lang}`);
          }
        });
        // Attempt to highlight a simple code snippet
        const code = 'const x = 5;';
        const result = hljs.highlight(code, { language: 'javascript' });
        console.log(`Highlight result: ${result.value}`);
      }

      // Call the debug function
      debugHighlightJs();
    });
  },
}

That way, you will see the currently used Highlight.js version. And you will check if the specified languages are correctly registered and available.
You can also test with this script if a simple JavaScript code snippet is correctly highlighted.
The goal is to see if the issue lies with language detection or plugin integration.
Comment: Unsure what giving the link to my GH issue was about but it's still not working and there's nothing overwriting the language prop - just me passing value `javascript` to the `language` prop when calling the plugin. I did not have `highlight.js` installed, only `@highlightjs/vue-plugin`. I installed it (`package.json`: `"highlight.js": "^11.9.0",`) but it doesn't make any difference.
Comment: @drake035 I have edited the answer to suggest some diagnostic ideas, to help pinpoint the issue. Let me know what you find.
Comment: Thank you @VonC. Getting `app.mounted is not a function` error, any idea how to work around that?
Comment: @drake035 I suspect `mounted` is a [lifecycle hook in Vue components](https://vuejs.org/guide/essentials/lifecycle), not a method on the Vue application instance created by `createApp`. To run code after the app is mounted, you should place it in the `mounted` hook of a Vue component, or alternatively, use the `app.mount()` method's callback if you need to execute code right after the app has been mounted globally. I have edited the answer to fix the code accordingly.
Comment: Thanks VonC (can't alias you, not sure why??). Getting this result: https://imgur.com/a/j5lLyGF. Or in plain text: `const x = 5;`. In other words, although the languages are correctly loaded, the class for javascript does *not* get applied. Could this plugin be actually faulty?
Comment: @drake035 So the issue is that the plugin is not applying the appropriate CSS classes for syntax highlighting. Is there any error message in the browser developer tools console?
Comment: it's not just the class - depending on the language class assigned to the wrapper `<code>` element, the plugin does all kinds of things differently inside it (wrapping vs not wrapping each DOM node and applying certain one class or another to them). No error in console.
Comment: @drake035 Strange. That could be a bug to report.
Comment: well I created a GH as you know but nobody hast replied yet. Anyway thanks!


How do I change cloud nine back to mr.cuddles?

Question: I went into the stash choose equip on the new cloud nine machine. I want to change it back to mr.cuddles but it doesn't have a unequip button and I can't figure out how to change it to me.cuddles
Answer: You go into the shop, go into the Vehicle Upgrades menu, scroll down to the Mr. Cuddles section and press your desired Mr. Cuddles skin (the normal Mr. Cuddles in your case) afterwards the tab will expand, revealing an "equip" button, press it and you're done.


What are the advantages of using nullptr?

Question: This piece of code conceptually does the same thing for the three pointers (safe pointer initialization):
int* p1 = nullptr;
int* p2 = NULL;
int* p3 = 0;

And so, what are the advantages of assigning pointers nullptr over assigning them the values NULL or 0?
Comment: For one thing, an overloaded function taking `int` and `void *` won't choose the `int` version over the `void *` version when using `nullptr`.
Comment: Well `f(nullptr)` is different from `f(NULL)`. But as far as the above code is concerned(assigning to a local variable), all the three pointers are exactly the same. The only advantage is code readability.
Comment: I am in favor of making this an FAQ, @Prasoon. Thanks!
Comment: NB NULL is historically not guaranteed to be 0, but is as oc C99, in the much the same way a byte wasn't necessarily 8 bits long and true and false were architecture dependant values. This question focuses on `nullptr` butthat's the difference between 0 and `NULL`
Answer: In that code, there doesn't seem to be an advantage. But consider the following overloaded functions:
void f(char const *ptr);
void f(int v);

f(NULL);  //which function will be called?

Which function will be called? Of course, the intention here is to call f(char const *), but in reality f(int) will be called! That is a big problem1, isn't it?
So, the solution to such problems is to use nullptr:
f(nullptr); //first function is called

Of course, that is not the only advantage of nullptr.  Here is another:
template<typename T, T *ptr>
struct something{};                     //primary template

template<>
struct something<nullptr_t, nullptr>{};  //partial specialization for nullptr

Since in template, the type of nullptr is deduced as nullptr_t, so you can write this:
template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!

1. In C++, NULL is defined as #define NULL 0, so it is basically int, that is why f(int) is called.
Comment: Your footnote seems backwards. `NULL` is required by the standard to have an integral type, and that's why it's typically defined as `0` or `0L`. Also I'm not sure I like that `nullptr_t` overload, since it catches *only* calls with `nullptr`, not with a null pointer of a different type, like `(void*)0`. But I can believe it has some uses, even if all it does is save you defining a single-valued place-holder type of your own to mean "none".
Comment: @MarkGarcia, This might be helpful: http://stackoverflow.com/questions/13665349/what-is-a-proper-use-case-of-stdnullptr-t-template-parameters
Comment: @DeadMG: What is incorrect in my answer? that `f(nullptr)` will not call the intended function? There were more than one motivations. Many other useful things can be discovered by the programmers themselves in the coming years. So you cannot say that there is *only one true usage* of `nullptr`.
Comment: As what Mehrdad had stated, these kinds of overloads are pretty rare. Are there other relevant advantages of `nullptr`? (No. I'm not demanding)
Comment: Another advantage (though admittedly minor) may be that `nullptr` has a well-defined numeric value whereas null pointer constants do not. A null pointer constant is converted to the null pointer of that type (whatever that is). It is required that two null pointers of the same type compare identically, and boolean conversion turns a null pointer into `false`. _Nothing else is required._ Therefore, it is possible for a compiler (silly, but possible) to use e.g. `0xabcdef1234` or some other number for the null pointer. On the other hand, `nullptr` is required to convert to numeric zero.
Comment: @DeadMG: Also, the downvoting is silly *even if* my answer doesn't talk about the _real_ motivation. It is like downvoting an answer which talks about C++ template metaprogramming, giving a silly reason that "template was NOT added to do metaprogramming" (yes, it was DISCOVORED).
Comment: @Damon: No, `NULL` cannot be any value other than `0`. It must be zero. Who said *"it's not allowable to compare the pointers like this"*? You can compare pointers.
Comment: The footnote needs correction. In C++ `NULL` has an implementation defined value, with possible definitions which can either `0` or `0L`.
Comment: @Taral: Both will work. `nullptr` can initialize both `nullptr_t` and `nullptr_t*`!!! Why I used `T*`, because I wanted to demonstrate the pointer semantic. See [this](http://ideone.com/XRjtXk) ... and [this](http://ideone.com/zC41dq). I appreciate your comment BTW. :-)
Comment: Well, I honestly don't know what `something` is for ;). Nice.
Comment: Wait. Why would I want to have `something sumThing`?
Comment: @MarkGarcia: One might need `something` especially in template metaprogramming.
Comment: On a second thought, "silly" is not so silly at all. A compiler could use distinct null pointer values for every type (in an address range that will certainly segfault), so a crash handler or debugger could immediately tell the type of a dereferenced null pointer only by looking at the raw address. This would not only be "not silly", but actually quite cool.
Comment: @Damon: Are you implying that `NULL` could have a value other than `0`?
Comment: This is incorrect. The real motivation was the need for forwarding. This trivial case can be solved by a cast.
Comment: @Nawaz: Yes, of course. The standard says that null literals are equivalent to a numeric value of zero (the literals, not the assigned pointers!), and they convert to the null pointer of the respective type. There are additional constraints (see above) but it does not say that the null pointer of a type must have any particular numeric value. In fact, by stating that nullpointers _of equal type_ compare equal, it is explicitly _not_ guaranteed that two null pointers of _different_ types compare equal. So, if `int* a=0; char* b=0; assert(a == b);` fails, that't totally allowable.
Comment: Ok, it's not allowable to compare the pointers like this... but you get the idea. If you cast them to integers so it compiles, the assert may fail.
Comment: @Nawaz: Comparing distinct pointer types the way I did above isn't allowed (not without cast, anyway), therefore that won't compile, but that's irrelevant for what I was saying (adding a cast to `intptr_t` wouldn't have fit into a comment anyway). About `NULL` and `nullptr`, note that they're different things. `NULL` is a macro for `0`, an integer literal which is implicitly converted to a null pointer (not `nullptr`) value. And this certainly **can** be something other than zero. It is not specified what value a null pointer of some type has, so if it's zero, that's just convenience or luck.
Comment: Is this really supposed to be `template struct something {};`, or rather `template ...` (without the `*`)?
Comment: @AlokSave: You mean the given example definitions for `NULL` are `0` and `0L`. It just needs to be a null-pointer constant implicitly convertible to any pointer type. `nullptr` fits the bill.
Answer: C++11 introduces nullptr, it is known as the Null pointer constant and It improves type safety and resolves ambiguous situations unlike the existing implementation dependent null pointer constant NULL. To be able to understand the advantages of nullptr. we first need to understand what is NULL and what are the problems associated with it.

What is NULL exactly?
Pre C++11 NULL was used to represent a pointer that has no value or pointer that does not point to anything valid. Contrary to the popular notion NULL is not a keyword in C++. It is an identifier defined in standard library headers. In short you cannot use NULL without including some standard library headers. Consider the Sample program:
int main()
{
    int *ptr = NULL;
    return 0;
}

Output:
prog.cpp: In function 'int main()':
prog.cpp:3:16: error: 'NULL' was not declared in this scope

The C++ standard defines NULL as an implementation defined macro defined in certain standard library header files.
The origin of NULL is from C and C++ inherited it from C. The C standard defined NULL as 0 or (void *)0. But in C++ there is a subtle difference.
C++ could not accept this specification as it is. Unlike C, C++ is a strongly typed language (C does not require explicit cast from void* to any type, while C++ mandates a explicit cast). This makes the definition of NULL specified by C standard useless in many C++ expressions. For example:
std::string * str = NULL;         //Case 1
void (A::*ptrFunc) () = &A::doSomething;
if (ptrFunc == NULL) {}           //Case 2

If NULL was defined as (void *)0, neither of above expressions would work.

Case 1: Will not compile because a automatic cast is needed from void * to std::string.
Case 2: Will not compile because cast from void * to pointer to member function is needed.

So unlike C, C++ Standard mandated to define NULL as numeric literal 0 or 0L.

So what is the need for another null pointer constant when we have NULL already?
Though the C++ Standards committee came up with a NULL definition which will work for C++, this definition had its own fair share of problems. NULL worked well enough for almost all scenarios but not all. It gave surprising and erroneous results for certain rare scenarios. For example:
#include<iostream>
void doSomething(int)
{
    std::cout<<"In Int version";
}
void doSomething(char *)
{
   std::cout<<"In char* version";
}

int main()
{
    doSomething(NULL);
    return 0;
}

Output:
In Int version

Clearly, the intention seems to be to call the version which takes char* as the argument, but as the output shows the function which takes an int version gets called. This is because NULL is a numeric literal.
Furthermore, since it is implementation-defined whether NULL is 0 or 0L, there can lot of confusion in function overload resolution.
Sample Program:
#include <cstddef>

void doSomething(int);
void doSomething(char *);

int main()
{
  doSomething(static_cast <char *>(0));    // Case 1
  doSomething(0);                          // Case 2
  doSomething(NULL)                        // Case 3
}

Analyzing the above snippet:

Case 1: calls doSomething(char *) as expected.
Case 2: calls doSomething(int) but maybe char* version was be desired because 0 IS also a null pointer.
Case 3: If NULL is defined as 0, calls doSomething(int) when perhaps doSomething(char *) was intended, perhaps resulting in logic error at runtime.   If NULL is defined as 0L, the call is ambiguous and results in compilation error.

So, depending on implementation, the same code can give various outcomes, which is clearly undesired. Naturally, the C++ standards committee wanted to correct this and that is the prime motivation for nullptr.

So what is nullptr and how does it avoid the problems of NULL?
C++11 introduces a new keyword nullptr to serve as null pointer constant. Unlike NULL, its behavior is not implementation-defined. It is not a macro but it has its own type. nullptr has the type std::nullptr_t. C++11 appropriately defines properties for the nullptr to avoid the disadvantages of NULL. To summarize its properties:
Property 1: it has its own type std::nullptr_t, and
Property 2: it is implicitly convertible and comparable to any pointer type or pointer-to-member type, but
Property 3: it is not implicitly convertible or comparable to integral types, except for bool.
Consider the following example:
#include<iostream>
void doSomething(int)
{
    std::cout<<"In Int version";
}
void doSomething(char *)
{
   std::cout<<"In char* version";
}

int main()
{
    char *pc = nullptr;      // Case 1
    int i = nullptr;         // Case 2
    bool flag = nullptr;     // Case 3

    doSomething(nullptr);    // Case 4
    return 0;
}

In the above program,

Case 1: OK - Property 2
Case 2: Not Ok - Property 3
Case 3: OK - Property 3
Case 4: No confusion - Calls char * version, Property 2 & 3

Thus introduction of nullptr avoids all the problems of good old NULL.
How and where should you use nullptr?
The rule of thumb for C++11 is simply start using nullptr whenever you would have otherwise used NULL in the past.

Standard References:

C++11 Standard: C.3.2.4 Macro NULL
C++11 Standard: 18.2 Types
C++11 Standard: 4.10 Pointer conversions
C99 Standard: 220.127.116.11 Pointers
Comment: I'm already practicing your last advice since I've known `nullptr`, though I did not know what difference it really does to my code. Thanks for the great answer and especially for the effort. Brought me a great deal light on the topic.
Comment: "in certain standard library header files." -> why not just write "cstddef" from the beginning?
Comment: Why should we allow nullptr to be convertible to bool type? Could you please elaborate more?
Comment: *...was used to represent a pointer that has no value...* Variables **always** has a value. It may be noise, or `0xccccc....`, but, a value-less variable is an inherent contradiction.
Comment: "Case 3: OK - Property 3" (line `bool flag = nullptr;`). Nope, not OK, I get the following error at compile time with g++ 6: `error: converting to 'bool' from 'std::nullptr_t' requires direct-initialization [-fpermissive]`
Answer: The real motivation here is perfect forwarding.
Consider:
void f(int* p);
template<typename T> void forward(T&& t) {
    f(std::forward<T>(t));
}
int main() {
    forward(0); // FAIL
}

Simply put, 0 is a special value, but values cannot propagate through the system- only types can. Forwarding functions are essential, and 0 can't deal with them. Thus, it was absolutely necessary to introduce nullptr, where the type is what is special, and the type can indeed propagate. In fact, the MSVC team had to introduce nullptr ahead of schedule after they implemented rvalue references and then discovered this pitfall for themselves.
There are a few other corner cases where nullptr can make life easier- but it's not a core case, as a cast can solve these problems. Consider
void f(int);
void f(int*);
int main() { f(0); f(nullptr); }

Calls two separate overloads. In addition, consider
void f(int*);
void f(long*);
int main() { f(0); }

This is ambiguous. But, with nullptr, you can provide
void f(std::nullptr_t)
int main() { f(nullptr); }

Comment: Funny. The half of the answer is same as other two answers which according to you is *"quite incorrect"* answers!!!
Comment: The forwarding problem can also be solved with a cast. `forward((int*)0)` works. Am I missing something?
Answer: Basics of nullptr
std::nullptr_t is the type of the null pointer literal, nullptr. It is a prvalue/rvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type.
The literal 0 is an int, not a pointer. If C++ finds itself looking at 0 in a context where only a pointer can be used, it'll grudgingly interpret 0 as a null pointer, but that's a fallback position. C++'s primary policy is that 0 is an int, not a pointer.
Advantage 1 - Remove ambiguity when overloading on pointer and integral types
In C++98, the primary implication of this was that overloading on pointer and integral types could lead to surprises. Passing 0 or NULL to such overloads never called a pointer overload:
   void fun(int); // two overloads of fun
    void fun(void*);
    fun(0); // calls f(int), not fun(void*)
    fun(NULL); // might not compile, but typically calls fun(int). Never calls fun(void*)

The interesting thing about that call is the contradiction between the apparent meaning of the source code ("I am calling fun with NULL-the null pointer") and its actual meaning ("I am calling fun with some kind of integer— not the null pointer").
nullptr's advantage is that it doesn't have an integral type.
Calling the overloaded function fun with nullptr calls the void* overload (i.e., the pointer overload), because nullptr can't be viewed as anything integral:
fun(nullptr); // calls fun(void*) overload

Using nullptr instead of 0 or NULL thus avoids overload resolution surprises.
Another advantage of nullptr over NULL(0) when using auto for return type
For example, suppose you encounter this in a code base:
auto result = findRecord( /* arguments */ );
if (result == 0) {
....
}

If you don't happen to know (or can't easily find out) what findRecord returns, it may not be clear whether result is a pointer type or an integral type. After all, 0 (what result is tested against) could go either way. If you see the following, on the other hand,
auto result = findRecord( /* arguments */ );
if (result == nullptr) {
...
}

there's no ambiguity: result must be a pointer type.
Advantage 3
#include<iostream>
#include <memory>
#include <thread>
#include <mutex>
using namespace std;
int f1(std::shared_ptr<int> spw) // call these only when
{
  //do something
  return 0;
}
double f2(std::unique_ptr<int> upw) // the appropriate
{
  //do something
  return 0.0;
}
bool f3(int* pw) // mutex is locked
{

return 0;
}

std::mutex f1m, f2m, f3m; // mutexes for f1, f2, and f3
using MuxtexGuard = std::lock_guard<std::mutex>;

void lockAndCallF1()
{
        MuxtexGuard g(f1m); // lock mutex for f1
        auto result = f1(static_cast<int>(0)); // pass 0 as null ptr to f1
        cout<< result<<endl;
}

void lockAndCallF2()
{
        MuxtexGuard g(f2m); // lock mutex for f2
        auto result = f2(static_cast<int>(NULL)); // pass NULL as null ptr to f2
        cout<< result<<endl;
}
void lockAndCallF3()
{
        MuxtexGuard g(f3m); // lock mutex for f2
        auto result = f3(nullptr);// pass nullptr as null ptr to f3
        cout<< result<<endl;
} // unlock mutex
int main()
{
        lockAndCallF1();
        lockAndCallF2();
        lockAndCallF3();
        return 0;
}

Above program compile and executed successfully but lockAndCallF1, lockAndCallF2 & lockAndCallF3 have redundant code. It is pity to write code like this if we can write template for all these lockAndCallF1, lockAndCallF2 & lockAndCallF3. So it can be generalized with template. I have written template function lockAndCall instead of multiple definition lockAndCallF1, lockAndCallF2 & lockAndCallF3 for redundant code.
Code is re-factored as below:
#include<iostream>
#include <memory>
#include <thread>
#include <mutex>
using namespace std;
int f1(std::shared_ptr<int> spw) // call these only when
{
  //do something
  return 0;
}
double f2(std::unique_ptr<int> upw) // the appropriate
{
  //do something
  return 0.0;
}
bool f3(int* pw) // mutex is locked
{

return 0;
}

std::mutex f1m, f2m, f3m; // mutexes for f1, f2, and f3
using MuxtexGuard = std::lock_guard<std::mutex>;

template<typename FuncType, typename MuxType, typename PtrType>
auto lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) -> decltype(func(ptr))
//decltype(auto) lockAndCall(FuncType func, MuxType& mutex, PtrType ptr)
{
        MuxtexGuard g(mutex);
        return func(ptr);
}
int main()
{
        auto result1 = lockAndCall(f1, f1m, 0); //compilation failed
        //do something
        auto result2 = lockAndCall(f2, f2m, NULL); //compilation failed
        //do something
        auto result3 = lockAndCall(f3, f3m, nullptr);
        //do something
        return 0;
}

Detail analysis why compilation failed for lockAndCall(f1, f1m, 0) & lockAndCall(f3, f3m, nullptr) not for lockAndCall(f3, f3m, nullptr)
Why compilation of lockAndCall(f1, f1m, 0) & lockAndCall(f3, f3m, nullptr) failed?
The problem is that when 0 is passed to lockAndCall, template type deduction kicks in to figure out its type. The type of 0 is int, so that's the type of the parameter ptr inside the instantiation of this call to lockAndCall. Unfortunately, this means that in the call to func inside lockAndCall, an int is being passed, and that's not compatible with the std::shared_ptr<int> parameter that f1 expects. The 0 passed in the call to lockAndCall was intended to represent a null pointer, but what actually got passed was int. Trying to pass this int to f1 as a std::shared_ptr<int> is a type error. The call to lockAndCall with 0 fails because inside the template, an int is being passed to a function that requires a std::shared_ptr<int>.
The analysis for the call involving NULL is essentially the same. When NULL is passed to lockAndCall, an integral type is deduced for the parameter ptr, and a type error occurs when ptr—an int or int-like type—is passed to f2, which expects to get a std::unique_ptr<int>.
In contrast, the call involving nullptr has no trouble. When nullptr is passed to lockAndCall, the type for ptr is deduced to be std::nullptr_t. When ptr is passed to f3, there's an implicit conversion from std::nullptr_t to int*, because std::nullptr_t implicitly converts to all pointer types.
It is recommended, Whenever you want to refer to a null pointer, use nullptr, not 0 or NULL.
Answer: There is no direct advantage of having nullptr in the way you have shown the examples.
But consider a situation where you have 2 functions with same name; 1 takes int and another an int*
void foo(int);
void foo(int*);

If you want to call foo(int*) by passing a NULL, then the way is:
foo((int*)0); // note: foo(NULL) means foo(0)

nullptr makes it more easy and intuitive:
foo(nullptr);

Additional link from Bjarne's webpage.
Irrelevant but on C++11 side note:
auto p = 0; // makes auto as int
auto p = nullptr; // makes auto as decltype(nullptr)

Comment: @MarkGarcia, It's an interesting question. cppreference has: `typedef decltype(nullptr) nullptr_t;`. I guess I can look in the standard. Ah, found it: *Note: std::nullptr_t
is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.*
Comment: For reference, `decltype(nullptr)` is `std::nullptr_t`.
Comment: @MarkGarcia, It's a full-blown type as far as I know.
Comment: @DeadMG: There were more than one motivations. Many other useful things can be discovered by the programmers themselves in the coming years. So you cannot say that there is *only one true usage* of `nullptr`.
Comment: @DeadMG: But you said this answer is *"quite incorrect"* simply because it doesn't talk about *"the true motivation"* you talked about in your answer. Not only that this answer (and mine as well) received a downvote from you.
Comment: @DeadMG: That is superlatively dumb. An answer is wrong when it gives you wrong information. But this answer (as well as mine) doesn't give any wrong information.
Comment: @DeadMG: The motivation was obviously NOT one; there were many. (Wait, let me guess : now you're going to say "primary" motivation, right?)
Comment: @chris Is `std::nullptr_t` a typedef, #define or something?
Comment: @chris And so, is it a (real) pointer type? And if it is, what type does it point to? (I'm really curious. Seriously.)
Comment: @chris Oh. They really like to always take things differently then. Still, thank you very much for the effort.
Comment: It's a really good thing you pointed out the deduction of `nullptr`.
Comment: This is quite incorrect. Perfect forwarding was the true motivation.
Comment: I never said there was one true usage. I said there was one motivation, namely, that 0 cannot forward for shit and `nullptr` can.
Comment: Well, since forwarding is the primary motivation, then any answer not discussing it is quite incorrect.
Comment: It suggests that the motivation for nullptr was something other than perfect forwarding, which it was not.
Answer: Just as others have already said, its primary advantage lies in overloads. And while explicit int vs. pointer overloads can be rare, consider standard library functions like std::fill (which has bitten me more than once in C++03):
MyClass *arr[4];
std::fill_n(arr, 4, NULL);

Doesn't compile: Cannot convert int to MyClass*.
Answer: IMO more important than those overload issues: in deeply nested template constructs, it's hard not to lose track of the types, and giving explicit signatures is quite an endeavour. So for everything that you use, the more precisely focused to the intended purpose, the better, it will reduce the need for explicit signatures and allows the compiler to produce more insightful error messages when something goes wrong.


Strange recursive folder created on npm installation

Question: something very strange is happening to my system. I'm running Ubuntu 12.04 and I use it for node.js deveopment. Every time I perform an installation either (sudo npm install -g myPackage) a srtange folder is created: [sudo] password for emanuele: cointaining a recursive infinite structure:
[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele: /home/emanuele/[sudo] password for emanuele:

and so on (emanuele is my username, off course).
I didn't know what caused this. I haven't seen anything like that!
Answer: Set the prefix to /usr/local using this:
npm set prefix /usr/local
npm install -g phon

Source:
Installing Phonegap with NPM 1 3 11 creates a password directory path on Mac OS
It worked for me


NSDate from String in Swift

Question: I've got a string (eg. "2014-11-06 16:32:01")
I want to turn this format into an NSDate object.
Here's what I'm doing:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var date = dateFormatter.dateFromString("2014-11-06 16:32:01")!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: date)
var year = myComponents.year
var month = myComponents.month
var day = myComponents.day

year, month, and day are each valued at 9223372036854775807. Am I getting the dateFormat wrong?
Comment: Just copypasted your example and got this: 2014-11-06 14:32:01 +0000
Answer: The date format is correct. But you have to specify all wanted units in the
myCalendar.components(...) call. All other components are set to NSNotFound aka NSIntegerMax,
which is 2^63 - 1 = 9223372036854775807 on the 64-bit architecture.
This should work:
var myComponents = myCalendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date)

Comment: This has given me the units:
year = 4;
month = -140590335715296;
day = -36028797018959872;
Comment: @DaveAlton: That is strange, I had tested the code before posting it. What does `println(date)` show? How did you print year/month/day?
Comment: For some reason println(date) isn't working. I'm getting the values by setting a breakpoint
Comment: Martin I just tested it. it showing correct date  let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        var date = dateFormatter.dateFromString("2014-11-06 16:32:01")!
        var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
        var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: date)

        println(date)
        var year = myComponents.year
        var month = myComponents.month
        var day = myComponents.day
Comment: @DaveAlton: Then you might be a "victim" of the "locale feature" (see http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature). Try adding `dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")` before the string-to-date conversion.
Comment: @DaveAlton: Does `dateFormatter.dateFromString("2014-11-06 16:32:01")` (without the `!`) return `nil`?
Comment: He needs only to deal with the 3 components he is trying to access. You can check how it can be done on my answer.
Comment: @LeonardoSavioDabus: Yes, and my suggested code shows how to fix OP's code to retrieve exactly the 3 components. I have tested that and it worked. – I really don't know why this answer deserves a downvote.
Comment: @DaveAlton: Any progress on this problem?
Comment: Hey, sorry. I gave up and worked on something else for a bit. Then my hard drive crashed a few weeks later. New hard drive and everything works fine now. Odd, eh?
Answer: static func convertStringToNSDate(dateStr: String) -> NSDate
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat =  "yyyy'-'MM'-'dd HH':'mm':'ss '+0000'"
    let date = dateFormatter.dateFromString(dateStr)

    return date!
}

On my code I am using that method in order to convert a string to NSDate. The only thing that you need to do is to change the dateFormat attribute to be the same as the date's format you want to convert.

NSDate from String in Swift


Structuring an e-commerce site for external sellers

Question: My questions require a fair bit of background information, so please bare with me.
We have an e-commerce app that lets users sell their records. To simplify the selling process we populated our database with a large collection of existing records. This allows sellers to search and select a record to sell, choose a price and an condition, and create their listing.
Our business rules represent the items as unique individual units, and the products as profiles in our database associated with items.
This forces the checkout process to be "Product centric" as opposed to "Item centric". In other words, when you search, or visit a product page, you're not looking at the actual item a seller wants to sell. Rather, you'll see the product profile, and along with it with a number of buying options. Each buying option corresponds to a different seller, different price, and a different condition.
Simply put "Here's the product and it's info, and here are the different sellers selling it." Although the sellers remain anonymous.
This leads to some questions:

When looking at a product, how should we prioritise the sellers?

We plan to display a single listing for each item condition (New, Excellent, Good, Record Only), giving the buyer a choice. But how do we choose those items? Based on price or the order they were listed?
Prioritising price means sellers who list first, but at a higher price, may never sell. This approach may also have implications for "promoted items."
Prioritising listing date may cause an item to never sell if the first seller has a very high price.

Our design decisions mean the catalogue index page will list unique products from our database. Only once a product page is visited by buyers will they see different buying options from all the sellers who listed an item. Is this a good approach?

We considered making the catalogue index "item centric." Instead of listing products from our db, we could list actual items listed by sellers. This means users will be able to visit pages associated with unique items, instead of a product profile with a bunch of sellers.
Comment: "Prioritising price means sellers who list first, but at a higher price, may never sell." Isn't this a good thing?
Comment: I think so. But we're reluctant to to commit to an approach without knowing if it stifles transactions.
Answer: You could consider allowing user transaction feedback to order sellers on the listing page, this way the better sellers would float to the top and sellers would be encouraged to make transactions go smoothly and list products with honestly described conditions.
You could also allow customers to order the listings, three ways immediately spring to mind: by price; by condition; and by seller rating (assuming you implement the above).
On the second question you will need to consider how the listings pages may end up. For example, searching for a popular artist will return many records, even if you just list products. You could list items, but be aware that if 50 people all list the same record you will be expecting users to scroll through a lot of repetitive entries.
Are you aware of http://discogs.com ? They have been working on solving this problem for at least a decade, you may want to have a look at how they do things for inspiration.
Comment: Thank you. Great answer. Unfortunately I can not vote you up since I don't have enough rep. On a side note, interesting suggestion re sellers ratings. We're trying to eliminate that aspect of the process, leaving sellers largely anonymous. But that should not prevent us from using some ratings system. Thanks for the link too.
Comment: @Micky: you could indeed implement the rating system even when your users remain anonymous. Anonymous does not mean unidentifiable and, all else being (almost) equal (condition/price) seller rating is about the only means shoppers have of selecting from whom to buy.
Comment: It's true, ebay users may have names, but they really are anonymous. I know nothing about them and only care that the transaction is carried out professionally.


JS: Hide variable for other scripts

Question: In scriptA I have this code:
var John = 'Doe';

and in scriptB:
alert(John);

But I don't want that the variables between the 2 scripts are shared, how can I hide the John variable for scriptB? Thanks in advance!
Comment: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript
Answer: You can "hide" variables by putting them inside an IIFE (immediately invoked function expression) like this:
(function() {
    // this variable is only accessible within this function block
    var John = "Doe";
})();

// this causes an error because the variable John is not available outside the IIFE
alert(John);

This creates a private function scope which is immediately executed.  This is a common design pattern for declaring variables which have local use, but you don't want broadly shared and you don't want to pollute or conflict with the global namespace.
Comment: Thanks you very much!
Answer: You can use anonymous functions to hide variables:

A similar block can be repeated but variable can have different value in that block:

JS: Hide variable for other scripts


Problem: Knob & Tube + conduit together in ceiling junction box

Question: First post here! We bought this old (1925) house late last year and have been fixing things up. Went to swap out a ceiling fixture in our finished attic bedroom, flipped on the breaker, and despite even the wall switch being "off," my wife screamed that sparks were flying out of the J-box!
I'm not electrician (obviously) but I swear I just replicated how the previous fixture was wired. The box has two old knob & tube wires (one with a black sleeve, one with a tan sleeve), and what looks like conduit with the standard black, white, and green wires. I connected the k&t black/conduit black/fixture black together, the k&t tan/conduit white/fixture white together, and so on.
After realizing what happened, I checked the damage. The conduit black/hot wire apparently snapped in half inside the box. I'm not sure if I damaged it somehow when moving the wires back into the box before putting up the fixture, or if it's possible it snapped from the energy release?
What am I doing wrong? I've put in a call to an electrician to come help us out here, but I'm still curious in the meantime. Pic attached.
Comment: Hello, and welcome to Home Improvement. Not a pro, but "knob and tube" plus sparks => no way could we safely advise you. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know you'll know the details of contributing here.
Comment: Wouldn't be the first time I've seen even modern wire arc through the insulation to the adjacent metal. I pulled a new 30A dryer circuit once and it arced to the strain relief clamp atop the service panel. Gave my wife quite a jump as well. :D Near as I could tell there was no actual problem, just an anomaly. In your case, the insulation may have had a crack or other degradation. Pull new wire if you can.
Answer: I see a few common problem areas.
Wire function
First, there are (were) 4 non-ground wires: black and white from each of conduit and K&T.    The lamp only takes 2 wires. The other 2 wires had been previously connected to each other, and you obviously disturbed that.  If there are 2 controlled fixtures on this switch I may be barking up the wrong tree here. But what usually blindsides novices is thinking wires are color coded for their convenience, and white-white, black-black and done.  Color coding is complete gibberish. (at least until you deal with it long enough to get the hustle and flow of it, and even then, inconsistencies abound).
In most junction boxes, you need information as to what each cable does.  This data is only stored in how the wires are interconnected.  There is no other repository of that knowledge.  The knowledge can be re-generated by a skilled person with test equipment, but the classic novice error is accidentally destroying that information by hastily dismantling stuff.
Nutting
The next thing I see is tape on wire nuts.  That is the hallmark of bad wire-nutting, which will certainly create sparks!  Novices put tape on wire-nuts to cover one of two blunders:

doing the nutting badly, and the wires fall out (or otherwise fail to pass a "pull test").  Iterate on technique. Make sure to crank it down hard enough. It should survive a vigorous pull test (hold the nut and pull each wire in turn).   It is not necessary to pre-twist the wires; the wire nut will do that all by itself very definitely, if you are using proper technique.
stripping the wires too long and leaving exposed wire end beyond the nut end.  If you have excess length, then snip 1/8" or 1/4" or whatever off the very end of the wire.  If not, then use electrical tape to insulate the problematic 1/8" or 1/4" or whatever.

The problem here, though...
I think you actually have two pieces of good news here.  Wires don't just snap off by themselves; this wire suffered extreme stress.  This solid wire failed right at the conduit fitting.  It was yanked, by someone dangling the fixture from the wire, and that nicked the insulation.
Good news #1 is it was the hot wire, which means we got to detect it (if it was neutral, we would've never known; and neutral might be nicked too).
Good news #2 is that the conduit is grounded because this wouldn't have happened otherwise. You will never need a ground wire in that pipe; the conduit is grounded and that means so is the metal box.
An electrician should make short work of this, and hopefully will use modern THHN which has a tough nylon outer jacket which probably would have prevented this, instead of the obsolete THW which does not.
It also looks to me like this Knob&Tube is perfectly fine.  The electrician may try to upsell you into a K&T-ectomy, replacing this K&T switch run or all the K&T in the house "for safety".  Believe me, he'll hit you with the full ooga-booga treatment, "very scary!"  Don't buy it for a minute. What will actually get you better safety is AFCI breakers ($40) on all circuits which have K&T.  AFCI trips on any sort of arcing, which is the failure we worry about with K&T.  But AFCI also trips on every other kind of arcing, so the win goes far beyond K&T.
You can kinda forgive the electrician for being all "replace all the K&T", because that was the only upgrade path until AFCIs came along.  Old habits die hard.
Also, you in particular are allowed to use $20 AFCI receptacles. They only protect the circuit downline (past) the receptacle, so they would have to be in the right place.  If AFCIs were mandatory, they would not be allowed.
So don't waste your money prophylactically changing out K&T wires.  Fit AFCIs instead and call it good.
Comment: @grahamtron The K&T isn't broken, so replacing it would be silly.  The conduit wire is broken, and changing wires in conduit is easy (that's kinda the whole point).  The electrician will use common/bog-standard conduit wire, which is THHN.  Since a) neutral may be damaged and b) it's just as easy to do both wires, you might as well.
Comment: Side comment about knob and tube... I agree with Harper that lots of k+t is in good shape and doesn't have to be touched. However, if your electrician is poking around and seeing k+t that's been abused (stepped on in the attic, had a bunch of 1950s era air splicing, bootleg ground outlets, etc), there are some situations where you want to upgrade your wire. One last thing, depending on your insurance provider, there may be advantages to a total rewire. (And yes, I do get just how daunting that is for an almost 100 year old house... I've done it to my own place.)
Comment: Thanks for the detailed response. When you said the electrician should use modern THHN wire, are you saying that one way forward here is to replace the conduit run from the switch with THHN? Leave the K&T in-place?
Comment: Thanks for the insight!
Answer: Glad you called an electrical. This is not advice on what to do.
As others have noted in other posts, it is a good idea to take a picture of how the fixture was wired before breaking apart the connections.
To answer your question on what might have gone wrong.
This is my guess as to what went wrong.  I am assuming this is a switched ceiling light controlled by a switch.  One of the pair of wires is going to the switch, which means both are hot and the white wire returning from the switch should have been ReID and marked with black tape or other markers.  The Feed black should be connected to the switch black only and not to the light.  The return white from the switch ( is really a black) would connect to the fixture Black.
By connecting black to black and white to white (one of the white is an unmarked black), you short-circuited the wiring.
The switched white, might have been marked with black tape, but you removed the tape to look cleaner not realizing the tape purpose as a marker.
If neither of the set of wires is a switch leg and the switch was on the lighting fixture, then it could have been a cut in the insulation on the black conduit wire.  We can't see the end of the black conduit wire as it is hidden from view by the mounting bar.  I can see a break in the green insulation at the point where it exits the conduit.
On another note, you have a knockout tab protruding into the box which is unsafe. The open knockout is also unsafe.
Comment: Thanks for the detailed answer! You are correct: it's a single switch on the wall controlling this fixture. Normally, I do take a photo of the fixture before dismantling (especially in this house which has a mix of K&T, etc), but for whatever reason I did not here and in my head thought it was straight forward. Shame on me.


Extracting third column in an efficient way using perl

Question: This Perl code gives the output as three.
echo one two three four | perl -pe 's/(\w+)\s(\w+)\s(\w+).*/$3/'

Is there any elegant solution to cut short this lengthy repetitive regular expression?
Answer: Perl has an autosplit command line option (see perlrun, -a)
echo one two three four | perl -lane 'print $F[2]'

EDIT: added -l per Vijay
Comment: you can remove the "\n" by adding -l flag `perl -lane 'print $F[2]'`
Answer: You can use the interval quantify {m,n} to indication repetition:
$ echo one two three four | perl -pe 's/((\w+)\s){2}(\w+).*/$3/'
three

So for the 100th column you do:
$ perl -pe 's/((\w+)\s){99}(\w+).*/$100/'

However I wouldn't suggest you do this as there a much easier ways to print single fields i.e with cut:
$ echo one tow three fout | cut -f3 -d' '
three

Answer: $ cat test
dsadasd dasdsad 3333 4rrff
$ perl -lane 'print $F[2]' test
3333

Answer: Why not use:
cut -f3 -d" "

or
awk '{print $3}'

or
perl -plane 's/.*/$F[2]/'

Comment: I believe -p and -n are mutually exclusive options (-p overrides -n).


Spark SQL failed in Spark Streaming (KafkaStream)

Question: I use Spark SQL in a Spark Streaming Job to search in a Hive table.
Kafka streaming works fine without problems. If I run hiveContext.runSqlHive(sqlQuery); outside directKafkaStream.foreachRDD it works fine without problems. But I need the Hive-Table lookup inside the streaming job. The use of JDBC (jdbc:hive2://) would work, but I want to use the Spark SQL.
The significant places of my source code looks as follows:
// set context
SparkConf sparkConf = new SparkConf().setAppName(appName).set("spark.driver.allowMultipleContexts", "true");
SparkContext sparkSqlContext = new SparkContext(sparkConf);
JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(batchDuration));
HiveContext hiveContext = new HiveContext(sparkSqlContext);

// Initialize Direct Spark Kafka Stream. Starts from top
JavaPairInputDStream<String, String> directKafkaStream =
                KafkaUtils.createDirectStream(streamingContext,
                        String.class,
                        String.class,
                        StringDecoder.class,
                        StringDecoder.class,
                        kafkaParams,
                        topicsSet);

// work on stream
directKafkaStream.foreachRDD((Function<JavaPairRDD<String, String>, Void>) rdd -> {
    rdd.foreachPartition(tuple2Iterator -> {
        // get message
        Tuple2<String, String> item = tuple2Iterator.next();

        // lookup
        String sqlQuery = "SELECT something FROM somewhere";
        Seq<String> resultSequence = hiveContext.runSqlHive(sqlQuery);
        List<String> result = scala.collection.JavaConversions.seqAsJavaList(resultSequence);

        });
    return null;
});

// Start the computation
streamingContext.start();
streamingContext.awaitTermination();

I get no meaningful error, even if I surround with try-catch.
I hope someone can help - Thanks.
//edit:
The solution looks like:
// work on stream
directKafkaStream.foreachRDD((Function<JavaPairRDD<String, String>, Void>) rdd -> {
    // driver
    Map<String, String> lookupMap = getResult(hiveContext); //something with hiveContext.runSqlHive(sqlQuery);
    rdd.foreachPartition(tuple2Iterator -> {
        // worker
        while (tuple2Iterator != null && tuple2Iterator.hasNext()) {
            // get message
            Tuple2<String, String> item = tuple2Iterator.next();
            // lookup
            String result = lookupMap.get(item._2());
        }
    });
    return null;
});

Answer: Just because you want to use Spark SQL it won't make it possible. Spark's rule number one is no nested actions, transformations or distributed data structures.
If you can express your query for example as join you can use push it to one level higher to foreachRDD and this pretty much exhaust your options to use Spark SQL here:
directKafkaStream.foreachRDD(rdd ->
   hiveContext.runSqlHive(sqlQuery)
   rdd.foreachPartition(...)
)

Otherwise direct JDBC connection can be a valid option.
Comment: Direct jdbc connection (without using SQLContext and Dataframes) inside an action is a valid approach. You simply cannot access SQLContext / SparkSession inside an action. Regarding jdbc vs Spark SQL operation for each rdd a lot depends on what exactly is `SELECT something FROM somewhere`. In practice I would benchmark both (considering broadcast joins as well) and simply check which one behaves better in particular scenario.
Comment: Which way is better if you need a table lookup with a specific value from Kafka message to process the message?
Comment: Do you mean join vs query over jdbc?
Comment: I think I misunderstood you. I thought my plan is already a mistake. So that I spark misused.
Comment: Your solution doesn't work for me. I get a lot's of errors it try to run sql query at this position. Some SparkException like `SerializableConfiguration cannot be cast to [B`.
Comment: If you have objects which are not serializable these have to be initialized per executor. This is not specific to this particular case.
Comment: To use the hiveContext at the driver-position is right. It is not possible to use dataframe at this position, because it failed to close. I'm not sure why.


driver=radeon on ubuntu 22.04 with a Radeon R9 390 graphic card

Question: I am running Ubuntu 22.04 and I have an AMD Radeon R9 390 graphic card and an AMD® Ryzen 5 3600x 6-core CPU.
Sometimes my computer simply either freezes or reboots out of nowhere, specially when watching a movie/youtube. When the computer starts again I see in the console an error code 8701013.
Googling it I get several people complaining about the same issue with the same combination of CPU and graphic card.
From the google results it seems to be an issue with the graphic card driver so I decied to  run sudo lshw -c video I get:
*-display
   description: VGA compatible controller
   product: Hawaii PRO [Radeon R9 290/390]
   vendor: Advanced Micro Devices, Inc. [AMD/ATI]
   physical id: 0
   bus info: pci@0000:26:00.0
   logical name: /dev/fb0
   version: 80
   width: 64 bits
   clock: 33MHz
   capabilities: pm pciexpress msi vga_controller bus_master cap_list rom fb
   configuration: depth=32 driver=radeon latency=0 resolution=3440,1440
   resources: irq:98 memory:e0000000-efffffff memory:f0000000-f07fffff ioport:e000(size=256) memory:fce00000-fce3ffff memory:c0000-dffff

It says driver=radeon while I was expecting to see driver=amdgpu.
Googling driver=radeon seems to indicate it is a legacy gpu driver.
How can I install and make sure the latest amdgpu driver is properly installed?
Comment: Googling its release date it gives series 300 (up to 390X) as 2015 so yes, legacy therefore supported by `radeon`.
Answer: https://help.ubuntu.com/community/AMDGPU-Driver
The above link informs which AMD chipsets are supported by amdgpu.
Everything else older than the aforementioned architectures is supported by radeon and that includes the 2015 R9 390.


How to get coordinates from non-GPS GNSS like GLONASS with react-native

Question: I'm using React-Native to create a native application for Android platforms. I want to get the coordinates from Global navigation satellite systems(GNSS) like GPS, GLONASS, Compass, IRNSS, QZSS, Galileo. For GPS I can use react-native geolocation but for others, I don't know what I should do.
Can someone help me?
Comment: Android does not have separate APIs based on the source of the location data. Any React Native plugin would use `LocationManager`, or possibly Play Services' location APIs, and those would use whatever location capabilities are built into the device. For external receivers, you would need to contact the manufacturers of those receivers and ask them what sort of Android integration options they offer.
Comment: Take a look in Fused API and https://github.com/MustansirZia/react-native-fused-location
Comment: @CommonsWare. Thanks for your answer. I searched a lot and found that there is a PRN code which would show me what is satellite system. But I should use java insted of react-native and javascript to create my app. Is there a way to get that PRN code with react-native.
Comment: @Mate .thanks too. I couldn't understand  how Fused API can help me to find the coordinates based on each satellite system seperately.
Comment: Almost three years later, has anyone found out another way?
Answer: I found my answer.
Not only it is not possible on react-native but also it is relate to version of Android that the phone is using.
Acording to this link https://stackoverflow.com/a/41095702/6771718
"With the andvent of Android 7.1, the raw data from GPS chips will be available to developers."
I want to compute coordinate separately. So i need to get raw data from GNSS sensor. For react-native in the time of writing this answer there was no module to get raw data for new Android phones. but it is possible by means of Android native programming with Java.


Lights won't work on dimmer

Question: I just installed some recessed lighting in my basement and I can't get the circuit to work properly.
The installation was: feed to multiple lights to dimmer switch. I used 14/2 for everything except from the last light to the dimmer switch, which I used 14/3. Only the last light dims and the other lights only stay on
Is my issue that I should've used 14/3 for everything or something wrong with the wiring?
Comment: It sounds like maybe you need neutral - and therefore 14/3 - at the dimmer, in which case it maybe should have been 14/3 the whole way. But not very clear. Please provided, if you can: model # of dimmer switch, picture of wiring at last light (14/2 & 14/3), picture of wiring at dimmer switch.
Comment: The switch is Halo LED SAL06P. I have the neutral unconnected since the switch says it doesn't need a neutral with the black wire on top and red wire on bottom of the right hand side. From the switch, it's to the last light in the chain where I have the neutrals together, the grounding together, the red to the light and the black from the incoming 14/2 and 14/3 together like I've seen in some diagrams online. All the other lights are setup so that all the whites are together, blacks are together, and grounding together.
Answer: According to the manual, for a single switch (as opposed to a a 3-way switch, which would require another wire and another (ordinary, non-dimmable) 3-way switch), the configuration is very simple (ignoring grounds, which should all be connected together everywhere):

Top right screw = Black = Hot - this should go directly back to the panel
Bottom right screw = Yellow = Switched Hot - this should go to the light(s)
The "far side" of the lights goes to Neutral

With a single fixture this is straightforward:
14/2 from panel to light at the light:

Connect white (neutral) to one side of the light.
Pass black through to the next cable - it does not connect to the light.

14/2 from light to switch at the light:

Connect black hot to the first cable's black hot
Connect white (="yellow") switched hot to the other side of the light.

14/2 from light to switch at the switch:

Connect black hot to top right (= black according to the instructions)
Connect white switched hot to lower right (= yellow according to the instructions)

Note that yellow is a typical "switched hot" color (could be red or blue or anything else except black, which is traditionally hot, white & gray, which are only neutral, or green, which is only ground). However, 14/2 cable only comes in black/white, so if you have the hot function in the cable then that gets black and switched hot or neutral gets white. Alternatively, if you have neutral function in the cable then that gets white and hot or switched hot gets black. So in this case, you use white as switched hot and then mark it with yellow tape to indicate that it is actually the switched hot.
This conveniently ignores that current code requires a neutral in the switch box, just in case you need it later. But hang on...
That gets one light working. But you have more than one. Now you need another wire. == 14/3.
The problem is you need to have two wires going between all the lights: switched hot and neutral. And you need another wire, not connected to any lights, for hot to get to the switch. With only one light, we cheat a little (except that neutral should be in the switch box) because there is no "carry neutral along to the next light" since there is only one light. But with multiple lights that doesn't work. So now you replace the 14/2 from the first light through all the other lights to the switch with 14/3. That 14/3 will be black/white/red. As described above, whenever possible black = hot and white = neutral. So that leaves red = switched hot. Here we go:
14/2 from panel to light at the light:

Connect white (neutral) to one side of the light.
Pass black through to the next cable - it does not connect to the light.

14/3 from first light to second light, at the first light:

Connect black hot to the previous cable's black hot
Connect white neutral to the previous cable's white neutral and to one side of the light. This actually means use a wire nut to connect the whites from the two cables plus a pigtail to the light.
Connect red switched hot to the other side of the light.

14/3 from first light to second light, at the second light:

Connect black hot to the previous cable's black hot
Connect white neutral to the previous cable's white neutral and to one side of the light. This actually means use a wire nut to connect the whites from the two cables plus a pigtail to the light.
Connect red switched hot to the previous cable's red switched hot and to the other side of the light. This actually means use a wire nut to connect the reds from the two cables plus a pigtail to the light.

All the later lights use that same setup: blacks together, whites together + light, reds together + light.
14/3 from last light to switch at the switch:

Connect black hot to top right (= black according to the instructions)
Connect red switched hot to lower right (= yellow according to the instructions)
Cap the white neutral with a wire nut

Now you have all the lights working and you have neutral in the box in case you need it in the future.
Comment: Thanks for the answer. Looks like I'll be fine tuning my electrical skills rewiring tomorrow
Answer: So here are the wires you need.

ground from supply to every lamp and switch. Ground must be green, green/yellow, or bare.
neutral from supply to every lamp and switch.  Neutral must be white.
always-hot from the power supply to the switch.  Always-hot is preferably black.
switched-hot from the switch to every lamp.  Switched-hot is ideally red, but can be black if the black wire is available.

As you can see, since power enters the opposite end from the switch, you need to carry "always-hot" all the way.  You also need to carry "neutral" all the way.  Then, if you want the lights to be switched, you need to carry switched-hot all the way back from the switch to the first lamp.
The lamp's hot wire is black.  You can hook it to always-hot if you want it always-on, but if you want it switched, I suggest hooking it to switched hot.
So yeah, you need /3 cable starting at the first lamp.
Answer: You need 14/3 between the lights
The reason why the lights are stuck ON is because they were wired directly between always-hot and neutral.  Since you need to bring switched-hot back to all the lights in order for the switch to control them, you'll need to replace the 14/2 between the lights with 14/3.

Lights won’t work on dimmer


Save the exact value of 1/3

Question: How to save the exact value 1/3?
For example in python:
x = float(1/3)
print (f"{x:.50f}")

Result:
0.33333333333333331482961625624739099293947219848633

But I want:
0.333333333333333333333333333333333333333333333333333...

Comment: how many digits of `0.33333...` are you going to print?
Comment: the `decimal` module allows you to get arbitrarily close, but it's never going to be exact.  you might have better luck working algebraically, e.g. via sympy which has support for [rationals](https://docs.sympy.org/latest/modules/core.html#rational)
Comment: It seems that there is a fractions module too that may fit your needs...
Answer: You won't be able to get the exact value. That's because of floating-point imprecision: Your computer has only a limited number of bits to store a float in, and if the number you want cannot be expressed with a finite number of digits in binary, then all you can get is an approximation. The approximation gets better the more bits you have (and floats in Python are 8 bytes, i.e., 64 bits), but it will never be absolutely exact. It's the same reason why you can't express the exact value of 1/3 in decimal.

Save the exact value of 1/3