Tuesday, September 11, 2018

How scope behaves in JS (let, block scope)


scope refers to the lifecycle of the variable, ie, where in the code its visible and how long

Understand "What is not a block scope"
curly braces doesnt mean block scope,
{
 // its not a block scope, but a global scope
 var a = "mytest"
}
console.log(a) // prints mytest

var a inside block overrides var a in function scope, so not a block scope

function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    var a = "override";
  }
  console.log(a)
  // prints "override" as said the curly braces don't signify block scope.
}


So how to declare block scope variable ?
ImmediatelyInvokedFunctionExpression (IIFE)


(function () {
  var a = "correct block scope";
})()

ie, the above myfun becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    (function () {
      var a = "right block scope";
    })()
  }
  console.log(a) // prints "function scope" .
  // because variable a inside IIFE is in block scope.
}

With ES6 we have "let" keyword, use inplace of "var" keyword. This creates a variable with block level scope. So myFunc becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    let a = "right block scope";
  }
  console.log(a) // prints "function scope" .
}

var a is only visible between the for-loop and not outside the loop

Ex:

var myFuncArray = [];
for (let i = 0; i < 5; i++) {
  myFuncArray.push(function(){
    console.log(i);
  })
}

myFuncArray.forEach((myfun) => {
  myfun(); //prints 0...4
});

for more JS quirks click here...

Thursday, July 07, 2016

Crossing the CORS

Cross Origin Resource Sharing by which you let others to access the api's hosted on your domain. 
Below (nginx) example adds the headers to default.conf file
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With, accept, content-type';
Below are few links that I used for my reference.
Any client side Javascript can make calls to other website which has the above rule set. Be careful while setting  Access-Control-Allow-Origin to '*', as this allows anyone to hit your api/website

Tuesday, May 07, 2013

How to use SQLite Db in the Android Development


SQLite is a self-contained i.e., having all the modules and dependencies with in it & does not depend much on external libraries. This is one of the important reasons why most of the embedded devices use SQLite as temporary storage. Well-known examples are Google, Mozilla Firefox, Apple, Adobe and Android devices. It has zero-configuration with out any separate process for installation or configuration.

Android has 2 main packages, which lets us to use SQLite in the application. android.database and android.database.sqllite has all the necessary api's for create/read/update and delete actions.
Also SQLiteOpenHelper class provides public methods like onCreate, onUpgrade, onOpen methods. onCreate is called whenever the database is created for first time, onOpen when the DB has been opened and onUpgrade when the databased needs to be upgraded.

A database handler class which implements the SQLiteOpenHelper should call the constructor to create helper object to create, open or manage database. Constructor takes database name & database version. See below.

public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

As a first step to implement SQLite, the database handler class should extend SQLiteOpenHelper. In the constructor method call the super() method by passing the context, database name and version.

         public DatabaseHandler(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
         }

Database handler class should also implement the onCreate & onUpgrade methods. onCreate method is called by framework when the DB is created for the first time and onUpgrade method is used whenever DB tables need to be updated.
ex:
         public void onCreate(SQLiteDatabase db) {
                  // Category table create query
                  String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
                  db.execSQL(CREATE_CATEGORIES_TABLE);
         }

// Upgrading database
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                  // Drop older table if existed
                  db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
                  // Create tables again
                  onCreate(db);
         }

For any read/write operation, SQLiteOpenHelper class provides getReadableDatabase() & getWritableDatabase() respectively. These methods returns reference to SQLiteDatabase object which can be used to create, read, update and delete from tables. For ex, below example shows Create/Open database.

         SQLiteDatabase db = this.getReadableDatabase();

         // Create/open a database for read/write operation.
         SQLiteDatabase db = this.getWritableDatabase();

The db object returned from the getReadableDatabase & getWritableDatabase provides create(), insert(), delete(), update() methods.
         Ex: insert takes table name, optional null column and content values that need to be inserted into the table.
         // Inserting Row
                  db.insert(TABLE_LABELS, null, values);

We can write query in 2 ways, First is raw query like "select * from ", "insert into" etc. and second one is structured query. For this SQLiteDatabase provides 2 methods query() & rawQuery().

query() methods provides structured interface which takes table name, array of columns that needs to be fetched, filter column (for WHERE clause), groupBy, orderBy, having and limit. Example below.

         db.query(TABLE_NAME, String[] columnNames, String[] selection, group by, having, order by);

rawQuery() takes the raw sql just like any sql database. ex
         db.rawQuery("select * from TABLE_NAME", null);

Both query() & rawQuery() returns something called Cursor object. Cursor is not actual result set; rather it is an object that is positioned before the first row of the result set. The handler class should iterate through the cursor object to get through all rows.
ex:
                  Cursor cursor = db.rawQuery(selectQuery, null);
                  // Looping through all rows and adding to list
                  if (cursor.moveToFirst()) {
                           do {
                                    cursor.getString(1);
                           } while (cursor.moveToNext());
                  }
Cursor.get*(), methods are the way to access columns of each rows.

All the above methods insert(), read(), delete() etc. should implement close() method to close db & cursor operations.

                  // closing connection
                  cursor.close();
                  db.close();

Reference materials:

Friday, April 19, 2013

CSS Specificity

Many times wondered in which order the styles are applied to document elements. When you are working on a bigger project or old projects which was written by ex-developers (no offense here) wondered how to over write a particular style or write a style so it has the higher precedence over other style.
We have more ways to add styles to a documents inline Style & external Style both containing

  •  Id (#) selector, 
  • class (.) selector, 
  • attribute selector (input[type=password]),
  • pseudo-classes (:link, :hover:, :visited, :focus, :active) , 
  • pseudo-elements (:before, :after, :first-line, :first-letter, :first-child)


All the above mentioned style have a rating/priority which is used while style the document.
ex: As we know  Id (#) selector has precedence over any other selection since ID is unique in a document and obviously they have the highest rating. Any style (inline or external) given using the ID is considered before class, pseudo elements.
ie, with inline style like below

  1. <style> #test {  text-decoration:"line-through"; }</style> 
  2. <a id="test" style="text-decoration:line-through;">Test</a>

has the higher specificity that any other style given to the above element.
similarly while considering external stylesheet, the first style (1) has the higher specificity that (2).

Example 1- a#test {  text-decoration:"line-through"; }
Example 2-  a[id=test] { text-decoration:"none"; }

How is the specificity calculated.
  1. # (id) selector takes 100 points 
  2. . (class, attribute, pseudo) selectors take 10 points
  3. type selector, pseudo-element selector take 1 points.
Considering the above example (1 & 2) we can easily say that example 1 style is always selected over example 2. Having said that, there is always some thing beyond the above 3. That is the inline style. Irrespective of any thing, the style attribute takes higher precedence/specificity over any thing (ie it has value 1000 points).





Wednesday, June 27, 2012

How to develop an IPhone Location App


You can say the continuation to my prev article on how to use the HTML5 GeoLocation api, but its different this time. It uses Objective C to get the location details rather than using HTML5.

Is building IOS App easy ?

I asked my self this question many times with out knowing how easy it is  before I attended the work shop conducted by Dr.Barbara Hecker.

My 4th App (other than my 3 hello world app) I created this Location Detection app which detects your position and displays latitude & longitude on the iPhone screen.

All you need is  Xcode (I used Xcode Version 4.3.3), IOS 5 SDK, iPhone Simulator and little bit of scripting knowledge :)

For who know how to create an app this should be simple.

Create new project using a Single View Application. This will create a default ViewController Interface & Implementation class (ViewController.h and ViewController.m). Download the code from here

To implement the location interface all you need to know about is LocationManager in IOS. This CLLocationManage is the interface to deliver the location events. The main objective is to deliver event, create instance and attach a delegate (CLLocationManageDelegate) object to it.
For more info on LocationManager refer this link.

In this I used the below properties
1) delegate property for configuring the updates
2) startUpdatingLocation to start the updates 

Make sure you import CoreLocation library (Target > Build Phases > Add CoreLocation under Link binary with libraries. It took me quite a while to figure it out properly. If you get "undefined symbols for architecture i386 _OBJC_CLASS_$_CLLocationManager" don't be panic)

Cut to chase, below is the sample implementation details.

//  ViewController.h
#import
#import
@interface ViewController : UIViewController

<CLLocationManagerDelegate
{
    IBOutlet UITextField *latitudeText;
    IBOutlet UITextField *longitudeText;
    CLLocationManager *locMgr;
}

@property (retain,nonatomic) IBOutlet UITextField *latitudeText;
@property (retain,nonatomic) IBOutlet UITextField *longitudeText;

@property (weak, nonatomic) IBOutlet UIButton *locationDetect;

@end

Using the story board I added 2 text fields (for latitude & longitude) and control+click on the textFields and drag it to interface class. This will create property for each text fields like below

@property (retain,nonatomicIBOutlet UITextField *latitudeText;

Also I created button, which on click will get the location.

Below is my implementation class

//  ViewController.m
#import "ViewController.h"
@implementation ViewController

@synthesize latitudeText,longitudeText,locationDetect; 
CLLocationManager *locMgr;

......
- (void)viewDidLoad
{
    [super viewDidLoad];
    locMgr = [[CLLocationManager alloc]init];
    [locMgr startUpdatingLocation];
}

......

- (IBAction)locationDetect:(id)sender {
    NSString *latitudeTextData = [[NSString
                                   alloc]initWithFormat:@"%g",locMgr.location.coordinate.latitude];
    NSString *longitudeTextData =[[NSString alloc]
                                  initWithFormat:@"%g",locMgr.location.coordinate.longitude];
    self.latitudeText.text = latitudeTextData;
    self.longitudeText.text = longitudeTextData;
}

@end

In this I created a LocationManager object and started the location update process by using the startUpdatingLocation method.  Then capture the values from the location manager and update the text field.

Isn't quite simple ;)







Wednesday, April 18, 2012

GeoLocation API HTML5

Finding the user location with HTML5 GeoLocation API is quite simple. I have been experimenting Geo api, just sharing what I learned. Follow the reference given below for more understanding.

Geolocation can be obtained from navigator object like navigator.geolocation.

First step check whether your browser supports geolocation. If not fall back to native javascript.

if(navigator.geolocation)
else alert("your browser doesn't support geolocation")

geolocation object has 3 methods

  • getCurrentPosition
  • watchPosition
  • clearWatch


getCurrentPosition & watchPosition looks similar and takes same arguments.

ex:

navigator.geolocation.getCurrentPosition(success, error, {map of geolocation options});

success = function(position) {
position.coords.latitude ;
position.coords.longitude  ;
position.coords.accuracy;
};

failure = function(error) {
// 3 types of error

1: 'Permission denied',
2: 'Position is not available',
3: 'Request timeout'

};

Failure return error code  of 1,2,3.


The third argument for both getCurrentPosition and watchPosition is the geolocation options which is optional.
 1) enableHightAccuracy - takes boolean true/false, enables the device to get more accurate latitude & longitude positions
2) timeout - time allowed for the device to get the data. keep it zero will let the browser to never timeout (in milliseconds). Setting to 2000 will wait for 2000 milliseconds before it quits with REQUEST TIME OUT error code 3.
3) maximumAge - lets the browser to use the cached data. if set to zero will always look up new position for each request.

I have made a small demo which is still in work in progress.

Reference:
Geolocation API Specification
HTML5 By Bruce Lawson and Remy Sharp

Friday, April 06, 2012

Boolean Attribute vs Boolean Value

If you are writing some thing using HTML5 then you need to understand their Boolean Attributes which is not same as what you think as true or false.Thanks to the Boolean father George Boole

Boolean attribute doesn't need any value set as true or false,  require=required.
Then how to use Boolean Attribute in your HTML ?
just add this attribute and do not assign any value. What .. Yes, its up to you if you want to assign you can.

Lets see the below example.
< input type=text name="user" disabled / >

You can use disabled=disabled or disabled=true.  Both has same meaning or just keep it simple and use "disabled" as I said the very existence of them makes meaning KISS principle

List of HTML5 Boolean Attributes