|
Ishaan Madan Oodles

Ishaan Madan (Manager-Sr. Project Manager- Technology)

Experience:9+ yrs

Ishaan, a skilled technical project manager, excels at breaking down complex projects into manageable tasks. With a background in both technology and project management, he offers a unique perspective to every project he undertakes. His effective communication skills enable him to collaborate seamlessly with both technical and non-technical stakeholders, ensuring everyone is aligned towards shared objectives. He has hands-on experience in utilizing agile methodologies like Scrum and Kanban to drive project management and foster team collaboration. He leverages project management tools such as JIRA, Trello, and Clickup to monitor progress, manage tasks, and facilitate communication among team members and stakeholders. Moreover, his proficiency in full-stack development empowers him to comprehend the technical aspects of projects and provide guidance to developers when necessary. He demonstrates expertise in utilizing popular Python frameworks like Django and Flask, along with data analysis and manipulation libraries such as NumPy and Pandas. On the front-end, Ishaan adeptly employs JavaScript libraries like React and Angular to craft visually appealing and user-friendly interfaces. Additionally, he possesses proficiency in HTML, CSS, and JavaScript for designing responsive and mobile-friendly layouts.

Ishaan Madan Oodles
Ishaan Madan
(Sr. Project Manager- Technology)

Ishaan, a skilled technical project manager, excels at breaking down complex projects into manageable tasks. With a background in both technology and project management, he offers a unique perspective to every project he undertakes. His effective communication skills enable him to collaborate seamlessly with both technical and non-technical stakeholders, ensuring everyone is aligned towards shared objectives. He has hands-on experience in utilizing agile methodologies like Scrum and Kanban to drive project management and foster team collaboration. He leverages project management tools such as JIRA, Trello, and Clickup to monitor progress, manage tasks, and facilitate communication among team members and stakeholders. Moreover, his proficiency in full-stack development empowers him to comprehend the technical aspects of projects and provide guidance to developers when necessary. He demonstrates expertise in utilizing popular Python frameworks like Django and Flask, along with data analysis and manipulation libraries such as NumPy and Pandas. On the front-end, Ishaan adeptly employs JavaScript libraries like React and Angular to craft visually appealing and user-friendly interfaces. Additionally, he possesses proficiency in HTML, CSS, and JavaScript for designing responsive and mobile-friendly layouts.

LanguageLanguages

DotEnglish

Fluent

DotHindi

Fluent

Skills
Skills

DotJavascript

100%

DotPython

80%

DotReactJS

80%

DotDjango

100%

DotFullstack

80%

DotTechnical Project Management

100%

DotHTML, CSS

60%

DotMySQL

60%

DotWordpress

60%

DotReact Native

80%
ExpWork Experience / Trainings / Internship

Jul 2016-Present

Technical Project Manager

Gurgaon


Oodles Technologies

Gurgaon

Jul 2016-Present

Apr 2015-Jul 2016

Wordpress Developer

Gurgaon


Techcraftz Solutions

Gurgaon

Apr 2015-Jul 2016

EducationEducation

2011-2015

Dot

Dronacharya College of Engineering, Farrukhnagar

Bachelor of Technology(Btech)-IT

Top Blog Posts
Reset Migrations in Django

Introduction:

 

In Django, the migration concept was developed with an idea to optmize large number of migrations during the product development. On general basis, its ok to have a large amount of information about migrations in the code base. Though occasionally it may cause some unexpected effects, such as to consume too much of time when tests are run. However, in such cases Django is flexible enough to allow disabling of migrations.

In this blog, you will get to know how to perform a clean-up of migrations, The blog covers two scenarios for the cleanup.

 

Prerequisites:

  • Django
  • SQLite3 / MySQL

 

Steps:

 

Scenario 1:

 

If, the project in in the development phase, it is sometimes feasible to do a fill clean up. This will lead to resetting the complete database.

Step 1. Removing all the migrations files in the project

Remove each and every file in all the migration folders present in the prijeexcept the __init__.pyfile.

In unix like OS, this can be done by using following commands inside the project directory:

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc"  -delete
Step 2. Drop or delete the current database.
Step 3. Creating the initial migrations to generate the schema of database using:
python manage.py makemigrations
python manage.py migrate

And that's it. All done.

 

Scenario 2:

 

If we want to clean up the history of migration without deleting the existing database. 

Step 1. Run Make Migrations using and apply them if some  pending migrations exist
python manage.py makemigrations

 

Step 2. Clearing migration history for all the apps

Run showmigrations command to keep track of existing migrations:

$ python manage.py showmigrations

Result:

admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
app_name
 [X] 0001_initial
 [X] 0002_remove_mymodel_i
 [X] 0003_mymodel_bio
sessions
 [X] 0001_initial

Clear migration history:

$ python manage.py migrate --fake app_name zero

The result should be:

Operations to perform:
  Unapply all migrations: app_name
Running migrations:
  Rendering model states... DONE
  Unapplying app_name.0003_mymodel_bio... FAKED
  Unapplying app_name.0002_remove_mymodel_i... FAKED
  Unapplying app_name.0001_initial... FAKED

Run the show migration command again:

$ python manage.py showmigrations

Result:

admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
app_name
 [ ] 0001_initial
 [ ] 0002_remove_mymodel_i
 [ ] 0003_mymodel_bio
sessions
 [X] 0001_initial

You must do that for all the apps you want to reset the migration history.

3. Removing the  migration files.

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete

find . -path "*/migrations/*.pyc"  -delete

Runing the showmigrations again:

$ python manage.py showmigrations

Result should be:

admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
app_name
 (no migrations)
sessions
 [X] 0001_initial
4. Creating initial migrations
$ python manage.py makemigrations

Result:

Migrations for 'app_name':
  0001_initial.py:
    - Create model MyModel
5. Faking initial migration

In this particular case, since the tables are already present in the DB, one should fake  the migrations using --fake-initial flag:

$ python manage.py migrate --fake-initial

Results:

Operations to perform:
  Apply all migrations: admin, app_name, contenttypes, auth, sessions
Running migrations:
  Rendering model states... DONE
  Applying app_name.0001_initial... FAKED

Running show migrations again to see the output:

admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
app_name
 [X] 0001_initial
sessions
 [X] 0001_initial

All Done.

 

Thanks

Creating a MySQL stored procedure with inputs

Introduction:

 

MySQL is the most popular and an open source relational DBMS capable of working on several platforms. It has features such as multiple user creation and has access to various storage engines, it is backed by Oracle. A major feature of MySQL is that it supports the Stored Procedures which in turn can execute a set of queries/codes and may contain business logic. This blog will show the creation of a stored procedure and its execution.

 

Prerequisites:

  • MySQL server
  • SQL basic queries 

 

Steps:

 

1. Create Tables:

 

CREATE TABLE items(item_id INTitem_description VARCHAR(100));
CREATE TABLE sales(sales_id INT auto_increment KEY,item_id INTsales_date DATETIMEsales_amount DECIMAL(12,2));
INSERT INTO items VALUES (1,'Television');
INSERT INTO items VALUES (2,'Mobile');
INSERT INTO items VALUES (3,'laptop');
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (1,'2014-01-01',1200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (2,'2014-01-02',200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (3,'2014-01-09',1700);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (3,'2014-01-29',1700);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (3,'2014-02-11',1700);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (1,'2014-02-16',1200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (2,'2014-02-16',200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (2,'2014-02-20',200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (2,'2014-02-20',200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (2,'2014-02-22',200);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (3,'2014-02-24',1700);
INSERT INTO sales(item_id,sales_date,sales_amountVALUES (1,'2014-02-24',1200);

 

2. Create a Stored Procedure:

 

DELIMITER $$
CREATE PROCEDURE Test.get_sales
(
param_item_description VARCHAR(100)
)

BEGIN
SELECT 
item_description,SUM(sales_amountAS sales_amount FROM items NATURAL
JOIN sales
WHERE item_description=param_item_description
GROUP BY item_description;
END;
$$
DELIMITER
;

 

Note:  In our example, the beginning of the stored procedure starts by setting a Delimiter '$$'. The delimiter in MySQL statements by default is a semicolon (;). Hence, for instructing the engine of MySQL about start as well as the end of a stored procedure code, we need a different delimiter (in our case $$).

 

 

3. Stored Procedure Execution:

 

The stored procedures can be executed by following command-

CALL get_sales('Television');

 

Upon Execution the result is-

Item_description sales_amount
Television 3600.00

 

Thanks

Using Environment Variables in Google Cloud App Engine for Nodejs

Google App Engine is a web framework that is amongst one of the services provided by the GCP (Google Cloud Platform). Its main purpose is to help in developing as well as hosting the web applications in Google Datacenters. App Engine makes use of a file name "app.yaml" to store and define environment variables for the application.

But, since app.yaml being part of the code needs to be committed to version control systems like GIT, Node.js web developers may tend to avoid storing secret information in the file. To solve this dilemma one a may make the use of google cloud storage. The Blog explains how to use google storage bucket to store environment variables and using them in our application.

 

Pre-requisites:

  • Operating System - Ubuntu.
  • Google Cloud CLI (latest stable version).
  • NPM and Nodejs (latest stable version).
  • Editor (Nano/VS code/Gedit)

 

Implementation:

Step 1:- Storing Information in Google Cloud Storage

Select,  Google Cloud -> Storage -> Browser.

Creating a Storage Bucket. The name of the bucket generally includes:

  • envvars
  • <project name>
  • <domain> include

For Instance, we create an application with a project named as “blogs”, to enlist all the blogs. I would name it envvars.blogs.oodles.com.


In Google Cloud, the bucket names are unique throughout the platform and are not specific to a company or project. However, the names ending with a domain are reserved and ownership of them needs to be verified.

 

Create a .env file and upload it to this bucket. Example:

#.env
MY_API_KEY=xxxx-xxxx-xxxx-xxxx
MY_OTHER_API_KEY=xxxx-xxxx-xxxx

        

 

Step 2:- Import the buket content to process.env

Installing Dependencies

 
npm install --save @google-cloud/storage  dotenv

 

Adding the prestart hook to the file package.json

#package.json
"scripts": {
  "prestart": "node getEnv",
  "start": "node index.js"
}
        

 

 

Create and Adding Script in getEnv.js to Download .env from Bucket:

 use strict;

const fs = require('fs')

const dotEnvExists = fs.existsSync('.env')
if (dotEnvExists) {
  console.log('getEnv.js: .env exists, probably running on development environment')
  process.exit()
}

// On Google Cloud Platform authentication is handled for us
const gcs = require('@google-cloud/storage')()

const bucketName = `envvars.${process.env.GCLOUD_PROJECT}.gunargessner.com`
console.log(`Downloading .env from bucket "${bucketName}"`)
gcs
  .bucket(bucketName)
  .file('.env')
  .download({ destination: '.env' })
  .then(() => {
    console.info('getEnv.js: .env downloaded successfully')
  })
  .catch(e => {
    console.error(`getEnv.js: There was an error: ${JSON.stringify(e, undefined, 2)}`)
  })
        

 

Usage: Using dotenv to load the content from .env into process.env

 use strict'

require('dotenv').config() // Loads .env

// ...

        

 

 

Conclusion:

Using the bucket in google cloud storage service we have hidden the secret information from the version control systems.  

 

Thanks

 

 

How to Construct Custom Bash Commands for GIT

Introduction:

In this blog, we will be learning how to create custom shortcut commands (aliases) in bash. The commands can be configured to execute multiple commands by just a single bash command. This comes really handy when one has to repeatedly do some task which involves multiple commands, for instance: creating builds, pushing code to git, etc

For the sake of comprehensibility, in this blog, we will create a custom command to create a local GIT branch from an updated version of the master.

 

Pre-requisites:

  • Operating System - Ubuntu.
  • GIT (latest stable version).
  • Editor (Nano/VS code/Gedit)

 

Implementation:

The custom commands are generally placed and defined in '.bashrc' file, this is basically a hidden file present in the home directory and thus is accessible from any location in the terminal. However, it is not an ideal practice to define all sort of custom usage commands in system files. For that reason. it is recommended to create a custom file ( ~/.custom_aliases) and place all our aliases in it.
Note: It is necessary to load the aliases using 
source ~/.custom_aliases, else the aliases just won't work.

 

Step 1:- Creating the custom_aliases file.

# create file
touch ~/.custom_aliases

 

Step 2:- Open file custom_aliases.

# opens file
gedit ~/.custom_aliases

 

 

Step 3:- Enter custom function to execute multiple commands.

# Multiple commands
function createBranchFromMaster() {
    git checkout master
    git pull origin master
    git checkout -b "$1" master
}

 

Step 4:-   Changes update.

# update file
source ~/.custom_aliases

 

Usage:

# create branch
createBranchFromMaster custom_branch
 

Conclusion:

For every task performed, time is a vital factor that impacts the performance and efficiency of a programmer. Hence, it is important to be efficient and creating such custom commands helps the cause greatly.  

 

Thanks

 
Introduction of strictNullChecks in Angular 4

With the release of Angular 4.1.1. This angular team fulfilled the promise meant for Angular 4.1 which was Adding the support for strictNullChecks in TypeScript's compiler, added in TypeScript 2.0.

 

Strict Null Checking = Writing a Safe Code

 

The transpiler allows us to write the code in a safer manner. Typescript with strictNullChecks enabled becomes way more comfortable for developers with a background in the static-types language. As the matter of fact, without the use of strict null checks, assigning null or undefined to a variable becomes perfectly possible.

 

// OK
const age: number = 24;
const age: number = null;
        

 

 

For developers friendly with JavaScript, this appears familiar as JavaScript doesn’t performs any sort of type checks during assignment of a variable. But, on the other hand, this behaviour appears quite weird to developers from Swift or C# who have are habitual with the concepts like 'optionals' and 'nullables'. For Eg:

 

// OK
int age = 24;
int? age = 24;
int? age = null;
 
// error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
int age = null;
        

 

The use of strict null checking in typescript enables a developer to have a similar behavior. The equivalent of the piece of code 'int?' nullable type from C# described above will be 'number | null'. With TypeScript compiler enabled for strictNullChecks, the behavior is :

 

// OK
const age: number = 24;
const age: number | null = 24;
const age: number | null = null;
const age: number | undefined = undefined;
 
// TS2322: Type 'null' is not assignable to type 'number'.
const age: number = null;
        

 

However, the behavior will be quite sufficient for the developers from a static-typed language environment would anticipate. The strictNullChecks allows to eliminate the careless mistakes made by developers and make the code base more safe by making the explicit occurrence of null —which is an integral characteristic of the static-typed languages.

 

Opt-in:

 

To allow the use of the new feature of strict null checking, one has to upgrade to Angular 4.1.1 and  TypeScript 2.1 (or later). Subsequently, add the below configuration to the tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictNullChecks": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}
        

 

Post enabling the above configuration, we might need to adjust existing type definitions wherever necessary. The compiler will point out towards all the required places in the code base which needs a change.

 

However, Please note, with this setting enabled, all the third-party libraries/plugins in use must support strictNullChecks.

 

NOTE: To disable type checking for third-party libraries, we may use 'skipLibCheck'.

 

Summary:

 

To summarize, strictNullChecks can play a great role in preventing careless slips and minor bugs in the code which are generally difficult to recognize. By making the existence of null or undefined variables much more specific, it enhances and strengthens the project's code base—a perfect choice for applications especially which are built on a larger scale. Opting-in is as easy as a process of just adding the line mentioned in above tsconfig.json to yours.

 

Thanks

Scoping and Hoisting in JavaScript

For a beginner in JavaScript, it's quite usual to come across the term "Hoisting in JavaScript", Before going into further details lets, have a look at an example. Below, a function is created and invoked:

function cowSays(sound){
  console.log(sound);
}
cowSays('moo');

 

As one may expect,  when the function "cowSays" is invoked by passing a string 'moo' as an argument, the function logs the passed string and the output in the case is 'moo'.

cowSays('moo');
// moo

 

But, what if we try to invoke the function before it is actually declared?

cowSays('moo');
function cowSays(sound){
  console.log(sound);
}

 

Unexpectedly, the function gets called again and 'moo' is returned as the output to the console.

cowSays('moo');
// moo

 

This is what is known as hoisting in JavaScript.

So, what did we just see? Usually, people describe hoisting as declarations moving at top of the code. Although, it is something that appears to be happening. But technically, the code never moves anywhere. Such magic doesn't exist yet. 

What actually happens is the declarations of the functions and variables are added to the memory at the time of compilation.


In the above given example, since the function declaration is added to the memory during the compile phase. In the example above, since the declaration of functions is added to the memory at the compile time, We were able to access them even before the place they were declared.

Now, Let's have a look at another example with a different variable:

Typically,  one should declare then initialize the variable,  and then should attempt to make use of it:

var a = 3;
console.log(a);
// 3

 

However, what will happend, if the variable is declared at the bottom of the code?

a = 3;
console.log(a);
var a;
// 3

 

The example above logs the output as '3'

But, How about the below example in which we declare and initialize  the variable right at bottom of the code?

console.log(a);
var a = 3;
// undefined

 

This is where something unexpected happenes for the first time and we getthe output as 'undefined' instead of '3'.

The above case happens because 'Javascript hoists just the declarations and avoids the initializations'.

 

When a variable is intitalize and declare say, 'var a = 3', JavaScript hoists only the declaration part and thus 'a=3' is not hoisted and therefore not added to the memory.

If we declare and initialize a variable, say var a = 3;, only the var a;portion (the declaration) is going to be hoisted. The a = 3; (the initialization) is not hoisted and therefore not added to memory.

As we know, when the variable is declared but not initialized, the variable is automatically initialized to 'undefined'. And, thus in the abpve example var a is set to 'undefined' and not '3'.

console.log(a);
var a = 3;
// undefined

 

In fact, the code is complied as:

var a;
console.log(a);
a = 3;
// undefined

 

Best Practice

 

Due of hoisting in javaScript, it is usually considered good practice to declare our variable always at the top of our respective scopes. Following this removed the risk of any undesirable effects in the code. declare your variables at the top of their respective scopes. This way there are no undesirable effects such as undefined variables in the code.

 

Thanks

Usage of Resolvers in Angular 2.

Introduction:

A common way to get and display the data from some API is routing a specific user to an angular component, and therafter calling a method present in service from the component’s  'ngOnInit' hook to fetch the necessary information. In this approach we often display some loading indicator till the response is arrived from the server.
However, there is another way called 'route resolver' which allows us to get the necessary data prior to navigation to a particular route. 

Tip- Resolvers should not be overused

We should load only the relevant data through resolvers to display the important sections of the page and rest of the data should be fetched asynchronously.

 

Resolver usage example in route config :

// main.ts

import { TransactionResolver } from './resolvers/transaction.resolver.ts';

export const routes: RouterConfig = [
  {
    path: 'transactions/:id',
    component: TransactionComponent,
    resolve: {
      transaction: TransactionResolver
    }
  }
];

bootstrap(AppComponent, [
  provideRouter(routes)
])
 
In the above example, we pass a 'TransactionResolver' class in the 'resolve' property of the route config object. Using this property Angular will run all the classes given inside the object, before loading the 'TransactionComponentcomponent given in the route.
 
Resolver Class Implementation
 
// transaction.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { TransactionService } from '../services/transaction.service';

@Injectable()
export class TransactionResolver implements Resolve {
  constructor(
    private transactionService: TransactionService
  ) {}

  resolve(route: ActivatedRouteSnapshot): Observable {
    return this.transactionService.getById(route.params.id);
  }
}
  • The exported class should be Injectable
  • The class should implements 'Resolve<any>' interface with one method 'resolve(): Observable<any>'
Thanks
A Brief Introduction To Virtual JoyStick In Phaser

Introduction

 

Most of the mobile and desktop games today come with an inbuilt virtual joystick. The joystick in a game not only enhances the user experience but also helps to gain prolonged attention of a user. This blog describes us a way through which we can add a virtual joystick in our game using phaser
In our current example, we will be loading a pad with such 'top', 'left', 'right' and 'bottom' keys along with three other buttons  'A', 'B', 'C', serving different purpose like "tint", "scale" and both "scale and tint" .
 
To load the pad we will be using "game.plugins.add(Phaser.VirtualJoystick)" method in the create function to create a "pad" object which will be used to configure our joystick navigation keys. Further we will be creating a 'stick' variable using 'pad' object which will add a stick like image over the screen. The stick can be positioned as per the game requirement.
Subsequently, The configuration of the stick is done in the update() function which runs every frame.
 
The final code is summarized below.
 
 
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example');

var PhaserGame = function () {

    this.sprite;

    this.pad;

    this.stick;

    this.buttonA;
    this.buttonB;
    this.buttonC;

};

PhaserGame.prototype = {

    init: function () {

        this.game.renderer.renderSession.roundPixels = true;
        this.physics.startSystem(Phaser.Physics.ARCADE);

    },

    preload: function () {

        this.load.atlas('dpad', 'assets/virtualjoystick/skins/dpad.png', 'assets/virtualjoystick/skins/dpad.json');
        this.load.image('ball', 'assets/virtualjoystick/beball1.png');
        this.load.image('bg', 'assets/virtualjoystick/space2.png');

    },

    create: function () {

        this.add.image(0, 0, 'bg');

        this.sprite = this.add.sprite(400, 200, 'ball');
        this.physics.arcade.enable(this.sprite);

        this.pad = this.game.plugins.add(Phaser.VirtualJoystick);

        this.stick = this.pad.addDPad(0, 0, 200, 'dpad');
        this.stick.alignBottomLeft(0);

        this.buttonA = this.pad.addButton(500, 520, 'dpad', 'button1-up', 'button1-down');
        this.buttonA.onDown.add(this.pressButtonA, this);

        this.buttonB = this.pad.addButton(615, 450, 'dpad', 'button2-up', 'button2-down');
        this.buttonB.onDown.add(this.pressButtonB, this);

        this.buttonC = this.pad.addButton(730, 520, 'dpad', 'button3-up', 'button3-down');
        this.buttonC.onDown.add(this.pressButtonC, this);

    },

    pressButtonA: function () {

        this.sprite.tint = Math.random() * 0xFFFFFF;

    },

    pressButtonB: function () {

        this.sprite.scale.set(Math.random() * 4);

    },

    pressButtonC: function () {

        this.sprite.scale.set(1);
        this.sprite.tint = 0xFFFFFF;

    },

    update: function () {

        var maxSpeed = 300;

        if (this.stick.isDown)
        {
            this.sprite.body.velocity.set(0);

            if (this.stick.direction === Phaser.LEFT)
            {
                this.sprite.body.velocity.x = -maxSpeed;
            }
            else if (this.stick.direction === Phaser.RIGHT)
            {
                this.sprite.body.velocity.x = maxSpeed;
            }
            else if (this.stick.direction === Phaser.UP)
            {
                this.sprite.body.velocity.y = -maxSpeed;
            }
            else if (this.stick.direction === Phaser.DOWN)
            {
                this.sprite.body.velocity.y = maxSpeed;
            }
        }
        else
        {
            this.sprite.body.velocity.set(0);
        }

    }

};

game.state.add('Game', PhaserGame, true);
 
Thanks
Use And Importance Of Zone Js In Angular

Purpose of ZoneJs in Angular 2.

 

This blog serves a good read for the ones who are looking for a brief overview on zonejs in angular2 and what is its exact purpose.

As soon as we come across some Angular 2 platform, we run across various sets of required packages which are responsible for working of Angular. Interestingly, the readme file in the angular bundle clearly states that "For Proper functioning of angular and other external dependencies, polyfilles are required(zone.js)"

So what is zone.js and what is the exact need of it. The definition of zone according to angular is 

"

Purpose of ZoneJs in Angular 2.

 

This blog serves a good read for the ones who are looking for a brief overview on zonejs in angular2 and what is its exact purpose.

As soon as we come across some Angular 2 platform, we run across various sets of required packages which are responsible for working of Angular. Interestingly, the readme file in the angular bundle clearly states that "For Proper functioning of angular and other external dependencies, polyfilles are required(zone.js)"

So what is zone.js and what is the exact need of it. The definition of zone according to angular is 

"A Zone is an execution setting that continues crosswise over async undertakings." One may consider it some string neighborhood stockpiling of JavaScript Virtual Machines."

That sounds good, and apparently Angular simply uses zonejs for domains like errors, traces of stack, etc. However that's not all zone js do. It has more vital tasks underneath.

Lets try an experiment for better understanding. Create a simple Angular app with basic binding, and exclude zone.js from it. See what's the impact. Yes, the binding stops working.

Digging in the code. Hence, zone js is basically responsible for all the change detection and without it change detection just wont work and we end up with ordinary DOM without any exciting UI updates via binding.

SO why it is important? Well,  this is beacuse in Angular , the $digest cycle is totally absent unlike in the original Angualr 1 version. So, ZoneJs acts as its replacement in Angular 2 and serves all the change detection purpose:

 

let marker = new google.maps.Marker({
  position: new google.maps.LatLng(1, 1),
  map: someMap,
  title: 'Title of a marker'
});
marker.addListener('click', () => {
  this.someProperty = Math.random();
});

 

In above code the UI would not update on the click properly, as 'someProperty' is infact updated outside the scope of Angular zone. So to get proper updates we will have to do something like this:

 

marker.addListener('click', () => {
  this.zone.run(() => {
    this.someProperty = Math.random();
  });
});

 

So to sum up, zone.run() is similar to the new $digest().

 

Thanks

"

That sounds good, and apparently Angular simply uses zonejs for domains like errors, traces of stack, etc. However that's not all zone js do. It has more vital tasks underneath.

Lets try an experiment for better understanding. Create a simple Angular app with basic binding, and exclude zone.js from it. See what's the impact. Yes, the binding stops working.

Digging in the code. Hence, zone js is basically responsible for all the change detection and without it change detection just wont work and we end up with ordinary DOM without any exciting UI updates via binding.

SO why it is important? Well,  this is beacuse in Angular , the $digest cycle is totally absent unlike in the original Angualr 1 version. So, ZoneJs acts as its replacement in Angular 2 and serves all the change detection purpose:

 

let marker = new google.maps.Marker({
  position: new google.maps.LatLng(1, 1),
  map: someMap,
  title: 'Title of a marker'
});
marker.addListener('click', () => {
  this.someProperty = Math.random();
});

 

In above code the UI would not update on the click properly, as 'someProperty' is infact updated outside the scope of Angular zone. So to get proper updates we will have to do something like this:

 

marker.addListener('click', () => {
  this.zone.run(() => {
    this.someProperty = Math.random();
  });
});

 

So to sum up, zone.run() is similar to the new $digest().

 

Thanks

Audio Sprite In Phaser

Introduction

 

No game in the world is complete without some special sounds. The sound during a game not only enhances the user experience but also helps to gain prolonged attention of a user. This blog describes us a way through which we can add sounds in our game using phaser. 
In our current example, we will be loading multiple buttons such as 'numKey', 'escape',  'shot', 'squit' . On click of this button we will be playing different sort of audios.
 
The buttons are created by calling makeButton function for each function and passing button meta data as arguments. The buttons are added using "game.add.button" method of the 'add' class. Also, the makeButton function is used to add text for each button which acts as button name. The text is added using "game.add.bitmapText" method with 'nokia' font loaded in preload.
 
To load the audio we will be using "game.load.audio" method in the preload function. Thereafter in create function we will be creating an audio object 'fx' which will be used to perform operations over an audio.
Subsequently, we will be creating audios with different identifiers using "fx.addMarker()" function which takes parameters like identifier, start time and duration of the audio. Eventually, there will be creating buttons and will play various audios on their click using "fx.play()" method
 
To cover up all the above mentioned steps, the final code is summarized below.
 
 
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create });

function preload() {

    game.load.image('title', 'assets/pics/catastrophi.png');

    game.load.spritesheet('button', 'assets/buttons/flixel-button.png', 80, 20);
    game.load.bitmapFont('nokia', 'assets/fonts/bitmapFonts/nokia16black.png', 'assets/fonts/bitmapFonts/nokia16black.xml');

    // game.load.audio('sfx', [ 'assets/audio/SoundEffects/fx_mixdown.mp3', 'assets/audio/SoundEffects/fx_mixdown.ogg' ]);
    game.load.audio('sfx', 'assets/audio/SoundEffects/fx_mixdown.ogg');

}

var fx;

function create() {

	game.add.image(0, 0, 'title');

	//	Here we set-up our audio sprite
	fx = game.add.audio('sfx');
    fx.allowMultiple = true;

	//	And this defines the markers.

	//	They consist of a key (for replaying), the time the sound starts and the duration, both given in seconds.
	//	You can also set the volume and loop state, although we don't use them in this example (see the docs)

	fx.addMarker('alien death', 1, 1.0);
	fx.addMarker('boss hit', 3, 0.5);
	fx.addMarker('escape', 4, 3.2);
	fx.addMarker('meow', 8, 0.5);
	fx.addMarker('numkey', 9, 0.1);
	fx.addMarker('ping', 10, 1.0);
	fx.addMarker('death', 12, 4.2);
	fx.addMarker('shot', 17, 1.0);
	fx.addMarker('squit', 19, 0.3);

	//	Make some buttons to trigger the sounds
	makeButton('alien death', 600, 100);
	makeButton('boss hit', 600, 140);
	makeButton('escape', 600, 180);
	makeButton('meow', 600, 220);
	makeButton('numkey', 600, 260);
	makeButton('ping', 600, 300);
	makeButton('death', 600, 340);
	makeButton('shot', 600, 380);
	makeButton('squit', 600, 420);

}

function makeButton(name, x, y) {

    var button = game.add.button(x, y, 'button', click, this, 0, 1, 2);
    button.name = name;
    button.scale.set(2, 1.5);
    button.smoothed = false;

    var text = game.add.bitmapText(x, y + 7, 'nokia', name, 16);
    text.x += (button.width / 2) - (text.textWidth / 2);

}

function click(button) {

	fx.play(button.name);

}

 
Thanks
Lazy Loading a Component in Angular
Introduction
We often come across several scenarios where there is only a a fraction of users visiting a particular module of an application. So, it makes a lot of sense to make them download only the relevant modules and removing the irrelevant modules from the payload. This not only reduces the payload but also enhances the user experience by decreasing the load time especially when omitted modules are having complex routings.
In Angular, the technique through which this can be achieved in "Lazy loading". Lazy loading enables us to load angular components in an asynchronous manner only when a particular route is enabled.
 
 
Step 1: Create a new App with Routing
The application will load "AppComponent"  at the root URL, and when the user will navigate to "lazy/load-me", our created lazy module will load in an asynchronous manner. The Module is created using.
 
ng new lazyDemo --routing
 
Step 2: Creating the Lazy Load Module

In this step we will create a module that we will use for lazy loading. We will also add a couple of components in it namely "lazy-parent" and "lazy-child". The --flat flag used in the commands is used to prevent the creation of a directory so that we can easily add components to the module using Angular CLI.

ng g module lazy --flat
ng g component lazy-parent --module lazy
ng g component lazy-child --module lazy

Import "RouterModule" inside the lazy module. There are two things to consider here:

  1. path: 'load-me' is the route path to the component although it would be activated on "lazy/load-me". It is the child route and it will be integrated in step 3
  2. The "RouterModule" has "forChild(routes)".
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LazyParentComponent } from './lazy-parent/lazy-parent.component';
import { LazyChildComponent } from './lazy-child/lazy-child.component';

import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    { path: 'load-me', component: LazyParentComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [
    LazyParentComponent,
    LazyChildComponent
  ]
})
export class LazyModule { }

 

Step 3: Pointing  App-Router towards the Lazy Module

Our Last step is pointing the route towards the created lazy module from app router. This can be done using  "loadChildren" property and passing path to module. We woulld also need to reference the module using a "#" to tell angular to load "LazyModule" only when the concerned url is active.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    { path: 'lazy', loadChildren: './lazy.module#LazyModule'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { } 

Thanks

Creating a custom plugin in wordpress

 

Introduction
 
In this blog we will learn how to create a custom plugin in wordpress. A plugin in wordpress is a set of re-usable code which helps us with any specific task. For instance, creating custom taxanomies, creating custom theme options etc.
I This blog we will aim to create a custom plugin which upon activation will automatically create a "custom post type" named "sample-post-type" in wordpress dashboard.
 
Essentials Steps.
 
A very basic plugin in wordpress comprises of a single php file which loads all the necessary functionality onto the dashboard over some default wordpress hook.
 
1. To Allow the wordpress to recognize our plugin we would need a .php file. As per the wordpress standards the file shoud be located at "wp-content/plugins/<plugin-directory>". In our example we will be creating "sample-post-type.php" in "sample-post-type" directory inside "wp-content/plugins" folder.
 
2. Upon creation, add the following code to the php file which allows wordpress to identify the plugin.
 
<?php
/**
* Plugin Name: Custom Sample Post Type
* Plugin URI: https://www.sample.com
* Description: A custom sample post type built for example.
* Version: 1.0 

**/

The above mentioned code should be enough to display our plugin inside the "Plugins" tab in the dashboard.
 
 
 
3. Now, to provide our plugin with the functionality to add custom post type we will add the following code to our php file over "init" hook using "add_action" method.
 
 
// Register the Custom Sample Post Type
 
function register_cpt() {
 
    $labels array(
        'name' => _x( 'Sample Post Type''sample_post_type' ),
        'singular_name' => _x( 'Sample Post Type''sample_post_type' ),
        'add_new' => _x( 'Add New''sample_post_type' ),
        'add_new_item' => _x( 'Add New Sample Post Type''sample_post_type' ),
        'edit_item' => _x( 'Edit Sample Post Type''sample_post_type' ),
        'new_item' => _x( 'New Sample Post Type''sample_post_type' ),
        'view_item' => _x( 'View Sample Post Type''sample_post_type' ),
        'search_items' => _x( 'Search Sample Post Type''sample_post_type' ),
        'not_found' => _x( 'No Sample Post Type found''sample_post_type' ),
        'not_found_in_trash' => _x( 'No Sample Post Type found in Trash''sample_post_type' ),
        'parent_item_colon' => _x( 'Parent Sample Post Type:''sample_post_type' ),
        'menu_name' => _x( 'Sample Post Type''sample_post_type' ),
    );
 
    $args array(
        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'Sample Post Type filterable by genre',
        'supports' => array'title''editor''author''thumbnail''trackbacks''custom-fields''comments''revisions''page-attributes' ),
        'taxonomies' => array'genres' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-format-audio',
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );
 
    register_post_type( 'sample_post_type'$args );
}
 
add_action( 'init''register_cpt' );
 

The above code upon activating the plugin will lead to the creation of a new custom post type in the dashboard as shown below.

 

 
Thanks
Easing Tween In Phaser

Introduction

 

The blog describes the way through which we can use tweens in phaser to generate animation effect over a particular sprite. This can be useful in instances where we need a sprite to be displayed through an animation like fade in, ease out etc. The tweening can also be applied over text objects in phaser.
In our current example, we will be loading two sprites- 'Phaser' and 'Shadow' and will be applying tween over them using "game.add.tween(sprite)" method.
Further, we will be using a  "To " tween which starts at the current value and tweens to the destination value given.
Its takes parameters which are used to configure the tween like delay, type of tween, object of the properties to apply tween to, autostart and repeat. 
To cover up all the above mentioned steps, the final code is summarized below.
 
let game = new Phaser.Game(750, 550, Phaser.CANVAS, 'container-ref', { preload: preload, create: create });

function preload() {

    game.load.spritesheet('shadow', 'assets/tests/tween/shadow.png', 138, 15);
    game.load.spritesheet('phaser', 'assets/tests/tween/phaser.png', 70, 90);
    
}

function create() {

    var item;
    var shadow;
    var tween;

    // Sets background color to white.
    game.stage.backgroundColor = '#ffffff';

    for (var i = 0; i < 6; i++)
    {
        // Add a shadow to the location which characters will land on.
        // And tween their size to make them look like a real shadow.
        // Put the following code before items to give shadow a lower
        // render order.
        shadow = game.add.sprite(190 + 69 * i, 284, 'shadow');

        // Set shadow's size 0 so that it'll be invisible at the beginning.
        shadow.scale.setTo(0.0, 0.0);

        // Also set the origin to the center since we don't want to
        // see the shadow scale to the left top.
        shadow.anchor.setTo(0.5, 0.5);
        game.add.tween(shadow.scale).to({x: 1.0, y: 1.0}, 2400, Phaser.Easing.Bounce.Out, true);

        // Add characters on top of shadows.
        item = game.add.sprite(190 + 69 * i, -50, 'phaser', i);

        // Set origin to the center to make the rotation look better.
        item.anchor.setTo(0.5, 0.5);

        // Add a simple bounce tween to each character's position.
        tween = game.add.tween(item).to( { y: 245 }, 2400, Phaser.Easing.Bounce.Out, true);
    }

}

 
Thanks
Camera Shake in Phaser

Introduction

The blog tells us a way through which we can make a camera shake in phaser game world. The shake can be used to depict various scenarios such as sprite destruction, game end or negative user input. The shake of the world is achieved by shaking the camera view to and fro for some predefined width or length.
 
In our current example, we will be moving sprite towards using physics which enables to mimic a natural real time movement. The physics over an object is activated through "game.physics.enable()" function.  Also, we will be using the arrow keys to move the sprite throughout the world and on click we will bind a "SHAKE" function which will be used to shake the world.
 
The action on mouse click event calls the "SHAKE" function which calls the  "game.camera.shake(0.05, 500);" method of the camera object. It takes two parameters. The first parameter is used to define the speed and the scond one is used to provide the duration of the shake.
Below is the complete code, summarizing all the steps.
 
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.image('background','assets/tests/debug-grid-1920x1920.png');
    game.load.image('player','assets/sprites/phaser-dude.png');

}

var player;
var cursors;

function create() {

    game.add.tileSprite(0, 0, 1920, 1920, 'background');

    game.world.setBounds(0, 0, 1920, 1920);

    game.physics.startSystem(Phaser.Physics.P2JS);

    player = game.add.sprite(game.world.centerX, game.world.centerY, 'player');

    game.physics.p2.enable(player);

    player.body.fixedRotation = true;

    cursors = game.input.keyboard.createCursorKeys();

    //  Notice that the sprite doesn't have any momentum at all,
    //  it's all just set by the camera follow type.
    //  0.1 is the amount of linear interpolation to use.
    //  The smaller the value, the smooth the camera (and the longer it takes to catch up)
    game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);

    game.input.onDown.add(shake, this);

}

function shake() {

    //  You can set your own intensity and duration
    game.camera.shake(0.05, 500);

}

function update() {

    player.body.setZeroVelocity();

    if (cursors.up.isDown)
    {
        player.body.moveUp(300)
    }
    else if (cursors.down.isDown)
    {
        player.body.moveDown(300);
    }

    if (cursors.left.isDown)
    {
        player.body.velocity.x = -300;
    }
    else if (cursors.right.isDown)
    {
        player.body.moveRight(300);
    }

}

function render() {

    game.debug.text("Arrows to move. Click to shake", 32, 32);

}
 
Thanks
Follow Mouse Pointer in Phaser

Introduction

The blog describes the way through which we can make a sprite follow a mouse pointer. This can be useful in instances where we need a sprite(eg: tool-tip) to be displayed just next to pointer, or move a player towards the mouse pointer on events such as mouse down.
In our current example, we will be moving sprite towards the pointer using physics which helps to mimic natural object movement. The physics on an object can be enabled using "game.physics.enable()" method. 
The action on mouse event takes place in "UPDATE()" function which run every frame. In oure  example, to move the sprite towards pointer we will use "game.physics.arcade.moveToPointer();" method while providing it some velocity using "sprite.body.velocity.setTo(0, 0);"
 
Below is the complete code, summarizing all the steps.
 
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });

function preload() {

    game.load.image('ball', 'assets/sprites/shinyball.png');

}

var sprite;

function create() {

    sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'ball');
   game.physics.enable(sprite, Phaser.Physics.ARCADE);
 
}

function update() {

    //  only move when you click
    if (game.input.mousePointer.isDown)
    {
        //  400 is the speed it will move towards the mouse
        game.physics.arcade.moveToPointer(sprite, 400);

        //  if it's overlapping the mouse, don't move any more
        if (Phaser.Rectangle.contains(sprite.body, game.input.x, game.input.y))
        {
            sprite.body.velocity.setTo(0, 0);
        }
    }
    else
    {
        sprite.body.velocity.setTo(0, 0);
    }

}
 
Thanks
Move A Sprite in Phaser

Introduction

The below-mentioned code demonstrates the creation of a "Movable Sprite" in phaser.
The approach used to achieve the objective comprises of a sprite which has animation enabled over it. The animation helps in giving a sense of a running bot. Further, The sprite is moved by updating its X and Y coordinates in "UPDATE" function upon arrow key press.
 
The "animation" property can be accessed via the sprite object and is used to evoke a methods "add()"  to define the animation over sprite. The method's parameters are explained as follows:
 
NameTypeArgumentDefaultDescriptionframeRatenumber<optional>null

The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.

loopboolean<optional>false

enables animation loop after playback.

killOnCompleteboolean<optional>false

Kills the parent sprite if set to true.

 

Code :-

 

    var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });
    
    function preload() {
        game.load.atlasJSONHash('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json');
    }
    
    var s;
    
    function create() {
    
        s = game.add.sprite(game.world.centerX, game.world.centerY, 'bot');
        s.anchor.setTo(0.5, 0.5);
        s.scale.setTo(2, 2);
    
        s.animations.add('run');
        s.animations.play('run', 10, true);
    
    }
    
    function update() {
    
        if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
        {
            s.x -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
        {
            s.x += 4;
        }
    
        if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
        {
            s.y -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
        {
            s.y += 4;
        }
    
    }
    
    function render() {
        game.debug.spriteInfo(s, 20, 32);
    
    }

 

Source: phaser.io/examples/v2/sprites/move-a-sprite

Thanks

Conditionally elements inside Array using Spread Operator

As a developer often, we often encounter scenarios where we need conditional elements in an Array or an object literal. To achieve the objective most of us often use one of the two ways:
1. Using "push()" method.
2. Using "Splice() method".

However both the above methods would need to be enclosed in a specific condition to work. With push() having a limitation to add an element only at the end of an array.

With the advent of ECMAScript 6, we may use a more feasible way to add elements to an array conditionally. The method use spread and ternary operator for the purpose and is explained below.

 

a)  Conditional elements inside Array.  

 

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

 

It works, as (...) - the spread operator spreads nothing if the operand is an empty array.

 

> [...[], 'a']
[ 'a' ]

 

b)  Conditional properties inside object literals  

 

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Thanks

Draggable Line in Phaser

Introduction

The below-mentioned code demonstrates the creation of a "Draggable Line" using two sprites in phaser.
The approach used to achieve the objective comprises of two independent draggable sprites who are connected using a geometrical line. The coordinates of the line are updated on the movement of each end thus moving the line itself.

In Phaser, The line can be linked to two sprites using "fromSprite " method. The method takes three arguments which are explained as follows:

An Example code of " Draggable Line" in phaser is provided below.

var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.spritesheet('balls', 'assets/sprites/balls.png', 17, 17);

}

var handle1;
var handle2;

var line1;

function create() {

    game.stage.backgroundColor = '#124184';

    handle1 = game.add.sprite(100, 200, 'balls', 0);
    handle1.anchor.set(0.5);
    handle1.inputEnabled = true;
    handle1.input.enableDrag(true);

    handle2 = game.add.sprite(400, 300, 'balls', 0);
    handle2.anchor.set(0.5);
    handle2.inputEnabled = true;
    handle2.input.enableDrag(true);

    line1 = new Phaser.Line(handle1.x, handle1.y, handle2.x, handle2.y);

}

function update() {

    line1.fromSprite(handle1, handle2, false);

}

function render() {

    game.debug.geom(line1);
    game.debug.lineInfo(line1, 32, 32);

    game.debug.text("Drag the handles", 32, 550);

}
 

Thanks

Rectangular Bound in Phaser

Introduction

 

Below Mentioned code demonstrates the "Bound Rect" functionality on the movement of a sprite in phaser.

The Bound Rect stands for a rectangular bounda which can be created to restrict movement of an object/sprite in a game world. 

In Phaser, "Bound Rect" is setting "boundsRect" property to a rectangular sprite or geomatrical Object.

However, To enable the bounds a sprite must have input enabled over it as the "boundsRect" property can be accessed only inside the input object of a sprite. The code to summarize it is as follows.

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });

function preload() {

    game.load.image('atari', 'assets/sprites/atari800xl.png');

}

var sprite;
var bounds;

function create() {

    game.stage.backgroundColor = '#2d2d2d';

    bounds = new Phaser.Rectangle(100, 100, 500, 400);

    // Create a graphic so you can see the bounds
    var graphics = game.add.graphics(bounds.x, bounds.y);
    graphics.beginFill(0x000077);
    graphics.drawRect(0, 0, bounds.width, bounds.height);

    sprite = game.add.sprite(300, 300, 'atari');
    sprite.inputEnabled = true;
    sprite.anchor.set(0.5);

    sprite.input.enableDrag();
    sprite.input.boundsRect = bounds;

}

Thanks 

Snap On Drag In Phaser

Introduction

 

 

Below Mentioned code demonstrates the "Snap On Drag" functionality on drag of a sprite in phaser.

To enable the "Snap On Drag" one must set input property of the sprite to be "true" and enable the drag over it using "enableDrag" method.

In Phaser, "Snap On Drag" is enabled using enableSnap() method which taked 6 parameters. They are explained as follows:

 

 

 

NameTypeArgumentDefaultDescriptionsnapXnumber  

The width of the grid cell to snap to.

snapYnumber  

The height of the grid cell to snap to.

onDragboolean<optional>true

If true the sprite will snap to the grid while being dragged.

onReleaseboolean<optional>false

If true the sprite will snap to the grid when released.

snapOffsetXnumber<optional>0

Used to offset the top-left starting point of the snap grid.

snapOffsetYnumber<optional>0

Used to offset the top-left starting point of the snap grid.

 

 

An Example code of "Snap On Drag" of the sprite is provided below.

    var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });
    function preload() {
    game.load.image('grid', 'assets/tests/debug-grid-1920x1920.png');
    game.load.image('atari1', 'assets/sprites/atari130xe.png');
    game.load.image('atari2', 'assets/sprites/atari800xl.png');
    }
    function create() {
    game.add.sprite(0, 0, 'grid');
    atari1 = game.add.sprite(128, 128, 'atari1');
    atari2 = game.add.sprite(256, 256, 'atari2');
    // Input Enable the sprites
    atari1.inputEnabled = true;
    atari2.inputEnabled = true;
    // Allow dragging
    // enableDrag parameters = (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite)
    atari1.input.enableDrag();
    atari2.input.enableDrag();
    // Enable snapping. For the atari1 sprite it will snap as its dragged around and on release.
    // The snap is set to every 32x32 pixels.
    atari1.input.enableSnap(32, 32, true, true);
    // For the atari2 sprite it will snap only when released, not on drag.
    atari2.input.enableSnap(32, 32, false, true);
    }

Thanks.

Drag Update Using Phaser

Introduction

 

Below Mentioned code demonstrates how to enable drag and drag related events on a sprite.

To enable the Drag one must set input property of the sprite to be "true", Upon Enabling the Drag three events can be attached to the sprite to perform some actions inside the Phaser World.

In Below Example, three evens are attached to the "ship" sprite. They are:

  • onDragStart
  • onDragUpdate
  • onDragStop

Above mentioned events are used to update the "ball" sprite's coordinates, angle and opacity(alpha) to give an effect of revolution of the arrow around the ship on drag.

    var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create });
    function preload() {
    game.load.image('ship', 'assets/sprites/ship.png');
    game.load.image('ball', 'assets/sprites/longarrow.png');
    }
    var angle = 0;
    var dragSprite;
    var copySprite;
    function create() {
    game.stage.backgroundColor = '#2f0f1c';
    dragSprite = game.add.sprite(game.world.centerX, game.world.centerY, 'ship');
    dragSprite.anchor.set(0.5);
    // Input Enable the sprite
    dragSprite.inputEnabled = true;
    // Allow dragging
    dragSprite.input.enableDrag();
    // Drag events
    dragSprite.events.onDragStart.add(dragStart);
    dragSprite.events.onDragUpdate.add(dragUpdate);
    dragSprite.events.onDragStop.add(dragStop);
    copySprite = game.add.sprite(dragSprite.x + 220, dragSprite.y, 'ball');
    copySprite.anchor.set(0, 0.5);
    copySprite.alpha = 0.5;
    copySprite.angle = 180;
    var text = game.add.text(32, 32, "drag the ship", { font: "32px Arial", fill: "#f9b4cf" });
    text.setShadow(6, 6, 'rgba(0,0,0,0.8)', 5);
    }
    function dragStart() {
    copySprite.alpha = 1;
    }
    function dragUpdate(sprite, pointer, dragX, dragY, snapPoint) {
    // As we drag the ship around inc the angle
    angle += 0.01;
    // This just circles the copySprite around the sprite being dragged
    copySprite.x = dragSprite.x + 220 * Math.cos(angle);
    copySprite.y = dragSprite.y + 220 * Math.sin(angle);
    // And this points the copySprite at the current pointer
    copySprite.rotation = game.physics.arcade.angleToPointer(copySprite);
    }
    function dragStop() {
    copySprite.alpha = 0.5;
    }

Thanks.

Cursor Key Movements In Phaser Gaming Engine

Introduction

 

Phaser is one of the most popular HTML5 gaming engine. It has wide array of support including mobiles as well as browser. This Phaser is basically contained in a JS file, which can be included in the page through CDN as well as locally. HTML5 handles graphics and games using canvas element. It updates the displayed canvas based on user input, and is compatible with use of physics in a game too thus making it a preferred choice for 2D game development. 

Below Mentioned code demonstrates the use of cursor keys as user inputs to move the camera to traverse inside the game world. The game world in this example is full of static sprites randomly positioned across the entire world bounds.

    var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });
    function preload() {
    game.stage.backgroundColor = '#007236';
    game.load.image('ball', 'assets/sprites/shinyball.png');
    game.load.image('mushroom', 'assets/sprites/mushroom2.png');
    game.load.image('phaser', 'assets/sprites/sonic_havok_sanity.png');
    }
    var cursors;
    function create() {
    // Modify the world and camera bounds
    game.world.setBounds(-1000, -1000, 2000, 2000);
    for (var i = 0; i < 100; i++)
    {
    game.add.image(game.world.randomX, game.world.randomY, 'mushroom');
    }
    game.add.image(-16, -16, 'ball');
    // This will create a new object called "cursors", inside it will contain 4 objects: up, down, left and right.
    // These are all Phaser.Key objects, so anything you can do with a Key object you can do with these.
    cursors = game.input.keyboard.createCursorKeys();
    var text = game.add.text(32, 32, 'Cursors to move. Shift + Up / Down to Rotate World', { fill: '#ffffff' });
    }
    function update() {
    // For example this checks if the up or down keys are pressed and moves the camera accordingly.
    if (cursors.up.isDown)
    {
    // If the shift key is also pressed then the world is rotated
    if (cursors.up.shiftKey)
    {
    game.world.rotation += 0.05;
    }
    else
    {
    game.camera.y -= 4;
    }
    }
    else if (cursors.down.isDown)
    {
    if (cursors.down.shiftKey)
    {
    game.world.rotation -= 0.05;
    }
    else
    {
    game.camera.y += 4;
    }
    }
    if (cursors.left.isDown)
    {
    game.camera.x -= 4;
    }
    else if (cursors.right.isDown)
    {
    game.camera.x += 4;
    }
    }
    function render() {
    game.debug.cameraInfo(game.camera, 32, 500);
    }

Thanks

 

Replacing Nested Switch Statements with Objects

I came across a scenario in which I had to use nested switch statements to return values based on nested cases. Although easy to implement using nested switch cases was not convincing enough for me considering the performance.
My code looked like the below function:

The function converts array indexes into minutes based on hour parameter named "hourGranularity.

function replaceMinuteIndexInMinutes(hourGranularity, index) {
 
    switch (hourGranularity) {
 
        case 1:
            {
                switch (index) {
                    case 0:
                        return 0;
                    default:
                        return null;
                }
            }
        case 2:
            {
                switch (index) {
                    case 0:
                        return 0;
                    case 1:
                        return 30;
                    default:
                        return null;
                }
            }
        case 4:
            {
                switch (index) {
                    case 0:
                        return 0;
                    case 1:
                        return 15;
                    case 2:
                        return 30;
                    case 3:
                        return 45;
                    default:
                        return null;
                }
            }
        default:
            {
                return 0;
            }
    }
 
}

 

The above function looks great but can prove to be a performance nightmare, So, A better way to achieve the desired result using such static values is using object literals. The approach uses multidimensional arrays/objects which involves taking each case as an index/key and returning the value for the corresponding matrix formed. For Instance:

function replaceMinuteIndexInMinutes(hourGranularity, index) {
let minuteIndexInMinutesObj = {
1:
{
0: 0
},
2:
{
0: 0,
1: 30,
},
4:
0: 0,
1: 15,
2: 30,
3: 45,
},
}
return minuteIndexInMinutesObj[hourGranularity][index]
 
}

Thanks.

Ultimate Guide to Angular CLI

Angular CLI Introduction

Angular CLI is the Command Line Interface which is used to automate our development and its workflow. We can perform following tasks using Angular CLI:

  • Creating an Angular application
  • Serve the Angular application with LiveReload support.
  • Doing Unit test in the application
  • Runing end-to-end (E2E) tests in the application.
  • build and deployment of the application on different environment.

Minimum Prerequisites

1.Node.js 6.9.0 or higher.

2. NPM 3.0.0 or higher

Angular CLI Installation

$ npm install -g @angular/cli

This command will install the ng command globally across the system and can be verified using:

$ ng version

which will display the version installed:

@angular/cli: 1.0.0
node: 6.10.0
os: darwin x64

Create the Angular Application using CLI

  •  
$ ng new my-app

The command results in production of following directories and project structure:

  •  
.
??? README.md
??? e2e
?   ??? app.e2e-spec.ts
?   ??? app.po.ts
?   ??? tsconfig.e2e.json
??? karma.conf.js
??? package.json
??? protractor.conf.js
??? src
?   ??? app
?   ?   ??? app.component.css
?   ?   ??? app.component.html
?   ?   ??? app.component.spec.ts
?   ?   ??? app.component.ts
?   ?   ??? app.module.ts
?   ??? assets
?   ??? environments
?   ?   ??? environment.prod.ts
?   ?   ??? environment.ts
?   ??? favicon.ico
?   ??? index.html
?   ??? main.ts
?   ??? polyfills.ts
?   ??? styles.css
?   ??? test.ts
?   ??? tsconfig.app.json
?   ??? tsconfig.spec.json
?   ??? typings.d.ts
??? tsconfig.json
??? tslint.json

$ ng generate --help can be used to see all theh available options of the locall installation of the Angular CLI.

Serving the Application

The app can be run by going into the project's root directory and using ther serve command of the angular CLI:

$ ng serve

This command will start the development server at default 4200 port. the output in the terminal can be viewed as:

** NG Live Development Server is running on http://localhost:4200 **
Hash: 09fb2ad840c1472e5885
Time: 6230ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 158 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 3.62 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 9.77 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.37 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

Navigating to http://localhost:4200/ will display a working angular quick start application:

Generate command:

The ng generate command is a vital command and can be used to add different features into the existing application:

  • ng generate class my-new-class: adding a new class to the application
  • ng generate component my-new-component: adding a new component to the application
  • ng generate directive my-new-directive: adding a new directive to the application
  • ng generate enum my-new-enumadding an enum to the application
  • ng generate module my-new-module: add a new module to the application
  • ng generate pipe my-new-pipe: adding a new pipe to the application
  • ng generate service my-new-serviceadding a new service to the application
  •  

Thanks

How to Integrate Credit Sense iframe Into A Web Page

Credit Sense is service which supports decision service. They have immense experience in the finance and IT sectors, their executive team felt the need of robust businesses and deeper understanding of customers.

Businesses needed the confidence to approve much higher number of customers along with managing the risk associated. Understanding customer’s recent transaction history is a pretty effective method to do this, however the process and steps involved in manually obtaining analyzing the bank statements slow, expensive and generally unreliable.

They resolved this issue by developing some advanced technology which uses pattern matching, a seemless customer experience and an easy integrable suite. These elements together deliver their clients some valuable decision support which is based on reliable analyzed of customer transaction histories in real-time during the customer application. The Credit Sense provides an Iframe Integration across web apps to fetch consumer details.

Responsive iframe:

The responsive iframe solution enables you to integrate Credit Sense as a step in your online application process, ensuring the customer stays on your page and improving completion rates. The responsive iframe is our most popular integration option. It is highly configurable offering full CSS override and a jQuery module enabling communication between the underlying page and the iframe.
Steps to Implement:
1.Insert the Include the jQuery dependency on your website.

<iframe id="creditSenseIFrame" src="about:blank"
style="height: 580px; width:98%; border:
none">iframes are not supported in this
browser</iframe>

2. Include Jquery dependency in your site. Typically, JavaScript files should be kept at the end of your body document (unless you have some requirement for it to be loaded earlier). This allows your page content to load as quickly as possible and provide the best user experience. You can either use a hosted version of jQuery, or self-host the code. For this example, we are using the Google-hosted version.

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/
1.12.4/jquery.min.js"></script>

3. Include the CreditSense iframe script on your website. This file must be included after jQuery's script tags. Note that you must use a version of the script hosted on CreditSense's servers. This allows us to push out improvements transparently.

<script
src="https://6dadc58e31982fd9f0be-d4a1ccb0c1936ef2
a5b7f304db75b8a4.ssl.cf4.rackcdn.com/CS-Integrated
-Iframe-v1.min.js"></script>

4. Include the initialisation script. This must be included after the CreditSense iframe script tags. Replace TEST111 with the client ID provided to you by CreditSense. You may rename the element selector to be whatever you wish, but it must match the iframe ID you specified earlier.

 

<script>
function logMsg(message) {
 if (typeof console == "object")
console.log(message);
 else alert(message);
}
$(document).ready(function() {
 $.CreditSense.Iframe({
 client: "TEST111",
 elementSelector: "#creditSenseIFrame",
 params: {
 appRef: '<your unique app reference>',
// Set this value to a unique reference for the
application
 uniqueAppRef: true // indicates that
the appRef provided is unique
 },
 callback: function(response, data) {
 switch (response) {
 case "99": // Example status code
(Bank status success)
 logMsg('Bank details collected
successfully');
 break;
 case "100": // Example status code
 onApplicationSuccess();
 break;
 }
 }
 });
});
</script>

 

Thanks

Piston Module for Django APIs

One of the most frequent requirement is providing third-party support in the we application. In this case we generally make an app which handles the API calls, which sets up the views, andsubsequently compiles the data which is then sent in the supported and safe format such as JSON. This also evoked the need to provide some documentation for these API calls and their usage.

In Django, piston solves all our purpose in a go.

django-piston can be installed using pip,

pip install django-piston

Piston is able to provides every little thing we need to create an API in our site withou. It need a few steps to install and to begin with enlist ‘piston’ into INSTALLED_APPS, so that Django can recognize it.

from django.db import models
from django.contrib.auth.models import User

class Note(models.Model):
    user = models.ForeignKey(User)
    pub_date = models.DateTimeField()
    title = models.CharField(max_length=200)
    body = models.TextField()

    def __unicode__(self):
        return self.title

Further steps involve:

1. create <api> app.

2. Define the namespace in the <api> app in entry level urls.py.

urlpatterns = patterns(”,

#other url mappings listed

(r’^api/’, include(‘piston_test.api.urls’)),
)

# next we need to define the resource.

3. create a file named handler.py projectRoot/api/. The file should containg the following code.

from piston.handler import BaseHandler
from myapp.models import Note

class NoteHandler(BaseHandler):
    allowed_methods = ('GET',)
    model = Note

    def read(self, request, id=None):
        if id:
            return Note.objects.get(pk=id)
        else:
            return Note.objects.all()

4. At Last, we need to map our urls to the resources in handler. Like:

from django.conf.urls.defaults import *
from piston.resource import Resource
from piston_test.api.handlers import NoteHandler

note_handler = Resource(NoteHandler)

urlpatterns = patterns('',
    url(r'^note/(?P<id>[^/]+)/', note_handler),
    url(r'^notes/', note_handler),
)

Interestingly, urlpatterns in url.py appear similar to the norm followed and that is the beauty of using Piston.

—-

Thanks

Create a contact form in WordPress using Contact Form 7

Search Plugins box to try and find the plugin you want.Search Plugins box to try and find the plugin you want.Search Plugins box to try and find the plugin you want.In every WordPress site or blog, the admin always needs to provide its viewers with a way to establish contact with him. After all, one always wants to get enquiries appreciations from the site visitors. So, is there any way to achieve this in WordPress

Answer: Contact Form

Contact Form 7 plugin

Contact form 7 plugin is one of the easiest, user-friendly and highly flexible plugin to build contact forms in WordPress. It involves some pretty simple steps to create a form that will give you your users a much-needed feature to contact you. The steps are:

Installation:
  1. Login to wp-admin account.
  2. Go to Plugins and click Add New.
  3. Search Plugins box to find the contact form 7 plugin and click Install Now.
  4. Activate the plugin by clicking Activate Plugin.

 

 

 

 

 

 

 

 

 

You can search for the Plugin you want, or upload the Plugin manually.

Form Creation:

Click on the Contact menu item on the dashboard and copy the shortcode of the default form which will appear similar to this:

[*contact-form-7 id=”1234″ title=”Contact form 1″] (Remove * from the code)

We may also create or own custom form and get its shortcode to display on our site. Contact form also allows us to create multiple contact forms which prove to be quite beneficial in multilingual sites.

Create a new page "Contact" in WordPress and paste the copied shortcode in its content field.

The page on being opened will display our form.

 

Customization:

Contact Form provides us with a rich and effective user interface to create, modify delete fields in the form. It has got various inbuilt fields to select from and even allows us to create and write our own custom markup. Once done creating the form we must save the form using "save" button at the right sidebar.

 

The form on saving is now ready and is displayed on the contact page we created above.

Thanks.

Creating a custom text widget in WordPress

Custom WordPress Text Widget Usage.

The default text widget of WordPress is used quite frequently. For Example:

 

As one may view, we have used multiple default Text widgets, but the problem which occurs frequently is without expanding the widget gives no idea about its internal content. This hampers the user experience as expanding each and every widget remains the only option to view internal content.

To work out this issue we needed to make or modify the existing widget that will be well labelled. In this blog, we will be creating a new widget similar to the text widget but with enhanced features. Steps involved for the same are:

Create a Plugin


Firstly, create a PHP file  [pluginname].php in the plugin directory in wp-content.

 

Add the below-mentioned code in the file replacing all the red marked areas according to the requirements. 

<?php
/* Plugin Name: [Enter name of your plugin here]
Plugin URI: [Enter your website URL]
Description: [Enter brief description of plugin]
Version: [Enter version number of plugin (probably 1.0)]
Author: [Enter your name]
Author URI: [Enter your website URL]
*/

class [PluginNameWithoutSpaces] extends WP_Widget {
          function [PluginNameWithoutSpaces]() {
                    $widget_ops = array(
                    'classname' => '[PluginNameWithoutSpaces]',
                    'description' => '[Enter brief description of plugin]'
          );

          $this->WP_Widget(
                    '[PluginNameWithoutSpaces]',
                    '[Enter plugin name]',
                    $widget_ops
          );
}

          function widget($args, $instance) { // widget sidebar output
                    extract($args, EXTR_SKIP);
                    echo $before_widget; // pre-widget code from theme
print <<<EOM

[Enter code that will appear in your widget here]

EOM;
                    echo $after_widget; // post-widget code from theme
          }
}

add_action(
          'widgets_init',
          create_function('','return register_widget("[PluginNameWithoutSpaces]");')
);
?>

 

Activating the Plugin


Go to the admin area and click on the plugin menu option in the sidebar, This will display all the available plugins on the site with their status. Activate the plugin we just created from the list by clicking "Activate" below the plugin name.

 

Using Widget
Subsequently, we can use our custom text plugin like every other widget available on the site. Just find the widget and select the sidebar it needs to display in.

Congrats! we just created our own custom text widget.
 

Thanks

Changing WordpPress domain using phpmyadmin

WordPress stores the site URL in the database which in turn is used by its various inbuilt functions for providing different features. However, the problem arises when one has to migrate or move the site to a different domain say localhost to staging and staging to production. This leaves the admin with an inaccessible site and no easy way to correct the problem. This blog allows the user to change these settings through some really simple steps directly. 

 

  1. Login to phpMyAdmin using the Control Panel.

  2. Select the MySQL database which is being currently used by the Wordpress site.

  3. After selecting the database, click on the table wp-options. Wp-options is the table which is used by WordPress to store the site URL and other global options.

  4. Click Edit on the row of siteurl. Also, Repeat the same process for the home in the same wp_options table.?


  5.  

  6. Enter the changed blog domain name and select the Go option given to proceed. Example, change the site domain from http://test.com to http://newtestdomain.com.?

  7.  

 

09. Repeat the above procedure for the home line found in the table wp_options

10. Finally, make rename the existing folder to the new URL via FTP or else the File Manager.

Thanks, 

A Sample Of Creating theme option with WordPress

Theme Option in Wordpress can be handy when we need some custom options available across the site. Initially, implementation of such options was a tricky and long procedure. However, with the advent of Settings API in Wordpress version 2.7, Theme options page got simpler as registering the settings calling the options was the only thing required.

The Settings API grants:

  • Ease
  • Enhanced security
  • WordPress Core compatibility.

So, we will be creating together a demo options page for our WordPress site:

Step1-  Register the options using function register_setting

The register_setting function should be hooked to  admin_init action in functions.php else it will result an error.

The above code will declare our options as existent. The options can now be called in the entire theme using function get_option.

However, right now the function won't return anything as out theme option footer_copyright is still undeclared and defined.

Step 2- Now in the below code we have defined the footer copyright to default “© 2017 Site-Name”.

Step 3- Having the default values, now we will declare the available values.

The  add_theme_page function should be called inside a function which in turn is hooked to the "admin_menu" WordPress action. This will append a sub-menu Appearance menu in the admin panel ofWordPresss.

Step 4 - The theme options page will be creating sticking to default layout of admin pages of WordPress.

Saving the file and running the code will display a theme option page in WordPress admin panel consisting of an option to modify footer copy right text. In theme, the copyright text can get fetched using.

Thanks

Creating a Virtualenv in Python

What is Virtualenv?

 

A Python Virtual Environment, is basically an isolated location of Python which
enables a user to work on a particular project without any concern of influencing other projects

It enables version specific installations of Python for each project according to requirements.

Is Virtualenv Already installed

 

There might be a possibility that virtualenv is already present on the system. 

To verify it we may Run the command in our terminal
virtualenv --version
If it displays a version (eg: 1.6.1), it's already installed.
>>1.6.1

Installing Virtualenv

 

There are a various ways for installing virtualenv. Some of them are:
$ sudo apt-get install python-virtualenv

$ sudo easy_install virtualenv

$ sudo pip install virtualenv

Setting up and Using Virtualenv

 

Create a directory for the isolated environment
sudo mkdir ~/myvirtualenvironment
Create a folder for the application that comprises of a neat copy of Python,
 Run:
sudo virtualenv ~/myvirtualenvironment/myNewApp
Chnage the directory to the project and activate the virtual environment.
cd ~/myvirtualenvironment/myNewApp/bin
Activate the environment:
source activate
Note: The prompt of the shell will be changed to signify the active virtual environment. 
To exit the python virtualenv just run “deactivate” command.

Installing a package in active Virtualenv

 

Looking at the bin directory in our virtualenv, we will see easy_install which
is modified to put all the packages in the virtualenv’s site-packages 
directory.

To install an app in the Virtualenv, we may run:
pip install flask
We don't  use sudo since the files being installed are installed in the virtualenv

Thanks

 

Using PM2 to Restart a Job Following System Reboot

Server crash is developer's nightmare, we worry every moment that our server might fail and we in any position are forced to login via SSH into the system to re-start the jobs. Fortunately, The one using PM2 modules are lucky enough to have an effective solution for it.

PM2 comes with a default feature to create startup scripts for multiple initialized systems. These startup-scripts are executed whenever a system is booted which in turn restarts the PM2 process itself. This PM2 process restarts the listed jobs and helps in 
resumption of the applications running on the server.

User may create a startup-script by using PM2 auto-detection feature else he can even pass a particular initialization system name to the 
startup command. If a user is unaware of 
init system, then he may just execute pm2 startup command via command line without passing any arguments and let PM2 auto-detect.

pm2 startup  
# or
pm2 startup <init-system>  
# <init-system> is one of these options

The startup command will produce an output which is a command. The command needs to be executed with root permissions on the system via command-line.

$ pm2 startup
[PM2] Writing startup script in /etc/init.d/pm2-init.sh
[PM2] Making script booting at startup...
[PM2] -ubuntu- Using the command:
      su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"

Execute the generated command to daemonize PM2 and generate the system’s init script which is executed on boot.

su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"

This will produce the output.

Platform ubuntu  
Template  
#!/bin/bash
…
[PM2] Writing init configuration in /etc/init.d/pm2
[PM2] Making script booting at startup...
…
[DONE]
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save

Start Node.js Application

Thereafter, we need to start our application and save it with the start-up

$ pm2 start node app.js
[PM2] Starting server.js in fork_mode (1 instance)
[PM2] Done.
---------------------------------------------------------------------------------------------------
? App name ? id ? mode ? pid  ? status ? restart ? uptime ? cpu ? memory     ? watching ?
---------------------------------------------------------------------------------------------------
? node app.js   ? 0  ? fork ? 2065 ? online ? 0       ? 0s     ? 22% ? 6.664 MB   ? disabled

Saving Processes to Restart on System Boot

The last simply involves saving the jobs to the start-up script and is done using the following command.

$ pm2 save

Thanks

Converting CSV file into an Array in PHP

This Blog helps to illustrate the method to import CSV file into an associative PHP array. PHP uses fgetcsv function for this specific purpose. The array created is associative which helps in accessing the value by the column field heading at the top of the CSV file.

The PHP fgetcsv function imports and reads the CSV file into an associative array on the basis of the column heading in the first row. To use it, we can call the function with an appropriate file as a parameter. The function after execution outputs an associative array containing imported .csv file data.

Note:  Imported CSV must possess first row as column headings as it is used to generate the associative array elements.

Read CSV using PHP

<?php
 
function ImportCSV2Array($filename)
{
    $row = 0;
    $col = 0;
 
    $handle = @fopen($filename, "r");
    if ($handle) 
    {
        while (($row = fgetcsv($handle, 4096)) !== false) 
        {
            if (empty($fields)) 
            {
                $fields = $row;
                continue;
            }
 
            foreach ($row as $k=>$value) 
            {
                $results[$col][$fields[$k]] = $value;
            }
            $col++;
            unset($row);
        }
        if (!feof($handle)) 
        {
            echo "Error: unexpected fgets() failn";
        }
        fclose($handle);
    }
 
    return $results;
}

Example

<?php
 
$filename = "demo.csv";
$csvArray = ImportCSV2Array($filename)
 
foreach ($csvArray as $row)
{
    echo $row['column1'];
    echo $row['column2'];
    echo $row['column3'];
}

Explanation?

The function reads each and every line of the CSV file using fgetcsv function. This function renders the line for fields in CSV format to return an associative array possessing the required data. The array has the first item at 0th location, second at 1st and process continues.

The initial row of data acts like the headings, thereafter a loop iterates over each element of array from fgetcsv and enters it for each column heading.The associative array is useful because it eliminates indexes which otherwise often confuse and are hard to remember for any specific field(column).

Thanks

Using Screen to Retain SSH Sessions a Process after Disconnection

Secure Shell widely know as SSH in layman terms is a process through which a user can login to another use the server residing on another machine through command line. The Login basically generates an artificial or pseudo terminal window and binds it to the logged in user shell.

The problem which is often encountered with SSH is as soon as the session is killed/terminated, a SIGHUP signal is sent to the pseudo-terminal created. The SIGHUP signal leads to killing of all the active processes initiated through the pseudo-terminal. Developers generally struggle to cope with this and often seek for a definate solution for it. This is where "Screen" come to our rescue.

Screen
 is a terminal multiplexer which enables user to manage multiple terminal sessions simultaneously, toggle in between sessions, and even retaining the session at any moment we require without a concern about the session being terminated. Screen can be initiated and detached from the parent window leaving it running in background and then restart at any time.

Installation

Screen can be installed in ubuntu using a pretty simple step which involves writing just a simple on line command in the terminal.

apt-get install screen

Starting a Screen

After typing ‘screen’ command, you will be in a new screen session, within this session you can create new windows, traverse between windows, lock the screen, and do many more stuff which you can do on a normal terminal.

$ screen

The new screen can then be used to run our processes which were terminated on ssh session termination.


Screen Detaching

What if we want to come back to our main login terminal to perform other functions. This is where we can use detach feature of the screen. The detach feature enables us to get back to the main terminal keeping the screen alive by making it an Daemon process.
To detach a screen from terminal,  user just has to press “Ctrl+a”  followed by “d” and he will be detached and sent to the terminal flashing a message about Screen being detached. User can safely terminate the SSH session and the screen terminal will remian alive.

 

Resuming Screen

Resuming a detached screen session is fairly easy, user has to just re-login to remote terminal again via SSH and type “screen -r” , The "r" flag in this case will open the remote screen terminals once again.

$ screen -r

Thanks,

Banner

Don't just hire talent,
But build your dream team

Our experience in providing the best talents in accordance with diverse industry demands sets us apart from the rest. Hire a dedicated team of experts to build & scale your project, achieve delivery excellence, and maximize your returns. Rest assured, we will help you start and launch your project, your way – with full trust and transparency!