Using reduce in JavaScipt

Here is a simple example of using reduce for adding all values in an array


let add = (...args) => {
    return args.reduce(function(a, b) { return a + b; }, 0);
};
let args = [3, 5, 7];
console.log(add(...args));

Clean, right ?

In regular JS or ES5, you’d do something like:


var total = 0;
var numbers = [3, 5, 7];
for (var i = 0; i < numbers.length; i++) {
    total += numbers[i];
}

You can simplify the above reduce example to


[3, 5, 7].reduce(function (a, b) {return a + b; }, 0);

I’d say reduce makes it simpler and easier. Read more about it here

Breaking changes from Angular 2 beta to final release candidate

If you’re using the Angular 2 beta version and want to upgrade to angular 2 final release candidate, it’s a good idea to be aware of the breaking changes from beta to final release. I followed a few youtube tutorials and struggled with it, so here is what i learnt:

Most of the content that was posted earlier on internet forms and youtube tutorials deals with Angular 2 beta. I waited for quite a while to move to angular 2 so that it matures before adopting it. But even then the relevant study material is old and you can’t really follow it word by word.

 

Module Names

Angular packages have been renamed from angular2 to @angular.

import { Component } from ‘@angular/core’;

 

Components and Directives

In Beta, you had to register a component or directive in directives attribute of the host component:

@Component({
directives: [FirstComponent, SecondComponent]
})
export class MyCoolComponent { }

In the Final Release, directives is removed from component metadata.

You should register all components and directives in AppModule (The main app’s root module) or the module they belong to (on sub level). Like the following:

@NgModule({
declarations: [MyHostComponent, ComponentA, DirectiveA]
})
export class AppModule { }

 

Directives

To access a DOM element, use this.el.nativeElement instead of this.el.

this.renderer.setElementStyle(this.el.nativeElement, ‘width’, ‘200’);

 

ngFor Syntax

With angular’s final release, the syntax for for loop has changed.  You should now be using the let keyword. here is how to upgrade all your for loops to new syntax.

In Beta:

*ngFor=“#course of courses”

In the final version:

*ngFor=“let course of courses”

 

Note: I’d keep this post updated if I find anything else as I continue with my study.

Solution: Angular `ng new` command stuck at ‘Installing packages for tooling via npm’

So I am learning Angular 2 and decided to use Angular CLI this time instead of those seed projects.

BTW, I am following this course to study basics of Angular.

sudo ng new angular-app

And this is what happened

Password:
As a forewarning, we are moving the CLI npm package to "@angular/cli" with the next release,
which will only support Node 6.9 and greater. This package will be officially deprecated
shortly after.

To disable this warning use “ng set –global warnings.packageDeprecation=false”.

installing ng2
create .editorconfig
create README.md
create src/app/app.component.css
create src/app/app.component.html
...
...
...
create karma.conf.js
create package.json
create protractor.conf.js
create tslint.json
Directory is already under version control. Skipping initialization of git.
Installing packages for tooling via npm.

It was stuck at the

Installing packages for tooling via npm

for ages and since I didn’t want to give up using the CLI, here is how I solved it.

$ ng new angular-app --skip-npm

As it was stuck on npm packages install process and using –verbose with the command didn’t help, I used above command to skip installing npm packages and did it manually.

So after above, I used

$ cd angular-app

to get into the directory and then installed npm via

$ npm install

that install script takes care if everything else that CLI does if it all works normally.

Now, since we are using the CLI, here is how to compile and run it

$ ng serve

and it should show something like following when it all works nicely.

** NG Live Development Server is running on http://localhost:4200. **
Hash: a1114768f326f4da3abe
Time: 9472ms
chunk {0} polyfills.bundle.js, polyfills.bundle.map (polyfills) 147 kB {4} [initial] [rendered]
chunk {1} main.bundle.js, main.bundle.map (main) 3.98 kB {3} [initial] [rendered]
chunk {2} styles.bundle.js, styles.bundle.map (styles) 10 kB {4} [initial] [rendered]
chunk {3} vendor.bundle.js, vendor.bundle.map (vendor) 2.62 MB [initial] [rendered]
chunk {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

Heading into the browser, it looked like this

Problem solved!

Simple code highlighter using only CSS

Over the last 10 years, I have learnt that sharing code on websites can be tricky. Just yesterday I was working on a blog post and realized that anything between the <code></code> can look ugly if not styled properly.

For example, after writing some bash code within the post, it looked this ugly:

Now, I just investigated how my CSS looked like. And the CSS to style it was barebones, like this


code,
kbd,
tt,
var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}

Clearly, not acceptable and it looked plain and ugly. I didn’t want to use third party JS based highlighter and wanted to use clean CSS approach. I don’t need complex syntax highlighting and basically didn’t want to mess with simplicity and cleanliness of my site. In short, no time for bullshit. So here is what I did


code,
kbd,
tt,
var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
background: #eee;
color: black;
margin: 20px 0;
display: block;
padding: 20px;
}

Now, that’s more like it and it would simply add some nice greyish background, fix some margins and padding around the code and in a way, highlight it so it’s well separated from the general text. Problem solved! Nice and simple.

My cache wouldn’t clear automatically, so I simply cleaned the browser cache but had already tested with the incognito mode, the best way to test websites while you are developing them for a new customer base or just want to see quick results instead of cleaning the browser cache.  Here is the final result:

This works perfectly on the white background of my site. I am a happy man and all it took was 20 minutes to do that and also write this blog post about it. A quick lesson in usability and user experience 🙂

Restart apache on CentOS

Recently, I had a friend setup a CentOS server for me as I personally have experience setting up and managing lamp on Ubuntu servers but needed a CentOS expert. Anyhow, the way to manage Apache on CentOS is a bit different than how it’s done on Ubuntu or debian based Linux. So I was trying to open my site and it wouldn’t connect. After ssh-ing into my box, I realized apache is not working and I needed to restart. Usually on Ubuntu you’d do

httpd restart

but it doesn’t really work, so after a couple minutes of googling, I found it

apachectl start

And, here is the error I got


Syntax error on line 295 of /etc/httpd/conf/httpd.conf:
DocumentRoot '/var/www/html' is not a directory, or is not readable

Now issue was, I deleted the directory without checking if it’s used by apache as I usually remove the default config of apache using `html` directory for default site config. I know, noob mistake. Anyhow, I created that director again and this time


apachectl start

worked like a charm. But I didn’t give up on the httpd command just yet. So tried it again


# httpd restart
Usage: httpd [-D name] [-d directory] [-f file]
[-C "directive"] [-c "directive"]
[-k start|restart|graceful|graceful-stop|stop]
[-v] [-V] [-h] [-l] [-L] [-t] [-S]
Options:
-D name : define a name for use in directives
-d directory : specify an alternate initial ServerRoot
-f file : specify an alternate ServerConfigFile
-C "directive" : process directive before reading config files
-c "directive" : process directive after reading config files
-e level : show startup errors of level (see LogLevel)
-E file : log startup errors to file
-v : show version number
-V : show compile settings
-h : list available command line options (this page)
-l : list compiled in modules
-L : list available configuration directives
-t -D DUMP_VHOSTS : show parsed settings (currently only vhost settings)
-S : a synonym for -t -D DUMP_VHOSTS
-t -D DUMP_MODULES : show all loaded modules
-M : a synonym for -t -D DUMP_MODULES
-t : run syntax check for config files

This time I realized I was doing it without the extra params I had to give to httpd command, so here we go:


[-k start|restart|graceful|graceful-stop|stop]

Now I just wanted to try it


# httpd -k stop
# httpd -k restart

So the first one stops it, I checked after and the site won’t load. That means it worked. Then I simply used restart ( I could have used -k start to start as well) to get it up and running.

This time, above command works perfectly. So a little but of learning today. Moral of the story, just try a little harder before googling it.

Hope this helps 🙂

Link to official CentOS page regarding starting and stopping apache. https://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-apache-startstop.html

Copy Javascript object or any variable from console into clipboard

While I was doing some debugging, I badly needed to compare two Javascript objects that I could easily print into console but then was having a hard time remembering all of the differences from one object to the other one. This was a major API change and I couldn’t just get everything off my memory. So I just needed a quick way of copying the JS object into clipboard. With chrome dev tools, I printed both the objects to console with console.log and then used Sublime comparison tool to compare them both and easily note the differences when I needed to.

Problem solved!

Here is how I did that.

 

Chrome Dev Tools – Save console log object into global variable

Right click on the variable or object and then click on “Store as Global Variable”. Since I had two variables that I needed to compare. I saved them both in the same manner.

 

Chrome Dev Tools – Objects after being saved as Global Variables

Now for the final step, I used

[[code]]czoxMjpcImNvcHkodGVtcDEpIFwiO3tbJiomXX0=[[/code]]

and
[[code]]czoxMjpcImNvcHkodGVtcDIpIFwiO3tbJiomXX0=[[/code]]

to get the variables stored in the clipboard and then subsequently coped them into different files to compare. You can use any file comparison tool for the visual difference which helps with quickly noticing what changed and modify whatever code changes are need for new object in the application. In my case, I used, “Compare Side-By-Side” package for Sublime Text. As you can see, I can quickly able to see the differences between the properties of object as we changed the API from V1 to V2.

Side-by-side file comparison & difference tool for ST2/3

Part 01 – Lets start with react – Hello world

Skip to real stuff. 

My mom always says, just do it! Or was it Nike? Anyhow, I plan on actually just doing it. Like this guy!

So I am going to challenge myself everyday. It’s 6:35 AM in the morning and I have been up all night. I just want to reinvent myself in the best possible may. May be I just need some new learning. My day job involves Angular 1 so I am kinda bored and want to learn new skills. So here we go:

I am starting with installing and getting a basic “Hello World” app with react. The idea is to spend 30 minutes everyday and share my experiences with you.

All you need to know for this is a little bit about node and what is npm. That’s all. Then simply go into the terminal and type as follows


npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start

Now after that, you should have a working app which you can open in your browser and have fun looking at it. I’d post more tomorrow. Stay tuned.

Note: This is my personal journey with the react learning and I’d keep posting everyday.

|    

Hello world!

OK, so here is hoping I blog for the next 365 days. Amen to that!

Right now, it feels like in the process of making a real catapult, I’d end up with something like that

catapult

 

Image stolen from: http://www.instructables.com/id/Mini-Siege-Engines/