Ajax and XMLHttpRequest

Ajax – an acronym for Asynchronous JavaScript and XML)[1] is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required; JSON is often used instead (see AJAJ), and the requests do not need to be asynchronous.

Technologies involved:
HTML (or XHTML) and CSS for presentation
The Document Object Model (DOM) for dynamic display of and interaction with data
XML for the interchange of data, and XSLT for its manipulation
The XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together

XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script. All browsers supports XMLHttpRequest.

typical use:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

With Jquery :

$('#main-menu a').click(function(event) {
   event.preventDefault();
 
   $.ajax(this.href, {
      success: function(data) {
         $('#main').html($(data).find('#main *'));
         $('#notification-bar').text('The page has been successfully loaded');
      },
      error: function() {
         $('#notification-bar').text('An error occurred');
      }
   });
});

Interfaces and Abstract Class

Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined.

I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.

One thing to remember is that any given class can “inherit” (technically implement) many interfaces but only one sub-class (be that abstract or not).

Interface is a contract whereas Abstract Class is actually a class. Objects cannot be instantiated in either Interface or Abstract Classes.

PHP interfaces can have constants, but not properties (instance variables). If you don’t need to modify your “property”, you can use a constant instead.

For interfaces also talk about “extending” interfaces and “multiple interface inheritance”

Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature – they cannot define the implementation.

– Abstract classes can have consts, members, method stubs and defined methods, whereas interfaces can only have consts and methods stubs.
– Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
– When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don’t have to be defined.
– A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces. Abstract class can extend another abstract class though.
– A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

Abstract Class vs Interface in PHP

Abstract Class

abstract class Animal { 
  function greeting() { 
    $sound = $this->sound();      // exists in child class by contract 
    return strtoupper($sound); 
  } 
  abstract function sound();      // this is the contract 
} 
class Dog extends Animal { 
  function sound() {              // concrete implementation is mandatory 
    return "Woof!"; 
  } 
}

Interface

interface animal {
function breath();
function eat();
}
Note: the interface’s functions/methods cannot have the details/guts filled in – that is left to the class that uses the interface.
Example of a class using an interface:
class dog implements animal{
function bark() {
echo “yap, yap, yap …”;
}
/* the interface methods/functions must be implemented (given their ‘guts’) in the class */
function breath() { echo “dog is breathing …”;}
function eat() { echo “dog is easting …”;}
}

Database Normalization

Normalization is a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics like Insertion, Update and Deletion Anamolies. It is a multi-step process that puts data into tabular form by removing duplicated data from the relation tables.

Database normalization is the process of organizing the fields and tables of a relational database to minimize redundancy. Normalization usually involves dividing large tables into smaller tables and defining relationships between them. It also deals with the insertion, update and deletion anomalies.

First Normal Form:
Deals with atomicity. Columns should not have multiple values.

Student       Age      Subject 
Adam          15       Biology, Maths 
Alex          14       Maths

Second Normal Form:
Removes partial dependency.
a table is in 2NF if and only if it is in 1NF and no non-prime attribute is dependent on any proper subset of any candidate key of the table.

As per the Second Normal Form there must not be any partial dependency of any column on primary key. It means that for a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence. If any column depends only on one part of the concatenated key, then the table fails Second normal form.

Student    Age    Subject 
Adam       15     Biology 
Adam       15     Maths 
Alex       14     Maths 

Candidate Key is {Student, Subject}. Age is dependent only on Student.

Third Normal Form:
Removes transitive dependency. Table is in 3NF if
– It is in second normal form
– There is no transitive functional dependency
By transitive functional dependency, we mean we have the following relationships in the table: A is functionally dependent on B, and B is functionally dependent on C. In this case, C is transitively dependent on A via B

Student_id    Student_name  Student_DOB Student_Zip  City State 

Student Zip is dependent on Student_id and City / State are dependent on Zip.

BCNF (Boyce Codd Normal Form):
– Strict form of 3NF

Fourth Normal Form:
-Under fourth normal form, a record type should not contain two or more independent multi-valued facts about an entity. In addition, the record must satisfy third normal form.

Consider employees, skills, and languages, where an employee may have several skills and several languages. We have here two many-to-many relationships, one between employees and skills, and one between employees and languages. Under fourth normal form, these two relationships should not be represented in a single record such as

——————————-
| EMPLOYEE | SKILL | LANGUAGE |
===============================

Fifth Normal Form:

http://www.studytonight.com/dbms/database-normalization.php

Sharding

Sharding is the equivalent of “horizontal partitioning”. When you shard a database, you create replica’s of the schema, and then divide what data is stored in each shard based on a shard key. For example, I might shard my customer database using CustomerId as a shard key – I’d store ranges 0-10000 in one shard and 10001-20000 in a different shard. When choosing a shard key, the DBA will typically look at data-access patterns and space issues to ensure that they are distributing load and space across shards evenly.

?”Vertical partitioning” is the act of splitting up the data stored in one entity into multiple entities – again for space and performance reasons. For example, a customer might only have one billing address, yet I might choose to put the billing address information into a separate table with a CustomerId reference so that I have the flexibility to move that information into a separate database, or different security context, etc.

To summarize – partitioning is a generic term that just means dividing your logical entities into different physical entities for performance, availability, or some other purpose. “Horizontal partitioning”, or sharding, is replicating the schema, and then dividing the data based on a shard key. “Vertical partitioning” involves dividing up the schema (and the data goes along for the ride).

MySQL Cluster vs MySQL Replication

MySQL currently supports two different solutions for creating a high availability environment and achieving multi-server scalability.

MySQL Replication
The first form is replication, which MySQL has supported since MySQL version 3.23. Replication in MySQL is currently implemented as an asyncronous master-slave setup that uses a logical log-shipping backend.
A master-slave setup means that one server is designated to act as the master. It is then required to receive all of the write queries. The master then executes and logs the queries, which is then shipped to the slave to execute and hence to keep the same data across all of the replication members.
Replication is asyncronous, which means that the slave server is not guaranteed to have the data when the master performs the change. Normally, replication will be as real-time as possible. However, there is no guarantee about the time required for the change to propagate to the slave.
Replication can be used for many reasons. Some of the more common reasons include scalability, server failover, and for backup solutions.
Scalability can be achieved due to the fact that you can now do can do SELECT queries across any of the slaves. Write statements however are not improved generally due to the fact that writes have to occur on each of the replication member.
Failover can be implemented fairly easily using an external monitoring utility that uses a heartbeat or similar mechanism to detect the failure of a master server. MySQL does not currently do automatic failover as the logic is generally very application dependent. Keep in mind that due to the fact that replication is asynchronous that it is possible that not all of the changes done on the master will have propagated to the slave.

MySQL Cluster
MySQL Cluster is a shared nothing, distributed, partitioning system that uses synchronous replication and automatic sharding in order to maintain high availability and performance.
MySQL Cluster is implemented through a separate storage engine called NDB Cluster. This storage engine will automatically partition data across a number of data nodes. The automatic partitioning of data allows for parallelization of queries that are executed. Both reads and writes can be scaled in this fashion since the writes can be distributed across many nodes.
Internally, MySQL Cluster also uses synchronous replication in order to remove any single point of failure from the system. Since two or more nodes are always guaranteed to have the data fragment, at least one node can fail without any impact on running transactions. Failure detection is automatically handled with the dead node being removed transparent to the application. Upon node restart, it will automatically be re-integrated into the cluster and begin handling requests as soon as possible.

A shared nothing architecture (SN) is a distributed computing architecture in which each node is independent and self-sufficient, and there is no single point of contention across the system

Storage Engines for MySQL Tables

MySQL provides various storage engines for its tables as below:

MyISAM
InnoDB
MERGE
MEMORY (HEAP)
ARCHIVE
CSV
FEDERATED
NDB
EXAMPLE
BLACKHOLE

Each storage engine has its own advantages and disadvantages. It is crucial to understand each storage engine features and choose the most appropriate one for your tables to maximize the performance of the database. In the following sections we will discuss about each storage engine and its features so that you can decide which one to use.

MyISAM

MyISAM extends the former ISAM storage engine. The MyISAM tables are optimized for compression an speed. MyISAM tables are also portable between platforms and OSes.

The size of MyISAM table can be up to 256TB, which is huge. In addition, MyISAM tables can be compressed into read-only tables to save space. At startup, MySQL checks MyISAM tables for corruption and even repair them in case of errors. The MyISAM tables are not transaction-safe.

Before MySQL version 5.5, MyISAM is the default storage engine when you create a table without explicitly specify the storage engine. From version 5.5, MySQL uses InnoDB as the default storage engine.

InnoDB

The InnoDB tables fully support ACID-compliant and transactions. They are also very optimal for performance. InnoDB table supports foreign keys, commit, rollback, roll-and forward operations. The size of the InnoDB table can be up to 64TB.

Like MyISAM, the InnoDB tables are portable between different platforms and OSes. MySQL also checks and repair InnoDB tables, if necessary, at startup.

MERGE

A MERGE table is a virtual table that combines multiple MyISAM tables, which has similar structure, into one table. The MERGE storage engine is also known as the MRG_MyISAM engine. The MERGE table does not have its own indexes; it uses indexes of the component tables instead.

Using MERGE table, you can speed up performance in joining multiple tables. MySQL only allows you to perform SELECT, DELETE, UPDATE and INSERT operations on the MERGE tables. If you use DROP TABLE statement on a MERGE table, only MERGE specification is removed. The underlying tables will not be affected.

Memory

The memory tables are stored in memory and used hash indexes so that they are faster than MyISAM tables. The lifetime of the data of the memory tables depends on the up time of the database server. The memory storage engine is formerly known as HEAP.

Archive

The archive storage engine allows you to store a large number of records, which for archiving purpose, into a compressed format to save disk space. The archive storage engine compresses a record when it is inserted and decompress it using zlib library as it is read.

The archive tables only allow INSERT and SELECT commands. The archive tables do not support indexes, so reading records requires a full table scanning.

CSV

The CSV storage engine stores data in comma-separated values file format. A CSV table brings a convenient way to migrate data into non-SQL applications such as spreadsheet software.

CSV table does not support NULL data type and read operation requires a full table scan.

FEDERATED

The FEDERATED storage engine allows you to manage data from a remote MySQL server without using cluster or replication technology. The local federated table stores no data. When you query data from a local federated table, the data is pull automatically from the remote federated tables.

NDB
This clustered database engine is particularly suited for applications that require the highest possible degree of uptime and availability.

BLACKHOLE
The Blackhole storage engine accepts but does not store data and retrievals always return an empty set. Useful for testing.

EXAMPLE
The Example storage engine is “stub” engine that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them.

Javascript Questions Set4

Global Variables:
The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable.

Types in Javascript:
JavaScript is a loosely-typed language (some call this weakly typed); this means that no type declarations are required when variables are created. Strings and numbers can be intermixed with no worries. JavaScript is smart, so it easily determines what the type should be. The types supported in JavaScript are: Number, String, Boolean, Function, Object, Null, and Undefined.

What does “this” refer to in Javascript?
In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack.

Every line of JavaScript code is run in an “execution context.” The JavaScript runtime environment maintains a stack of these contexts, and the top execution context on this stack is the one that’s actively running.

There are three types of executable code: Global code, function code, and eval code. Roughly speaking, global code is code at the top level of your program that’s not inside any functions, function code is code that’s inside the body of a function, and eval code is global code evaluated by a call to eval.

The object that this refers to is redetermined every time control enters a new execution context and remains fixed until control shifts to a different context. The value of this is dependent upon two things: The type of code being executed (i.e., global, function, or eval) and the caller of that code.

That’s it! You can figure out what object this refers to by following a few simple rules:

– By default, this refers to the global object.
– When a function is called as a property on a parent object, this refers to the parent object inside that function.
– When a function is called with the new operator, this refers to the newly created object inside that function.
– When a function is called using call or apply, this refers to the first argument passed to call or apply. If the first argument is null or not an object, this refers to the global object.

Why to use call and apply instead of calling a function directly ?
You use call or apply when you want to pass a different this value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call expects parameters separated by commas, while apply expects parameters in an array.

Sorting Algorithms

1) Merge Sort

– O(n log n) comparison based sorting algorithm (best case, worst case, avg case)
– Produces a stable sort (implementation preserves the input order of equal elements in the sorted output)
– Top Down Implementation and Bottom Up Implementation
– Is more efficient at handling slow-to-access sequential media. Merge sort is often the best choice for sorting a linked list
– Uses more memory (2n locations)
– Can be parallelized

2) Quick Sort
– Avg O(n log n) , Worst Case O(n ^ 2)
– Is comparison based sorting
– In place partioning algorithm and hence uses O(log n) additional space
– Can be parallelized (like mergesort)
– Depending on implementation may or may not be a stable sort
– Low memory required
– Useful in cases where data is in RAM, not useful in cases where data lives on disk (In that case use merge sort)
– usually faster than mergesort
– The worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk

QuickSort is more popular than Merge Sort because it:

Is in-place (MergeSort requires tons of extra memory).
Has a small hidden constant

3) Heap Sort

– Heapsort is part of the selection sort family. Is a comparison based sorting algo.
– it has the advantage of a more favorable worst-case O(n log n) runtime
– Heapsort is an in-place algorithm, but it is not a stable sort
– Quicksort is typically faster than Heapsort, but the worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk
– Merge sort requires ?(n) auxiliary space, but heapsort requires only a constant amount.

Merge sort has several advantages over heapsort:
Merge sort on arrays has considerably better data cache performance, often outperforming heapsort on modern desktop computers because merge sort frequently accesses contiguous memory locations (good locality of reference); heapsort references are spread throughout the heap.
Heapsort is not a stable sort; merge sort is stable.
Merge sort parallelizes well and can achieve close to linear speedup with a trivial implementation; heapsort is not an obvious candidate for a parallel algorithm.
4) Intro Sort

Must Know Algorithms

As per Cracking the Coding Interview:

Data Structures
Linked Lists
Binary Trees
Tries
Stacks
Queues
Vectors/ArrayLists
Hash Tables

Algorithms
Breadth First Search
Depth First Search
Binary Search
Merge Sort
Quick Sort
Tree Insert/Find/etc

Concepts
Bit Manipulation
Singleton Design Pattern
Factory Design Pattern
Memory (Stack vs Heap)
Recursion
Big-O Time