Start with react — React starter kit

Reactjs is one of the powerful library for building user interfaces.

Let’s start with reactjs project.

To start with reactjs I created a react-starter-kit which can be downloaded from github.

In this starter kit, I am using following modules.
Nodejs — Node server
Expressjs — Express framework
Reactjs — React as view layer
React-router — For routing the application
Eslint — For best practices.
Webpack — For bundling

First, we have to clone this repo.

git clone https://github.com/shabeeb/react-starter-kit
once it cloned we have to move to that directory
cd react-starter-kit
Then we have to install all depentency modules. dont worry below commands will do it.
npm install
Now our sample reactjs project is ready,
We can run development server using below command
npm run dev

Now go to the editor and change something in src/components/home.js and see the browser again, react-hot-loader will reload the page.

To run production build
npm run build
it will minify all the js/jsx code and save to build/bundle.js file
npm start or npm run start
will start server with production version.

You can remove the strict code check (best practices ) by removing below lines (line 25 to 30) of code from webpack.config.js
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},

727 total views, 5 views today

Common git commands

Here is a list of commonly used git commands

  • Initiate a directory as git
git init --bare
  • Git clone
git clone url-to-git

example URL :user@domain.com:/home-path/username/directory/
  • Git status

it will show the files status – modified, tracking , untracked

git status
  • Git Add for tracking
git add filename
or 
git add .
dot is using to add all files

  • Git commit
git commit -m "commit message"

If the file is under git track we can combine both comments in one line like

git commit -am "your-message"
or
git  commit -a -m "your-message"

-a to add
-m to commit message
  • Push your changes to server
git push

or 
git push branch
  • Creating  branch in git
git branch  branch-name 
  • Switch to branch
git checkout branch-name
  • Create a new branch and switch to new branch
git checkout -b branch name
  • List all the branches
git branch -a
  • Merge Branch

Consider we have master branch A and another branch B,

To merge branch B changes to branch A,

git checkout branch A
git merge branch B

if any conflict happened, it will show conflict, we have to do modification and commit again.

  • Delete a branch
git branch -d <brach name>

this will delete if all the changes are merged, if you want to use force delete , even not merged,

git branch -D <branch name>
  • Upload branch into server at setting head for push
git push --set-upstream origin <branch name>
  • Stash all local changes
git stash
  • Take back stashed changes – This will take aback all the changes you stashed
git stash pop
  • Discard changes on one file
git checkout filename
  • Remove local commit  and reset to server head –  it will delete all the local changes
git reset --hard origin/branch name
  • List all the branches push/pull remote origin.

This will show all the remote and local branches and where it is pointing into

git remote show origin
  • Fetch and push origin list
git remote  -v
  • View uncommitted changes made
 git diff
  • To see all the logs
git log
  • To see log with difference
git log -p
  • Git log for a single file
git log -p file/path
-p will give changes also
  • Other options with git log
 git log --stat    //this will show only number of files changed and number of changes
git log --pretty=oneline    //show all the changes in one line with head and comment
git log --pretty=format:"%h - %an, %ar : %s"   //show with name time and commit message

git log --author=username  //show only one user commit

 


 

 

4,391 total views, 7 views today

lazy scroll – infinite scrolling angularjs plugin

What is lazy scrolling?

lazy-scroll is an angularjs directive for infinite scrolling. Instead of click pagination links or going to next page , this will help to load data on scrolling like you see in Facebook. lazy-scroll will work even without jquery .

Download lazy-scroll

minified version      |     uncompressed version 

What you have to do to implement on angularjs project?

lazy-scroll is a simple directive for angularjs application. We just have to call the function which you want to call for pagination in lazy-scroll attribute.

It will magically load data and append into variable when user reaches bottom of the page. There are also API’s available to control the behavior.

Just see some demo samples.

 Check out some Demo

Demo with explanation can see here

How do I use in my project?

You can download the minified version   or you can use the cdn and follow the 3 simple steps below:

STEP 1 :

Add ascript at the bottom of the page after angularjs

<script src="path-to-script/angularjs.min.js"></script>
<script src="path-to-script/lazy-scroll.min.js"></script>
STEP 2:

Ensure that your application module specifies lazy-scroll as a dependency.

var app = angular.module("yourModule",['lazy-scroll']);
STEP 3:

Use the directive by specifying a lazy-scroll attribute on an element.

<div lazy-scroll="paginationFuntion()" lazy-scroll-trigger="80" >

That is it  and it will work like a magic!

What is next?

Check our API  here 

See some demo and implement 🙂

4 total views, no views today

promises and call back

promises and call back are only doing similar job,  but sometimes we have to think whether to have a callback function or promises.

Here we will be discussing about promises and call back function. So let have look on both callback function and promises and how it works.

Call back function

Callback functions are functions that are executed after completing one function.

For example, if we have to do something after getting the result from the server, then we can write a call back function and it will execute once it gets the result from the server.

Let us have a look on the below example:

function first(arg1, callback){
//do some code
//after that call back funtion will be callled
if(type of callback ==function ) 
callback(options);

}

 

promises

Promise is just a way of writing asynchronous code in a more synchronous fashion.
ie, When you call promises, it will return a promise value and the calling code will wait until the promise is full filled, before executing next.

angularjs promises example:

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
 //then(successCallback, errorCallback, notifyCallback)

We can pass three parameters for ".then" function, of which one is on success, 
another one on failure and last one is notifyCallback .notifyCallback can be 
called more than one time to the show progress and it is an optional parameter.

 Some differences between call back promises

  • Call back can be called once or more than once (depends on how it is written).
  • Promises will be called only once
  • Call back can throw errors and exceptions (have to write more call back for errors)
  • Promises have error handling
  • then(fulfilledHandler, errorHandler, progressHandler)
  • No states in call back
  • May have one of 3 states: unfulfilled, fulfilled and failed or only move from unfulfilled to either fulfilled or failed
  • In call back we can call N function in N levels
  • Can write a sequence of N async calls without N levels of indentation

These are some of my view points, if you have any suggestions or addons, you comments are welcome.

28,685 total views, 232 views today

Simple web server using nodejs

We can make a folder just like a web server using nodejs for quick jobs

First we can install connect and expressjs, serve-static with Node.js:

$ npm install connect serve-static

We can make .js file (serve.js) and write the below code in that file:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);

Then in cmd, run this file:

$ node server.js

Now we can access the local server in URL:

 http://localhost:8080/myfiles.html

And can exit by pressing:

ctrl+c

1,549 total views, 3 views today

Cross-Origin Request block issue fix

Sometime we have to request files from different host using ajax, and it may create problem because of CORS polices.

CORS means Cross-Origin Resource Sharing (CORS).

Cross domain request will be block by most of the browsers due to same-origin security policy. so we have to enable CORS on our server.we can do this by setting
Access-Control-Allow-Origin in a PHP with changing server.

if we need to allow a request from a perticular domain we can restrict as below

 

header('Access-Control-Allow-Origin: http://www.example.com');

 

or we can allow from all sites

 

header('Access-Control-Allow-Origin: *');

3,194 total views, 13 views today

Clear your form using Javascript

If you need to clear all the input fields irrespective of type in a form, try the below code.  The below code works even if your fields contains place holders.

    $.fn.clearForm = function() {
      return this.each(function() {
        $(':input', this).each(function() {
          var type = this.type, tag = this.tagName.toLowerCase();
          if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
          else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
          else if (tag == 'select')
            this.selectedIndex = -1;
        });
      });
    };

 

729 total views, 3 views today

Replace all special character from a string

Hi,
Here is a function which will replace all special character from a string.

We can write a regx to check all character number ,space and – , and we can replace everything with –

[^A-Za-z0-9\- ]

Below is sample for how to replace all special character from a string using regx

$variable = "word";
preg_replace('/[^A-Za-z0-9\- ]/', '-', $variable);

Hope it will help some one

1,628 total views, 3 views today

Random unique alphanumeric string

HI gays ,

Here is a function to generate random unique alphanumeric string using PHP,

I am sure it will help some one to solve their problem

  function get_rand_txn_id($length = 10) {


        $randstring = '';
        $string_array = array_merge(range(0, 9), range('a', 'z'), range('A', 'Zå'));

        for ($i = 0; $i < $length; $i++) {
            $randstring .= $string_array[array_rand($string_array)];
        }

        return $randstring;
    }

 

 

 

 

 

6,580 total views, 25 views today

Helper classess in laravel

      In most case, we want to extend our Laravel applications capabilities by adding helper class.
It is not a best practice to insert this classess inside Controller and Model.

so we have to write our classess in separate files and group it by folder

Here let us have a look how we add helper classess in laravel

1.    We have app folder on root folder of laravel.There we can create a Libraries folder inside app folder.

2.  We can create a class/helper file and we can write a our custom class there, on the top of custom class we have to define namespace our_folder_name;




 

namespace our_folder_name

for example ,

 
//here my folder name is Libraries
namespace Libraries;

class className{
    
    //class methodes
    
}

Now we can go to our controller and on top we can include our helper class

use Libraries\filename as filename;

And we can go to compser, inside autoloder we can add “app/foldername”

app/foldername

 

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/tests/TestCase.php",
 			"app/Libraries",// we've added classes folder on compose
		]
	},

 




And we can update composer by using below comment

 composer dump

Now we can use our helper class in our controller

  $test = new className();

All my samples files are given below
Library/className.php

<?php
 namespace Libraries;

class className{
    
    //class methodes
    
    function testmesthode(){
        
        return "Hello world";
    }
    
}

testController.php

<?php

use Libraries\className as className;

class testController extends BaseController {
    
    
    function index(){
        
        $test = new className();
        echo $test->testmesthode();

    }
    
}

compser file

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/tests/TestCase.php",
 			"app/Libraries",// we've added classes folder on Laravel ClassLoader
		]
	},



1,486 total views, 3 views today

© 2017 shabeeb Blog

Theme by Anders NorénUp ↑