Friday, 27 March 2015

Angularjs directive

a

directive in  module ng

Modifies the default behavior of the html A tag so that the default action is prevented when the href attribute is empty.
This change permits the easy creation of action links with the ngClick directive without changing the location or causing page reloads,


 e.g.: <a href="" ng-click="list.addItem()">Add Item</a>


form

  1. - directive in module ng
Directive that instantiates FormController.
If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of <form> elements, so Angular provides the ngForm directive which behaves identically to <form> but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

  • ng-valid is set if the form is valid.
  • ng-invalid is set if the form is invalid.
  • ng-pristine is set if the form is pristine.
  • ng-dirty is set if the form is dirty.
  • ng-submitted is set if the form was submitted.
Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.
For this reason, Angular prevents the default action (form submission to the server) unless the <form> element has an action attribute specified.
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
  • ngSubmit directive on the form element
  • ngClick directive on the first button or input field of type submit (input[type=submit])
To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives. This is because of the following form submission rules in the HTML specification:
  • If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
  • if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit
  • if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit)
Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated. Use ngSubmit to have access to the updated model.

Animation Hooks

Animations in ngForm are triggered when any of the associated CSS classes are added and removed. These classes are: .ng-pristine, .ng-dirty, .ng-invalid and .ng-valid as well as any other validations that are performed within the form. Animations in ngForm are similar to how they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well as JS animations.
The following example shows a simple way to utilize CSS transitions to style a form element that has been rendered as invalid after it has been validated:
//be sure to include ngAnimate as a module to hook into more
//advanced animations
.my-form {
  transition:0.5s linear all;
  background: white;
}
.my-form.ng-invalid {
  background: red;
  color:white;
}

Directive Info

  • This directive executes at priority level 0.

Usage

  • as element:
    <form
      [name=""]>
    ...
    </form>
     
     
     

    input

    1. - directive in module ng
    HTML input element control. When used together with ngModel, it provides data-binding, input state control, and validation. Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.

    Usage

    • as element:
      <input
        ng-model=""
        [name=""]
        [required=""]
        [ng-required=""]
        [ng-minlength=""]
        [ng-maxlength=""]
        [ng-pattern=""]
        [ng-change=""]
        [ng-trim=""]>
      ...
      </input>
       
       
       
       
      
      
      
      
      
      
      

      input[checkbox]

      1. - input in module ng
               HTML checkbox.

      Directive Info

    • This directive executes at priority level 0.

    Usage

    <input type="checkbox" ng-model="" [name=""] [ng-true-value=""] [ng-false-value=""] [ng-change=""]>
     
     

    input[date]

    1. - input in module ng
    Input with date validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 date format (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do not yet support this input type, it is important to provide cues to users on the expected input format via a placeholder or label.
    The model must always be a Date object, otherwise Angular will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.
    The timezone to be used to read/write the Date instance in the model can be defined using ngModelOptions. By default, this is the timezone of the browser.


     

    Usage

    <input type="date"
           ng-model=""
           [name=""]
           [min=""]
           [max=""]
           [required=""]
           [ng-required=""]
           [ng-change=""]>

     

Thursday, 12 March 2015

Git Basic and Tags

Initializing a Repository in an Existing Directory

git init

Cloning an Existing Repository

If you want to get a copy of an existing Git repository—for example, a project you’d like to
contribute to—the command you need is git clone
You clone a repository with git clone [URL]. For example, if you want to clone the Ruby
Git library called Grit, you can do so like this:

git clone git://github.com/sonam/grit.git


That creates a directory named grit,initializes a *git directory inside it, pulls down all
the data for that repository, and checks out a working copy of the latest version.

Recording Changes to the Repository


You have a bona fide Git repository and a checkout or working copy of the files for that project.
Remember that each file in your working directory can be in one of two states: tracked or
untracked. Tracked files are files that were in the last snapshot; they can be unmodified, modi-
fied, or staged. Untracked files are everything else—any files in your working directory that
were not in your last snapshot and are not in your staging area. When you first clone a repository,
all of your files will be tracked and unmodified because you just checked them out and haven’t
edited anything.



Checking the Status of Your Files

git status

Tracking New Files

git add [name of file]

Skipping the Staging Area


git commit -a -m "message"

Viewing the Commit History

After you have created several commits, or if you have cloned a repository with an existing
commit history, you’ll probably want to look back to see what has happened.

git log

or 

git log --stat

One of the more helpful options is -p  which shows the diff introduced in each commit.
You can also use -2 ,which limits the output to only the last two entries:

git log -p -2

Undoing Things

At any stage, you may want to undo something. Here, I’ll review a few basic tools for undoing
changes that you have made. Be careful, because you can’t always undo some of these undos.
This is one of the few areas in Git where you may lose some work if you do it wrong.

Changing Your Last Commit

One of the common undos takes place when you commit too early and possibly forget to add
some files, or you mess up your commit message. If you want to try that commit again, you
can run commit with the --amend option:

git commit --amend

This command takes your staging area and uses it for the commit.
And then you can add and commit that file.

Adding Remote Repositories

git remote add  [URL]

Fetching and Pulling from Your Remotes

git fetch [remote-name]

Pushing to Your Remotes

git push origin master


Listing Your Tags



git tag

Creating Tags

Git uses two main types of tags: lightweight and annotated. A lightweight tag is very much like
a branch that does not change—it’s just a pointer to a specific commit. Annotated tags, how-
ever, are stored as full objects in the Git database. They’re check-summed; contain the tagger
name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Pri-
vacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have
all this information; but if you want a temporary tag or for some reason don’t want to keep the
other information, lightweight tags are available too.



Annotated Tags

Creating an annotated tag in Git is simple. The easiest way is to specify -a when you run the
tag command:

git tag -a [name of tag] -m "message"

Signed Tags

You can also sign your tags with GPG, assuming you have a private key.

git tag -s [name of tag] -m "message"

Lightweight Tags

Another way to tag commits is with a lightweight tag.This is basically the commit checksum
stored in a file—no other information is kept.

git tag [name of tag] -lw

Verifying Tags

To verify a signed tag

git tag -v [name of tag]

Sharing Tags

 The git push command does not transfer tags to remote servers. You have to explic-
itly push tags to a shared server after you create them. This process is just like sharing remote
branches—you can run

git push origin [name of tag]

If you have a lot of tags that you want to push up at once

git push origin --tag



Friday, 20 February 2015

ionic

Ionic was built by @benjsperry, @adamdbradley, and @maxlynch at Drifty, an independent bootstrapped software company and makers of such fine products as Codiqa and Jetstrap.
Ionic was built to take HTML5 on mobile into the future. We wanted a mobile framework that not only looked and worked great, but was also powerful enough to build the amazing apps the best developers were creating. HTML5's time has arrived. Ionic is the framework that proves it.


 Ionic is focused on building native/hybrid mobile apps rather than mobile websites.
As such, our browser support tends to be whatever Web View API is available to native apps on a given platform.

Ionic is an open source framework released under a permissive MIT license. This means you can use Ionic in your own personal or commercial projects for free. MIT is the same license used by such popular projects as jQuery and Ruby on Rails.

Header

Headers are fixed regions at the top of a screen that can contain a title label, and left/right buttons for navigation or to carry out various actions.

Icons

Ionic also comes with its own free and open-sourced icon font, Ionicons, with over 500 icons to choose from.
Simply add icon and the Ionicon classname for the icon to show, which can be easily looked up on the Ionicons homepage.
<i class="icon ion-star"></i>
While it's possible for buttons to use a child <i> to set the icon, they can also set their icon just by setting the buttons own class. Please take a look at button icon docs for more info.

Padding

Many components in Ionic purposely have both padding and margin reset set to zero. In many instances apps will have components bleed to the edge of the screen, and by starting each component at zero developers can easily control padding and margins throughout the app.
The padding utility classes can be reused to give any element's content some breathing room, meaning it adds a default 10px between the outer box of the element and its inner content. The following classes are not required for any element, but may be helpful with your layout.


  • padding  Adds padding around every side.
  • padding-vertical Adds padding to the top and bottom.
  • padding-horizontal Adds padding to the left and right.
  • padding-top Adds padding to the top.
  • padding-right Adds padding to the right.
  • padding-bottom Adds padding to the bottom.
  • padding-left Adds padding to the left. 

Sub Header

A secondary header bar can be placed below the original header bar. There are quite a few more ways to customize Headers. Have a look at Button Bars to get other ideas on how it could be used.
<div class="bar bar-header">
  <h1 class="title">Header</h1>
</div>
<div class="bar bar-subheader">
  <h2 class="title">Sub Header</h2>
</div>
 

Content

The content area in Ionic is the scrollable viewport of your app. While your headers and footers will be fixed to the top and bottom, respectively, the content area will fill the remaining available space.

Footer

Footers are regions at the bottom of a screen that can contain various types of content.
<div class="bar bar-footer bar-balanced">
  <div class="title">Footer</div>
</div>
Footers have the same color options as the headers, just use bar-footer instead of bar-header. If a title is present in the footer, any buttons will automatically be placed on the correct side of the title in relation to how the markup was written, such as:
<div class="bar bar-footer">
  <button class="button button-clear">Left</button>
  <div class="title">Title</div>
  <button class="button button-clear">Right</button>
</div>
  if no title is present and a right side button is required, you'll need to add pull-right to the right side button, such as:
<div class="bar bar-footer">
  <button class="button button-clear pull-right">Right</button>
</div>

 


express js

express()

Creates an Express application. The express() function is a top-level function exported by the express module.
var express = require('express');
var app = express();

Application

The app object conventially denotes the Express application. Create it by calling the top-level express() function exported by the Express module:
var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);
The app object has a methods for
It also has settings (properties) that affect how the application behaves; for more information, see Application settings.

Properties


app.locals

The app.locals object is a JavaScript object, and its properties are local variables within the application.
app.locals.title
// => 'My App'

app.locals.email
// => 'me@myapp.com'
Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.
You can accesss local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data. Note, however, that you cannot access local variables in middleware.
app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';

app.mountpath

The app.mountpath property is the path pattern(s) on which a sub app was mounted.
A sub app is an instance of express which may be used for handling the request to a route.
var express = required('express');

var app = express(); // the main app
var admin = express(); // the sub app

admin.get('/', function (req, res) {
  console.log(admin.mountpath); // /admin
  res.send('Admin Homepage');
})

app.use('/admin', admin); // mount the sub app
It is similar to the baseUrl property of the req object, except req.baseUrl returns the matched URL path, instead of the matched pattern(s).
If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on, as shown in the following example.
var admin = express();

admin.get('/', function (req, res) {
  console.log(admin.mountpath); // [ '/adm*n', '/manager' ]
  res.send('Admin Homepage');
})

var secret = express();
secret.get('/', function (req, res) {
  console.log(secret.mountpath); // /secr*t
  res.send('Admin Secret');
});

admin.use('/secr*t', secret); // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin); // load the 'admin' router on '/adm*n' and '/manager', on the parent app

Events


app.on('mount', callback(parent))

The mount event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.
var admin = express();

admin.on('mount', function (parent) {
  console.log('Admin Mounted');
  console.log(parent); // refers to the parent app
});

admin.get('/', function (req, res) {
  res.send('Admin Homepage');
});

app.use('/admin', admin);

Methods


app.all(path, callback [, callback ...])

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.
It’s useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: loadUser can perform a task, then call next() to continue matching subsequent routes.
app.all('*', requireAuthentication, loadUser);
Or the equivalent:
app.all('*', requireAuthentication)
app.all('*', loadUser);
Another example is white-listed “global” functionality. The example is much like before, however it only restricts paths that start with “/api”:
app.all('/api/*', requireAuthentication);

app.delete(path, callback [, callback ...])

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide.
You can provide multiple callback functions that behave just like middleware, except these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
app.delete('/', function (req, res) {
  res.send('DELETE request to homepage');
});

app.disable(name)

Sets the Boolean setting name to false, where name is one of the properties from the app settings table. Calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').
For example:
app.disable('trust proxy');
app.get('trust proxy');
// => false

app.disabled(name)

Returns true if the Boolean setting name is disabled (false), where name is one of the properties from the app settings table.
app.disabled('trust proxy');
// => true

app.enable('trust proxy');
app.disabled('trust proxy');
// => false

app.enable(name)

Sets the Boolean setting name to true, where name is one of the properties from the app settings table. Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo').
app.enable('trust proxy');
app.get('trust proxy');
// => true

app.enabled(name)

Returns true if the setting name is enabled (true), where name is one of the properties from the app settings table.
app.enabled('trust proxy');
// => false

app.enable('trust proxy');
app.enabled('trust proxy');
// => true
 

app.engine(ext, callback)

Registers the given template engine callback as ext.
By default, Express will require() the engine based on the file extension. For example, if you try to render a “foo.jade” file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.
app.engine('jade', require('jade').__express);
Use this method for engines that do not provide .__express out of the box, or if you wish to “map” a different extension to the template engine.
For example, to map the EJS template engine to “.html” files:
app.engine('html', require('ejs').renderFile);
In this case, EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally so if you’re using “.ejs” extensions you don’t need to do anything.
Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seemlessly with Express.
var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);

app.get(name)

Returns the value of name app setting, where name is one of strings in the app settings table. For example:
app.get('title');
// => undefined

app.set('title', 'My Site');
app.get('title');
// => "My Site"

app.get(path, callback [, callback ...])

Routes HTTP GET requests to the specified path with the specified callback functions. For more information, see the routing guide.
You can provide multiple callback functions that behave just like middleware, except these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
app.get('/', function (req, res) {
  res.send('GET request to homepage');
});

app.listen(port, [hostname], [backlog], [callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
var express = require('express');
var app = express();
app.listen(3000);
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
The app.listen() method is a convenience method for the following (for HTTP only):
app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

app.METHOD(path, callback [, callback ...])

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on. See below for the complete list.
For more information, see the routing guide.
Express supports the following routing methods corresponding to the HTTP methods of the same names:
  • checkout
  • connect
  • copy
  • delete
  • get
  • head
  • lock
  • merge
  • mkactivity
  • mkcol
  • move
  • m-search
  • notify
  • options
  • patch
  • post
  • propfind
  • proppatch
  • purge
  • put
  • report
  • search
  • subscribe
  • trace
  • unlock
  • unsubscribe
 

Friday, 13 February 2015

web socket

WebSocket
  is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.
WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. The WebSocket protocol makes more interaction between a browser and a web site possible, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.

In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-web Internet connections using a firewall. The WebSocket protocol is currently supported in most major browsers including Google Chrome, Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it.


Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.
Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.
Following is the API which creates a new WebSocket object.
var Socket = new WebSocket(url, [protocal] );
Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.

WebSocket Attributes:

Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above:
AttributeDescription
Socket.readyStateThe readonly attribute readyState represents the state of the connection. It can have the following values:
  1. A value of 0 indicates that the connection has not yet been established.
  2. A value of 1 indicates that the connection is established and communication is possible.
  3. A value of 2 indicates that the connection is going through the closing handshake.
  4. A value of 3 indicates that the connection has been closed or could not be opened.
Socket.bufferedAmountThe readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method.

WebSocket Events:

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above:
EventEvent HandlerDescription
openSocket.onopenThis event occurs when socket connection is established.
messageSocket.onmessageThis event occurs when client receives data from server.
errorSocket.onerrorThis event occurs when there is any error in communication.
closeSocket.oncloseThis event occurs when connection is closed.

WebSocket Methods:

Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above:
MethodDescription
Socket.send()The send(data) method transmits data using the connection.
Socket.close()The close() method would be used to terminate any existing connection.

WebSocket Example:

A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.

Client Side HTML & JavaScript Code:

At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://localhost:9998/echo");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

Install pywebsocket:

Before you test above client program, you need a server which supports WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server ans install it following these steps.
  1. Unzip and untar the downloaded file.
  2. Go inside pywebsocket-x.x.x/src/ directory.
  3. $python setup.py build
  4. $sudo python setup.py install
  5. Then read document by:
    • $pydoc mod_pywebsocket
This will install it into your python environment.

Start the Server

Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and run the following command:
$sudo python standalone.py -p 9998 -w ../example/
This will start the server listening at port 9998 and use the handlers directory specified by the -w option where our echo_wsh.py resides.
Now using Chrome browser open the html file your created in the beginning. If your browser supports WebSocket(), then you would get alert indicating that your browser supports WebSocket and finally when you click on "Run WebSocket" you would get Goodbye message sent by the server script.


Getting Started

You open up a WebSocket connection simply by calling the WebSocket constructor:
var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
Notice the ws:. This is the new URL schema for WebSocket connections. There is also wss: for secure WebSocket connection the same way https: is used for secure HTTP connections.
Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.
The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing protocol property of WebSocket object.
The subprotocol names must be one of registered subprotocol names in IANA registry.

// When the connection is open, send some data to the server
connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

Communicating with the Server

As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send('your message') method on the connection object. It used to support only strings, but in the latest spec it now can send binary messages too. To send binary data, you can use either Blob or ArrayBuffer object.
// Sending String
connection.send('your message');

// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i];
}
connection.send(binary.buffer);

// Sending file as Blob
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);
Equally the server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property.
WebSocket can also receive binary messages in the latest spec. Binary frames can be received in Blob or ArrayBuffer format. To specify the format of the received binary, set the binaryType property of WebSocket object to either 'blob' or 'arraybuffer'. The default format is 'blob'. (You don't have to align binaryType param on sending.)

// Setting binaryType to accept received binary as either 'blob' or 'arraybuffer'
connection.binaryType = 'arraybuffer';
connection.onmessage = function(e) {
  console.log(e.data.byteLength); // ArrayBuffer object if binary
};
Another newly added feature of WebSocket is extensions. Using extensions, it will be possible to send frames compressed, multiplexed, etc. You can find server accepted extensions by examining the extensions property of the WebSocket object after the open event.


// Determining accepted extensions
console.log(connection.extensions);

Cross Origin Communication

Being a modern protocol, cross origin communication is baked right into WebSocket. While you should still make sure only to communicate with clients and servers that you trust, WebSocket enables communication between parties on any domain. The server decides whether to make its service available to all clients or only those that reside on a set of well defined domains.

Proxy Servers

Every new technology comes with a new set of problems. In the case of WebSocket it is the compatibility with proxy servers which mediate HTTP connections in most company networks. The WebSocket protocol uses the HTTP upgrade system (which is normally used for HTTP/SSL) to "upgrade" an HTTP connection to a WebSocket connection. Some proxy servers do not like this and will drop the connection. Thus, even if a given client uses the WebSocket protocol, it may not be possible to establish a connection. This makes the next section even more important :)

Use WebSockets Today

WebSocket is still a young technology and not fully implemented in all browsers. However, you can use WebSocket today with libraries that use one of the fallbacks mentioned above whenever WebSocket is not available. A library that has become very popular in this domain is socket.io which comes with a client and a server implementation of the protocol and includes fallbacks . There are also commercial solutions such as PusherApp which can be easily integrated into any web environment by providing a HTTP API to send WebSocket messages to clients. Due to the extra HTTP request there will always be extra overhead compared to pure WebSocket.

The Server Side

Using WebSocket creates a whole new usage pattern for server side applications. While traditional server stacks such as LAMP are designed around the HTTP request/response cycle they often do not deal well with a large number of open WebSocket connections. Keeping a large number of connections open at the same time requires an architecture that receives high concurrency at a low performance cost. Such architectures are usually designed around either threading or so called non-blocking IO.

Friday, 30 January 2015

shortcut keys


Shortcut Keys Summary for UNIX/Linux
Keyboard Bindings

Shortcut Keys
Function
Ctrl + Shift + Space
Complete Command
Esc
Complete Command
Home
Cursor to start of line
End
Cursor to end of line
Page Up
Cursor back one page
Page Down
Cursor forward one page
Ctrl + Home
Cursor to top of worksheet
Ctrl + End
Cursor to end of worksheet
Ctrl + Left Arrow
Cursor to previous word
Ctrl + Right Arrow
Cursor to next word
Ctrl + Up Arrow
Move to top of input line
Ctrl + Down Arrow
Move to bottom of input line
Shift + Enter
Soft new line
Tab
Cursor down to next input region
\
Escape next character for entering "^"
Ctrl + Tab
Move forward through multiple open worksheet and document tabs in a Maple window.
Ctrl + Shift + Tab
Move backward through multiple open worksheet and document tabs in a Maple window.

  
For a list of math editing shortcut keys, see 2-D Math Shortcut Keys and Hints.
  
The following is a list of menu accelerators.
Shortcut Keys
Function
Ctrl + N
New Document/Worksheet (based on Options dialog setting)
Ctrl + O
Open Worksheet
Ctrl + F4
Close Current Worksheet
Ctrl + S
Save Worksheet
Ctrl + P
Print Worksheet
Alt + F4
File -> Exit
 
 
Alt + Backspace
Undo
Ctrl + Y
Redo
 
 
Ctrl + X
Cut to Motif Clipboard
Ctrl + C
Copy to Motif Clipboard
Ctrl + Shift + M
Copy Selection as MathML
Ctrl + V
Paste from Motif Clipboard
Ctrl + Delete
Delete an Element
 
 
Ctrl + A
Select All
Ctrl + Alt + Shift + D
Select document block
Ctrl + Alt + Shift + E
Select execution group
Ctrl + Alt + Shift + S
Select section
Ctrl + F
Find/Replace
 
 
F5
Switch between Text and Math mode
F3
Split Execution Group
F4
Join Execution Group
Shift + F3
Split Section
Shift + F4
Join Section
Enter
Evaluate
Alt + Enter
Evaluate and Display Inline (U.S. and International keyboards)
Ctrl + =
Evaluate and Display Inline (U.S. keyboards)
Ctrl + Shift + A
Convert the selected expression into an atomic identifier (2-D math only)
 
 
Ctrl + 0
Zoom to 50%
Ctrl + 1
Zoom to 75%
Ctrl + 2
Zoom to 100%
Ctrl + 3
Zoom to 125%
Ctrl + 4
Zoom to 150%
Ctrl + 5
Zoom to 200%
Ctrl + 6
Zoom to 300%
Ctrl + 7
Zoom to 400%
F9
Show/Hide Execution Group Range Guides
Shift + F9
Show/Hide Section Range Guides
 
 
Ctrl + T
Switch to Text Input
Ctrl + M
Switch to Maple Input
Ctrl + R
Switch to 2-D Math Input
Ctrl + L
Insert Label
Ctrl + Enter
Insert a Page Break
 
 
Ctrl + K
Insert Execution Group Before Current Paragraph
Ctrl + J
Insert Execution Group After Current Paragraph
Shift + Ctrl + J
Insert Paragraph After Current Paragraph
Shift + Ctrl + K
Insert Paragraph Before Current Paragraph
 
 
Ctrl + B
Bold (text or Maple input)
Ctrl + I
Italic (text or Maple input)
Ctrl + U
Underline (text or Maple input)
Ctrl + .
Section Indent
Ctrl + ,
Section Outdent
 
 
F7
Spellcheck
 
 
Ctrl + F1
Help Table of Contents
Ctrl + F2
Maple Quick Reference Card
F1
Quick Help Pop-up Menu
F2
Context-sensitive Help
Shift + Ctrl + E
Launch the startup code editor