Categories
Uncategorized

How to set $http timeout in AngularJs

http://

Global Timeout
To set a global http timeout in angularjs, we need to use the following code, which takes time in milliseconds to override the default http timeout value.

angular.module('myApp',[])
  .factory('timeoutHttpIntercept', function ($rootScope, $q) {
    return {
      'request': function(config) {
        config.timeout = 1 * 60 * 1000; 
                      // 1 minute or 60 seconds or 60,000 milliseconds
       return config; } 
      }; 
    });

angular.module('myApp')
  .config(function($routeProvider) { $httpProvider.interceptors.push('timeoutHttpIntercept');  });

Call specific Timeout
To specifically set a custom timeout for a particular http call that you make, you can include it as part of the config object.

var app = angular.module('myApp', []);
app.controller('myCtrl',   function($scope, $http) {

// 1 minute or 60 seconds or 60,000 milliseconds
var config = {
          method : "GET",
          url : "https://www.example.com/post",
          timeout: 1 * 60 * 1000
     };

$http(config)
        .then(
           function mySuccess(response) {
            $scope.myWelcome = response.data;
           },
           function myError(response)   {
             $scope.myWelcome =   response.statusText;
         });
});

                                                         or

var app = angular.module('myApp', []);
app.controller('myCtrl',   function($scope, $http) {
    
   $http({
          method : "GET",
          url : "https://www.example.com/post",
          timeout: 1 * 60 * 1000
      })
        .then(
            function mySuccess(response) {
               $scope.myWelcome = response.data;
            },
            function myError(response)   {
               $scope.myWelcome = response.statusText;
          });
});
Categories
Uncategorized

How to redirect passport to referrer after authentication

PassortJSPassportJS by default redirects to the homepage and not the referrer, after authentication. To achieve redirection to the referrer without installing any additional plugins, all that needs to be done is to store the referrer URL in session.redirectTo variable. This can be used to later redirect the user once the authentication is performed successfully. It does not matter whether the session is stored locally or remotely (scalable applications).

Storing the referrer URL

app.use(function (req, res, next) {
    if (req.user) {
        next();
    } else {
        session.redirectTo = req.url;

       // or   session.redirectTo = req.originalUrl;
       // if that doesn't work try this
       //     require('url').parse(req.url).path;

      res.redirect('/login');
    }
});

Redirecting to required URL after successful login

// For 0Auth 2.0 Passport Strategy

app.get('/auth/provider/callback',
 passport.authenticate('provider',
  { failureRedirect: '/login' }, 
  function(req, res) {
    // You can log the user to backend API logs and then upon success        
    //redirect to referrer
   
   if (session.redirectTo)
      res.redirect(session.redirectTo);
   else 
      res.redirect('/');
 }
));
Categories
Uncategorized

How to use AngularJS Services

angularjs by googleThere are many ways in which one can use Angular Services in an Angular project. The following is a good example of a frequent use case for the angular factory. (Services can be implemented by either angular service or angular factory)

When we write a service, the main goal is to be make it modular and reusable. In the following service named ‘serviceModuleName’, we have added support for HTTP GET & POST calls. We are handling them using promises being returned. For this purpose we use the $q service in angular.

Define a Service

(function () {
    'use strict';
    angular.module('App').factory('serviceModuleName', function ($http, $q) {
        var httpDeferGet = function (url) {
            var deferred = $q.defer();
            $http.get(url)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

        var httpDeferPost = function (url, obj) {
            var deferred = $q.defer();
            $http.post(url, obj)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

   var getLaunch = function () {
    return httpDeferGet('www.example.com/test-get-endpoint');
    };

var postLaunch = function (obj) {
    return httpDeferPost('www.example.com/test-get-endpoint', obj);
};

return {
getLaunch: getLaunch,
postLaunch: postLaunch
}

});
})();

Injecting a Service into the Controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, serviceModuleName) {
 
});

Calling a Service from inside a Controller

Since a promise is being returned by the service we need to handle it with then, catch and finally blocks. ‘then’ returns the data, ‘catch’ catches the exception thrown and it can be handled here. Finally the ‘finally’ block of statements are executed regardless of success/failure.

$scope.callService = function(postObj) { 

 $scope.loading = true;
 
serviceModuleName.postLaunch(postObj) 
 
.then(function (data) { 
 $scope.returnedData = data; 
 }) 

 .catch(function (err) { 
 $scope.error = 'Sorry something went wrong! ' + err; 
 }) 

 .finally(function () { 
 $scope.loading = false; 
 }); 
 
};
Categories
Uncategorized

AngularJS 1.X ng-options

Using the predefined angularjs ng-options directive can be quite tricky at times. The following is a basic example of how to iterate through list of people. The value of the person that is chosen from the drop down list is store in $scope.chosenPerson and can be accessed with the same from the controller.
Example 1:


  

Output:
ng-options 1

Demo

Example 2: If you just want the value to be last name instead of the whole object  use this.


  

Output:
ng-options 1

Demo

To access a nested array and show it as part of the dropdown the following example demonstrates how to do that,

Example 3


  

Output

ng-options output2

Demo

In the above example if the countries and locations were 2 completely different objects, then a hashmap can be used to link those two objects by keys and values.

Categories
Uncategorized

Generate/Check valid JWTs using PHP

jwt

https://github.com/Shiva1029/token

Pull the latest code from the repository onto your web server with php 5.x+ pre-installed.

  1. Run index.php first to generate a JWT (JSON Web Token) token.
  2. Paste the JWT into the variable $jwt in check_token.php within 5 mins after generating it, to validate the JWT. The JWT expiration time is set to until 300 seconds after 10 initial seconds delay. If the JWT is validated after this time period, then you will get an error that states that the token is invalid as it is expired.
  3. The server side secret key can be regenerated using genSecret.php
    This value can be used  to replace the existing secret key in the config/config.php file.

This code uses the following composer libraries:
{
“require”: {
“firebase/php-jwt”: “dev-master”,
“zendframework/zend-config”: “~2.3”,
“zendframework/zend-http”: “~2.3”
}
}

Categories
Uncategorized

Samsung Fast Wireless Charging Stand for Samsung Galaxy S7 Edge

 

The Samsung  Fast Wireless Charging Stand comes in a Black Saphire color. It is very ideal for daily use, as you no longer need to charge your phone for long hours or need to plug in the cord to your phone while charging. You could use it at home, office and also in your car. The base of this charger has a sticky rubber finish, that stops the stand from easily being displaced.

This charger is compatible with the following Samsung devices.

Galaxy S7, Galaxy S7 edge, GS6 edge, GS6, GS6 edge+, Note5

It also charges most Qi-enabled devices. Fast charge only works when your phone is compatible. For example, my Samsung Galaxy S7 Edge works in Fast charging mode with this charger, as it has that feature built into the phone. At the bottom of the device you have a multi-colored LED indicator to depict the status of the charging. This wireless fast charger from Samsung works with a micro USB charger, which is included in the box with this purchase. This means that you get a spare wired fast charger for your phone.

It costs only 69.99$ + Taxes.

Buy here from Samsung. The shipping is free and it usually arrives in about 2-3 business days. I got mine from here, and fedex delivered it on time.

Categories
Uncategorized

New CPU installed press F1 to setup or F2 to load defaults – Fixed!

new cpu installed

Most of us are faced with this problem on booting after reconnecting/replacing few components on their Desktops. I had this issue and fixed it by unlatching the Processor and putting it back more firmly. This booting issue doesn’t appear after placing the Processor chip firmly into it’s position.

Categories
Uncategorized

Asus Z170 Deluxe for Gaming

The Asus Z170 Deluxe Motherboard supports 2-way SLI technology for Gamers. Like most other motherboards, the Z170 also comes with a free SLI-bridge. As of the time this post was written, this is one of the best Motherboards for Personal Computing. Also this is one of the very few motherboards, that offer on board NVMe support through an m.2 slot and Hyperkit. The amazingly fast Intel 750 series SSDs can be interfaced with the Asus Z170 using the U.2 connector and the Hyperkit (needs to be connected to your m.2 slot on-board). You can also program function keys to switch to UEFI BIOS. This beats the Asus X99 Deluxe as it cannot support 6th Generation Intel i7 Processors. The audio section on this board, has shielding and also an amplifier.

Asus Z170 Deluxe

  • Supports Intel Skylake Processors (Intel LGA Socket 1151, 6th Generation 14nm)
  • Supports upto 64GB of DDR4 memory with Over Clocking (O.C.) upto 3733 Mhz
  •  2.5-in NVMe support through U.2 (previously SFF-8639) connector and Hyperkit + m.2 slot .
  • PCI Express to m.2 adapter for an extra m.2 slot.
  • 3 x PCle 3.0 (GEN3)
  • 6 X SATA 6Gb/s
  • SLI (2-Way) & 3-WAY CFX Support
  • 2-way SLI bridge
  • 6 USB 3.1 (1 Type C 5 Type A) ports and 4 USB 3.0 ports.
  • 3×3 Dual – Band Wi- Fi 802.11ac + BT 4.0 and Wireless Antenna Adapters (External)

Note: The Asus Z170-Deluxe only supports one Titan Z as it already a Dual GPU in SLI and the z170-Deluxe only supports 2-way SLI. However, to achieve similar or even better results at times, you can have 2 nvidia Titan Xs in SLI mode using the 2-way SLI bridge.

Categories
Uncategorized

Handling CORS and API

CORS

Handling CORS (Cross-Origin Resource Sharing) can be quite tricky at times.  Browsers restrict Cross-Origin HTTP requests due to security reasons. For example, the XMLHttpRequest doesn’t work for external domains. With CORS, XMLHttpRequest 2 allows that.

To handle the Cross-Origin requests on modern browsers, there is an easy workaround. A backend technology like PHP, nodejs, .NET, Java or Ruby on Rails can be used to route externals API calls through them, instead of directly calling the API from the frontend technologies like jQuery and AngularJS.

For example I have written a simple program using PHP 5.6 in the backend and AngularJS on the front end to initiate the CORS.

DEMO

Code

If you are having trouble handling the COR’s on the API side and have access to the Apache config file(ex: apache2.conf) on your API server, then you can enable the settings by adding this line in your Directory or Virtual Hosts tag.

Header set Access-Control-Allow-Origin "*"

To allow only a particular domain,

Header set Access-Control-Allow-Origin "your-domain.com"

If you do not have access to the apache config file, then you need to include the following header in your API service file, to allow Cross-Origin requests made to it. Not initiating this may lead to 403 errors as response. To allow any domain to request the API, you can use the following piece of code in your php file.

 <?php
     header("Access-Control-Allow-Origin: *");
     ...
  ?>

To allow only a certain domain to make requests to your API, you can use the following line of code.

 <?php
     header("Access-Control-Allow-Origin: your-domain.com");
     ...
  ?>

If you have any other ideas regarding CORS, you can add a comment below.

Categories
Uncategorized

Temp Files in Windows

Regularly clearing the temporary files on your Windows system can save you a lot of space on your Hard Drive. To start a quick clean up process, open up the Run dialogue box in Windows using the Windows+R key. Enter the following commands and click on Ok. Then delete the files permanently (Shift+Del).

  1. temp [admin privileges]
  2. %temp% [user privileges]
  3. prefetch [admin privileges]temporary
    You might want to view and delete the hidden files as well in these folders.
    Note that the prefetch folder is used as a caching storage to speed up loading your programs, so clearing it to refresh or to save space would mean that your programs will take longer to open the next time you turn on your computer.Some of the more common tasks to clear up even more space would to,

->  Clear Internet Browsing history on all your browsers
-> Empty the Recycle Bin
-> Perform Disk Cleanup on all drives.

If you think that you do not use Recycle Bin’s storage to it’s full extent, then you can reduce it’s quota by right clicking and selecting properties and choosing the right percentage for your Hard Drive.

You can use CCleaner to do  regular cleanup tasks and tasks like fixing your Windows Registry errors for free. Scanning and fixing the registry errors takes care of all the broken links in the windows registry after running a program setup or uninstalling it, or for missing files, etc. You can also speed up your system startup process, by choosing which applications run on system startup.

If you have anymore ways to cleanup temp files and speed up the PC, then you can leave a comment below.