ngnix virtual hosts

Setting up virtual host in nginx


# create *.conf files locally
# create 2 server blocks. Only one block carries the default_server directive
server {
 listen 80 default_server;
 listen [::]:80 default_server ipv6only=on;
 root /var/www/example.com/public_html;
 index index.html index.htm;
 server_name example.com www.example.com;
 location / {
   try_files $uri $uri/ =404;
 }
}
# notice: The 2nd server block is non-default and it doesn't carry ipv6only directive
server {
 listen 80;
 listen [::]:80;
 root /var/www/foobar.com/public_html;
 index index.html index.htm;
 server_name foobar.com www.foobar.com;
 location / {
   try_files $uri $uri/ =404;
 }
}

# the default server responds if a domain matching fails, or if you directly hit the IP of the server

# copy them to the 'sites-available' remote dir
scp -r /Users/<username>/<path-to-dir>/foozbar.com.nginx.conf root@123.456.789.101112:/etc/nginx/sites-available/foozbar.com.nginx.conf
# remove default conf from 'sites-enabled' dir
rm /etc/nginx/sites-enabled/default

# create soft-link of the 'conf' from the '-available' to the '-enabled' dir
ln -s /etc/nginx/sites-available/foozbar.com.nginx.conf /etc/nginx/sites-enabled/

# note: the file extension is not mandatory. It has just been used as a convention

# restart nginx
# a) the signal way
nginx -s reload

# b) the service way
sudo service nginx restart

That’s all folks

Run a little gem: Faker

screen-shot-2016-09-26-at-12-28-50-am

Faker @github is a ruby gem for generating fake data, albeit not guaranteed to be unique every time. It’s for general purposes of fake data generation.

# Instructions
# go to terminal
$ gem install faker

# start the interactive ruby shell
$ irb

# load the gem: Faker
irb(main):011:0> require 'Faker'
true
# returns 'true' if you're loading it for the first time.
irb(main):011:0> require 'Faker'
false
# false, because it's already loaded

# now, time to play around
irb(main):011:0> Faker::Name.name
=> "Brook Reichel"

irb(main):011:0> Faker::Address.city 
=> "West Brigitte"

# need a bitcoin wallet?
irb(main):014:0> Faker::Bitcoin.address
=> "1PfXhC3E64DYkdmYPKGwxziRh3ZzMKgzNn"


Update 1:

On the similar premises there are some other data generators you can have at your disposal

How the memory usage shoots up in a VPS when you create virtual hosts

screen-shot-2016-09-23-at-3-54-01-am

The server was running on port 80 and serving a single domain on the VPS. I `a2ensite`-ed  2 domains  running on different ports. Mind you, the server was rendering nothing beyond static html files containing `hello world` messages.

You can see the server running calmly at 2.5MBs and after creating those domains, the memory rises beyond 12.5MBs.

That’s nearly 6 times.

In the coming weeks I’ll hunt for some data around this to present the full case: memory usage with virtual hosts.

Don’t quit keep playing

My friend sent me an inspirational video of Alan Thrall today and that hit me as intensely as it did 6 years ago while reading about Elmore music. This is an article I compiled for the college magazine Avipsa 6 years ago arranging & gluing stories straight from 2 news letters received from elmore-music. Here it is.

When I started compiling this article, I too became hesitant. But, the title itself is so enchanting that it urged me write more & more. I tried to yolk together fragrances & flavors of several beautiful stories that epitomize this inherent godly message of keeping pace even among hurdles.

When the house lights dimmed and the concert was about to begin, the mother returned to her seat and discovered that her child was missing. Suddenly, the curtains parted and spotlights focused on the impressive Steinway on stage. In horror, the mother saw her little boy sitting at the keyboard, innocently picking out “Twinkle, Twinkle Little Star”. At that moment, the great piano master, Paderewski made his entrance, quickly moved to the piano and whispered in the boy’s ear, “Don’t quit”. “Keep playing”. Then, leaning over, Paderewski reached around to the other side of the child, and he added a running obbligato. Together, the old master and the young novice transformed what could have been a frightening situation into a wonderfully creative experience. The audience was so mesmerized that they couldn’t recall what else the great master played. Only the classic “Twinkle, Twinkle Little Star”.
Perhaps that’s the way it is with God. What we can accomplish on our own is hardly noteworthy. We try our best, but the results aren’t always graceful. However, with the hand of the Master, our life’s work can truly be beautiful. The next time you set out to accomplish great feats, listen carefully. You may hear the voice of the Master, whispering in your ear, “Don’t quit”. “Keep playing”. I met a man who shared this story with me while chatting. In return, he left me eulogizing his story of success… here it is…
A man with bibulous imaginations walks to his rickety old balcony of his rental room & begins to think about great people who made fortunes across the globe. Unable to sleep a wink, he asks himself – If this is him, a graduate working a 9-5 job, earning $9 per hour, who barely affords to pay his rent at the end of the month? Fantasizing the stories how big millionaires like Richard Bronson bought an island or Donald Trump acquired another building, he makes up his mind. He no longer wants to watch the same miserable faces to and from work on that same old train. He turns on his PC, opens his mail box & notices a message from his cousin – she was upset, since she longed to learn guitar, but she could barely afford lessons, she could neither invest money on a tutor nor time. Suddenly he feels himself exhausted. As he turns the switch off, he felt a light bulb that went off in his head. “It’s time for killing the rat on the wheels that goes no where. It’s time for ending up my drudgery”, he makes a wild decision, and “I’ve to start my own business.”

“Most of the times it happens that you want to start your own business, but you just don’t know where to begin. Most of my ideas either cost too much or I simply didn’t have the experience to make it work. As the thought of catching the train the next day dawned on me … I made a decision right there and then that I was going to make a change, starting from now”, he explains it all.
He was really upto something, he was going to start his own online business and show people how to play the guitar on the internet. Now, what principles say, if you can’t overcome a hurdle, just avoid it, ignore it. “Working a full time job” came in the way of his new venture. So what’s next, he quits the job.
“It’s strange, but when you want something badly enough — you’ll find a way to get it … no matter what!…I don’t know why I did that, but I still remember that gut feeling of next week … I have no money to buy groceries! I had a total $0 income.”
He started by writing one guitar lesson per day, no more and no less being consistent at his aim of making a booklet of around fifty pages. Computer algorithms have an excellent saying – “Garbage in, Garbage out”. Unless you put good stuff into your head, you can’t expect good stuff to appear in your hands. Spending lunch hours in the state library studying business books he learnt business, sales, marketing and customer service. He could not hire someone & he would compile his tutorial himself. He figured out a need of $5000 in his start up capital.
“So, I started scanning the local papers. I bought cheap laptops from graduating students and sold them for a profit to the new students. Sometimes I sold up to 5 laptops in one evening and made more profit in one night than an entire week at work.” he said.
By the end of it all … a grand saving of $5,000 in his wallet & 50 pages of guitar tutorial made his head was filled with business, marketing and customer service strategies. “I called my parents begging to stay in their garage for a few weeks till I got my business off the ground. I had just met my girlfriend at that stage, so you can imagine how humiliating that must have been — no job, no money and living in your parent’s garage … what kind of guy is this!…But I swallowed my pride, lived in a single garage with $0 income for a few weeks.”

Men make wonders in their own castle. A wall in the center of the room halved it for a part for his business work and the other for a single bed. That’s all the room there was! It was just the perfect illustration for two halves of your brain in your cranium, one for creative purpose & other for logical decisions.

If your mind can conceive it – you will achieve it – period! There is no substitute to hard work & success comes to those who dare & act. The timid never made fortunes. So he adds, “…During that time … I worked my A** off from dusk till dawn. I learned everything from how to build a web site to writing sales copy to connecting merchant accounts to marketing online and search engine submissions … you name it … I did it!”

 

Wait pal! Times were ain’t no good so far. You never build Rome over a night. Saplings would take time to grow. You just saw the root. If you demand your own fruit, then to taste it you must go for a period of hunger…And remember – this probation period makes no promises, no guarantees.

 

Months went by. But, presto! The first fruit you taste, no matter how big it is…Its flavor will be sweetest among all. “My first sale came in. I almost fell off my chair. It was only $27 but it meant a world to me. It was like a light at the end of the tunnel…”
After some search engine optimization study, his guitar site went to No. 1 in Google Page Rank. Allowing other people to re-sell his product for a commission & implementing an affiliate program he earned a handsome gross total of $5,000 a month. Now, a handy book turned into a media & graphics content rich flashy website that goes live & sends regular newsletters for free to the visitors who willingly sign up for it.

“I thanked my parents for use of their garage and cleared off their mortgage for them before I left. I wiped off all my student loans, bought my first Mercedes Benz straight off the showroom floor and built a brand new dream home for my wife and new baby boy to live in.”
Today they employ staff, contribute to charities, fly overseas every year on vacation and return home to a bigger bank account than when they first left…He is an Australian & he is only 27 years old, but he has rightly played a brand new ball game of life. He misses his colleague who still works at the same job for the same boss for the same weekly paycheck waiting for retirement. “It’s a great life and gets better each day…When you really focus and put your mind to it … great things can happen.”
There so much more out there, so much more to do, so much more to see, so much more to experience and so much more to enjoy. If you are silently saying to yourself … ‘it sounds good, but let’s get real’ … then that’s the precise point where we need to start! Your current mindset!

In conclusion…It’s possible! Don’t Quit…Keep Playing…

DPI specific image loading ( Not srcset )

HTML5 provides you with srcset attribute on img tags to load resolution-, dimension- or dpi- specific images. But techniques for loading higher DPI images existed since the early days of HTML5 + CSS3 announcement.

Mobile web app developers, especially the ones developing for iOS safari, have been using -webkit-device-pixel-ratio in media queries to load up normal images for non-retina and images of higher dimension for retina display, squeezed into the same space by adjusting background-size property.

The same can be achieved for loading images on a standard page

  1. Set the image src to a transparent 1×1 gif , Data URIs preferred (albeit slow, but we’re talking about a workaround remember?)
  2. Set the dimension of the images via css (also attributes, because performance)
  3. Write/Generate some CSS
  4. Set the background image for the img tag

The only barrier in this approach – dynamic images: Ideally people don’t change the master CSS file for changes in banner images.

The easiest workaround for this problem: Dynamically injected inline CSS straight into the markup that contains the image URLs for the banner images.

MySQL Error in 5.7+: only_full_group_by

database_3
Generally found in: v5.7+
Version on my machine: 5.7.14
Key words: only_full_group_by, 
Remedy:
Documentation: 6.1.7 Server SQL Modes

Solution

The issue is generally observed in 5.7+. If your team/ you previously worked with an older version, then it’s advisable to stay consistent with the stack. However, in specific cases where you can’t downgrade the version, this solution may work.

Disable FULL_GROUP_BY Mode temporarily:

You may need to execute this every time you do a fresh war deployment.

# execute the following commands
mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Change MySQL Conf to permanently change SQL mode in MySQL:

First we need to identify the location of the configuration file.

Note: If you’re on Mac, the binary mysql installer (not homebrew) doesn’t create a my.cnf file. You can find sample conf files in the support-files directory located under /usr/local/mysql/support-files.

You can find the cnf file by:

$ which mysqld
# let's say it gives you /usr/sbin/mysqld
$ /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
# It'll give the following output
# Default options are read from the following files in the given order: 
# /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

# The cnf file doesn't appear in the default non-home-brew installation
# The sample file can be found under the following directory

$ which mysqld
# let's say it gives you /usr/sbin/mysqld
# cd .. to 2 levels back to the mysql directory
# Try to locate the 'support-files' directory

$ cat /usr/sbin/support-files/my-default.cnf
# This contains a sample cnf file
# copy the contents and create one file under the user directory

$ touch ~/my.cnf

Make the following changes to the my.cnf file:

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

 

Although not required, restart your MySQL server as a precautionary measure.

Bookmarks: August, 2016

  1. Jake Archibald: Performance benefits of norelopener and the security implications
  2. TCP/TLS: TLS Handshake Mechanism (with diagram)
  3. CDN: CDNs aren’t just for caching
  4. ReactJS: React Perf with description about how the diff-ing algorithm works
  5. PWA: Flipkart: Case study for progressive webapps
  6. PWA Apps: Konga: Cuts its data usage by 72%: Case study and youtube video
  7. Joke: Datatypes in languages
  8. A/B Testing Tips: 19 obvious AB Tests that should be performed
  9. Top A/B Testing Blogs
  10. Optimizely A/B Testing tips
  11. Addy Osmani: Scroll Anchoring and feedback
  12. Jake Archibald: jaffathecake
  13. Coding Conventions/Best Practices
  14. New kids (frameworks) in the block – ELM, RiotJS, Preact
  15. Github Repos worth watching: React Hacker news

webpack sucks, at least for now

2105791

Javascript is an interpreted language and by that I understand that when I hit the F5, I expect zero latency for the new script to appear in local dev environment.

When you take that away by introducing obnoxious compilers like webpack – that first needs to be told how to load, then it compiles, then concats before showing me the output, you’re already the subject of my fury.

The ‘wait time’ for compilation sucks

The reasons why I stayed all these years away from coffee script –

  1. I know how to write ‘good’ javascript and
  2. The compilation time – it sucks.

Let JS remain the interpreted language we all know and love. Don’t put your compiled language genius into it. You’re not welcome here – to the interpreted world.

Debugging is horror

you’ve to trace that line out. Imagine a project consisting of 100 small files with almost similar looking content that you concatenated and now clueless where exactly to hunt and debug.

It’s not uncommon – when you write derived components inherited from parent components, the siblings tend to look similar.

webpack – you’re a clutter builder and clarity killer. And, No. I’m not going to work in large files a.k.a monoliths just to support your existence.

Lack of build blocks

I came from an AngularJS Development environment, where I extensively used yeoman and that allows me to work on an index.html file locally which has references to locally kept css and JS.

That means we don’t have to wait for concat or compile before we hit the F5 or ctrl+r.

Plus, the library files from bower_components stay separate. In webpack, unfortunately, they become part of the compilation step.

Luckily, we’ve wiredep and usemin blocks for our rescue – which simplifies local development and gives great support for production builds.

Learn something from it. Your hotness may look tempting to fools and noobs. I ain’t one. Grow up.

Till then – happy hating.

Remedy

And, I always believe there is no point in complaining, one must find a remedy. Following are some workarounds to reduce frustration:

The little catch with Arrow Functions inside Accessors and Methods

es6-logo

Arrow functions are shorthand notation for function expressions. Although the catch is with the binding of this keyword in the context of accessors

Follow the code snippet below:

'use strict';
var obj = {
  a: 10
};

//Snippet A:
Object.defineProperty(obj, "b", {
  get: () => {
    console.log(this.a, typeof this.a, this);
    return this.a+10; // represents global object 'Window'
  }
});

//Snippet B:
Object.defineProperty(obj, "b", {
  get: function() {
    console.log(this.a, typeof this.a, this);
    return this.a+10; // represents current object 'obj'
  }
});

Though the snippets A & B may appear to be working alike, the only catch is with this binding, in the snippet A, where the arrow functions doesn’t bind the this keyword as expected.

I’m a little puzzled, not sure if it’s a bug or a feature, because MDN mentions:

An arrow function does not create it’s own this context, rather it captures the this value of the enclosing context

 

The binding of lexical this takes place differently in case of Arrow functions.

Examples below:

'use strict';
var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b(); // prints undefined, Window
obj.c(); // prints 10, Object {...}

Common Assumption: this.i should behave like any other function inside. NO.

 

Another example involving call (yanked from MDN):

var obj = { base: 1 };
var f = v => console.log(v + this.base, this);
var g = function ( v ) { console.log(v + this.base, this); };
f.call(obj, 2); // logs NaN, Windows
g.call(obj, 2); // logs 3, Object { base... }  

 

The anomaly in the aforementioned snippet ‘A’ is an ‘expected behavior in ES6’ albeit not anticipated in ES5.

Therefore, it can be safely concluded that arrow functions  can well be used for functions, but they are not ideal candidates for Methods. And, as MDN quotes:

Arrow function expression are best suited for non-method function

 

Bonus: Here is a little mindfuck to play around. Try to guess the output.
(() => ({ foo: () => ({ foo: () => ({ foo: () => ({ foo: () => ({ }) }) }) }) }))();

What? It was easy? Nice. Try the next
(() => () => () => () => () => ({}) )()()()()();

Pacman much?
(() => () => () => () => () => {})()()()()();

Update: Updated the same code as examples in MDN

What is it that you fear about `death`?

While getting drunk with friends on a night atop a water tank, atop a building, a movie-director-friend asks this question ‘Why death is so scary? What’s it that we fear about death?’. The audience, high on drinks, wanted anything but cliché.

We were talking about death in the normalcy, hence, a ‘violent gory gruesome death’ was of course out of the way. The consensus –

The biggest fear we’ve about death is – dying alone, in silence, unnoticed.

Millions die everyday. Nobody cares. I don’t want to be one of those millions who are forgotten. When I die, I want my death to be noticed, I do want that people should feel sad for losing me, they should miss me. I want their attention, I seek their love. I want to live in their memories and I want my story to be told to their children.

..I don’t do this for the money, or the fame, or the glory. I do it because when you write a song, it’s the closest thing to immortality that you are ever going to taste, and when it goes to the public it is magic

Bon Jovi  (Read

Perhaps, it’s our yearning for immortality, that makes death so scary. And, living in people’s memories – is the closest possible alternative.