Monday, 28 August 2017

Angular 4.0 – Installation & Setup in Local Environment


For building Angular Application we can use many languages like JavaScript, ES5, ES2015(Known as ES6), Typescript, CoffeeScript and Dart (Non-JavaScript language). Typescript is the most commonly used language to develop Angular Applications.
Typescript is an open Source language and which is a superset of JavaScript. As the name says it is strongly typed and it has classes, interface, inheritance as like any object-oriented language. It gets converted to JavaScript which is supported by all the browsers.  You can find more information about Typescript in its official documentation.
If you are new to Angular you will be wondering how to start coding Angular Application. There are several ways you can do this,

Try Angular 4.0 on plunker without installing anything (QuickStart Example given in official Angular document)

Manually Installing Angular 4

In this post, we will see how to set up Angular 4 development environment manually. It is similar to Angular2 setup with few changes. Although we have many easy ways to start, it is always good to know manual method for better understanding

Step 1:  Install Node.js and npm

Node package manager(npm) is the command line utility that interacts with the repository of open source projects. It has become the package manager for JavaScript. Npm is distributed with Node.js, when you download Node.js you will automatically get npm installed on your computer. Get npm from this link.
When installation is complete we can run the below command to check version of node or npm installed.
node -v
If the installation is successful, you will get the below version number,
V7.9.0 (this may vary depends on the current version)
npm -v

If the installation is successful, you will get the below version number
4.5.0 (this may vary depends on the current version)
Angular 4.0 Installation

Step 2:  Choosing an Editor

Angular programming can be done with any code editor. You can choose any editors like Sublime Text, WebStorm, Atom, visual studio, visual studio code, eclipse. I’m using Visual studio code and you can install it from this link.
Once you have Installed node.js, npm, editor and a browser of your choice (I’m using chrome) we are ready to start our development.

Step 3:  Creating an Application Folder Structure

Angular 4.0 Folder Structure
Angular application folder structure will look as shown in this image.
Create the application folder as angularsetup (any name). Inside angularsetup folder, Create the folder src and inside ‘src’ folder create new folder app. Files outside src include configuration files and external dependency. Files inside src/ belong to your app typescript, HTML, CSS, and application specific features.

Step 4:  Creating package.json, bs-config.json, tsconfig.json, systemjs.config.js

package.json
Create new file package.json in application folder(angularsetup) and add the below configuration. Npm command will read the package config file and then install the required files into our application file path
{
  "name": "angular-setup-example",
  "version": "1.0.0",
  "private": true,
  "description": "Angular setup - example",
  "scripts": {
    "build": "tsc -p src/",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",  
    "build:watch": "tsc -p src/ -w",
    "build:upgrade": "tsc",
    "serve:upgrade": "http-server",
    "i18n": "ng-xi18n",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "dependencies": {
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/compiler-cli": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/forms": "~4.0.0",
    "@angular/http": "~4.0.0",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",
    "@angular/platform-server": "~4.0.0",
    "@angular/router": "~4.0.0",
    "@angular/tsc-wrapped": "~4.0.0",
    "@angular/upgrade": "~4.0.0",
    "angular-in-memory-web-api": "~0.3.1",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "systemjs": "0.19.39",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/angular": "^1.5.16",
    "@types/angular-animate": "^1.5.5",
    "@types/angular-cookies": "^1.4.2",
    "@types/angular-mocks": "^1.5.5",
    "@types/angular-resource": "^1.5.6",
    "@types/angular-route": "^1.3.2",
    "@types/angular-sanitize": "^1.3.3",
    "@types/node": "^6.0.45",
    "canonical-path": "0.0.2",
    "concurrently": "^3.0.0",
    "http-server": "^0.9.0",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.2",
    "source-map-explorer": "^1.3.2",
    "tslint": "^3.15.1",
    "typescript": "~2.2.0"
  },
  "repository": {}
}
package.json has the list of packages required for the angular application. It has three important sections,
  • Scripts: Script section will start the development server and typescript compiler from command line.
  • Dependencies: List of packages that application depend on to run. This contains angular libraries, polyfill libraries that add modern features to old browsers.
  • DevDependencies: This contains libraries that will be used only in development environment and will not be used after deployment.
bs-config.json
Create the lite-server configuration file (bs-config.json) in application folder and add the below configuration settings.
bs is browser sync and it serves the static content, detects changes, refreshes the browser, and offers many customizations. It will be useful for super-fast lightweight development
{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    },
    "minify": false,
    "browser": "chrome"
  }
}
tsconfig.json
typescript requires a configuration file, create tsconfig.json in the ‘src’ folder and add the below configuration. We are writing our angular code in Typescript, but Browsers can’t execute Typescript directly. We can configure the Typescript compiler options and compile on save options to transpile .ts to .js files.
{
  "compilerOptions": {
    "target": "es5",//Setting ECMS script version to ES5
    "module": "commonjs", //generates our module in commonjs format.
    "moduleResolution": "node", 
    "sourceMap": true, //option to generate source map file.
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    //all types packages will be included.
    "typeRoots": [
      "../node_modules/@types/"
    ]
  },
  "compileOnSave": true, //to generate all the files for the tsconfig.json upon save.
  "exclude": [
    "node_modules"
    ] 
}

systemjs.config.js

Create new file systemjs.config.js inside src folder and add the below configuration. It is an ES module loader which loads all the files for our application. So, we don’t have to add script tag for every file we use in our application.
/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      /*specifies the path where system files are located
        npm: is the alias for the path 'node_modules'
      */
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js',
        meta: {
          './*.js': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

tslint.json (optional)

Add new file tslint.json inside application folder and add the below rules.  tslint checks Typescript code for readability, maintainability, and functionality errors. Simply add the file to the root directory of the project. You should adjust rules to your needs
{
  "rules": {
    "class-name": true,
    "comment-format": [
      true,
      "check-space"
    ],
    "curly": true,
    "eofline": true,
    "forin": true,
    "indent": [
      true,
      "spaces"
    ],
    "label-position": true,
    "label-undefined": true,
    "max-line-length": [
      true,
      140
    ],
    "member-access": false,
    "member-ordering": [
      true,
      "static-before-instance",
      "variables-before-functions"
    ],
    "no-arg": true,
    "no-bitwise": true,
    "no-console": [
      true,
      "debug",
      "info",
      "time",
      "timeEnd",
      "trace"
    ],
    "no-construct": true,
    "no-debugger": true,
    "no-duplicate-key": true,
    "no-duplicate-variable": true,
    "no-empty": false,
    "no-eval": true,
    "no-inferrable-types": true,
    "no-shadowed-variable": true,
    "no-string-literal": false,
    "no-switch-case-fall-through": true,
    "no-trailing-whitespace": true,
    "no-unused-expression": true,
    "no-unused-variable": true,
    "no-unreachable": true,
    "no-use-before-declare": true,
    "no-var-keyword": true,
    "object-literal-sort-keys": false,
    "one-line": [
      true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],
    "quotemark": [
      true,
      "single"
    ],
    "radix": true,
    "semicolon": [
      "always"
    ],
    "triple-equals": [
      true,
      "allow-null-check"
    ],
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace",
        "index-signature": "nospace",
        "parameter": "nospace",
        "property-declaration": "nospace",
        "variable-declaration": "nospace"
      }
    ],
    "variable-name": false,
    "whitespace": [
      true,
      "check-branch",
      "check-decl",
      "check-operator",
      "check-separator",
      "check-type"
    ]
  }
}
Systemjs-angular-loader.js (optional)
Create new file systemjs-angular-loader.js inside src folder and add the below configurations. This file is introduced in Angular 4.0, This plugin dynamically converts “component-relative” paths in templateUrl and styleUrls to “absolute paths“.
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;

module.exports.translate = function(load){
  if (load.source.indexOf('moduleId') != -1) return load;

  var url = document.createElement('a');
  url.href = load.address;

  var basePathParts = url.pathname.split('/');

  basePathParts.pop();
  var basePath = basePathParts.join('/');

  var baseHref = document.createElement('a');
  baseHref.href = this.baseURL;
  baseHref = baseHref.pathname;

  if (!baseHref.startsWith('/base/')) { // it is not karma
    basePath = basePath.replace(baseHref, '');
  }

  load.source = load.source
    .replace(templateUrlRegex, function(match, quote, url){
      let resolvedUrl = url;

      if (url.startsWith('.')) {
        resolvedUrl = basePath + url.substr(1);
      }

      return 'templateUrl: "' + resolvedUrl + '"';
    })
    .replace(stylesRegex, function(match, relativeUrls) {
      var urls = [];

      while ((match = stringRegex.exec(relativeUrls)) !== null) {
        if (match[2].startsWith('.')) {
          urls.push('"' + basePath + match[2].substr(1) + '"');
        } else {
          urls.push('"' + match[2] + '"');
        }
      }

      return "styleUrls: [" + urls.join(', ') + "]";
    });

  return load;
};
Step 5: Installing the packages using “npm install”
Go to application folder (where package.json is available) in the command prompt and run the below command. It may install with some warnings but we can ignore it. Upon successful installation, you can find node_modules folder created in application folder. If you have existing, ‘node_modules’ folder in the application path below command will update the folder based configuration in package.json.
npm install

NPM Install

Step 6:  Creating Angular component and Angular module

Component
An Angular class responsible for exposing data to a view and handling most of the view’s display and user-interaction logic. The component is one of the most important building blocks in the Angular system.
AppComponent is the root component of the application. Common naming convention of the Angular component is to name the component with its feature name and append the word component as suffix. Those familiar with “MVC” and “MVVM” patterns will recognize the component in the role of “controller” or “view model“.
Create the file app.component.ts inside src\app\ folder and add the below code
//import the components which is used in this component.
import {Component} from "@angular/core";

//Component decorator- which has metadata that defines the template used by this component
@Component(
    {
        selector: "my-app",
        template:`
            <div>
                <h1 style="color:blue"> {{strName}} </h1>
                <div style="color:green"> My First Angular Component </div>
            </div>
            `
    }
)

//component class which has the methods and properties need by the view.
export class AppComponent{
    //string type property 
    strName:string ='Angular4 Setup Example'   
} 
Export keyword is used to export the class and make it used by the other components. Decorator is a function that adds metadata to class and its members. Selector is the directive name used in HTML. This is the custom HTML tag that can be used in html page to render this component’s template. All the component has templates which defines the layout or view managed by that component.
Module
Angular module is used to organize our application in to blocks of functionality and provides boundary within application. An Angular module identifies the components, directives, and pipes that the application uses along with the list of external Angular modules that the application needs. Every Angular application has an application root-module class. By convention, the class is called AppModule and resides in a file named app.module.ts.
Create the file app.module.ts inside src\app\ folder and add the below code
//importing the required modules from angular
import{NgModule} from "@angular/core";
import{BrowserModule} from "@angular/platform-browser";
//importing the component for this module
import{AppComponent} from "./app.component";

//Module decorator  
@NgModule({
    //To import external module that are used by all the components belong to this Module.
    imports:[BrowserModule],
    //array defines the component belongs to this module.
    declarations:[AppComponent],
    //root component of the application which contains selector in the index.html file
    bootstrap:[AppComponent]
})

//App module class. Root module of the application
export class AppModule {
}

Step 7:  Creating an Index.html and main.ts file

Create index.html file in src folder and add the below markup.
<html>
  <head>
    <title>Angular 4 Setup Application</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <!--polyfills for older browser-->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <!--Angular uses zone for change detection and databinding-->
    <script src="node_modules/zone.js/dist/zone.min.js"></script>    

    <!--module Loader-->
    <script src="node_modules/systemjs/dist/system.src.js"></script>

   <!-- system configiration file-->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <!-- content managed by Angular -->
    <my-app></my-app>
  </body>
</html>
Create the main.ts file in the src folder and add the below code,
//Main Entry point of the application 
import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";
import {AppModule} from "./app/app.module"

//Angular compiler compiles the application in the browser and run the application from App module.
platformBrowserDynamic().bootstrapModule(AppModule); 

Step 8: Starting the server

All the basic setup has been done and now we will test our application, run the following command from the application root folder
npm start

This command starts the Typescript compiler and light-server development HTTP server and typescript compiler in watch mode. After running this command, new browser window will display our index.html page in localhost:3000
Whenever you do some changes to any files type script recompile them, the lite-server will refresh the browser automatically and reflect our changes immediately.
Angular 4.0 - Setup Example
How it Works?
Below picture showing the steps how Angular 4 project runs,
  1. html is setup to host the application by specifying the selector (my-app) inside the body tag.
  2. html imports and executes the main JavaScript file using systemjs.config.js file.
  3. ts is the main entry of the application, which bootstraps the applications Angular module ‘appmodule’.
  4. AppModule bootstraps the root component ‘appcomponent’ and the appcomponent’s template appears in the index.html page (inside selector tag) in the browser.
Note:  Typescript will generate equivalent .js and .map.js files for every .ts files which will be used by the browser to load the application.
Typescript will generate equivalent .js and .map.js files for every .ts files

Typescript will generate equivalent .js and .map.js files for every .ts files

Thursday, 24 August 2017

Docker Secrets and MySQL Password Management

In this posting we will look at currently recommended ways of managing passwords in MySQL Docker containers and explore whether the recently introduced concept of Docker Secrets could play a role in this area.
Managing runtime secrets in Docker has traditionally been hard to do securely. The MySQL Docker images have typically offered various ways to set the MySQL root password, where some methods are recommended over others. The typical ways to set the root password are 1) specifying the password directly using the MYSQL_ROOT_PASSWORD environment variable 2) bind-mounting a password file into the container, and have MYSQL_ROOT_PASSWORD point to this file, and 3) setting the MYSQL_RANDOM_ROOT_PASSWORD in order to have MySQL generate a random root password. The recommended way on MySQL 5.6 and newer is to use MYSQL_RANDOM_ROOT_PASSWORD in conjunction with MYSQL_ONETIME_PASSWORD, and we’ll briefly explain why this is so.
Specifying the password directly using MYSQL_ROOT_PASSWORD is the least secure option. When running a Docker container, its environment variables are exposed to both the host system and to the container itself, leaving the password at very high risk of exposure. We’ll leave it as an exercise for the reader to find out how and why; suffice it to say that we strongly discourage this way of doing it in any kind of setting where security is of any concern whatsoever.
Bind-mounting a password file will avoid some of the exposure, but the file would still have to be stored on the host system. The environment variable would also expose where it can be accessed on the host system. Not really ideal. Now, the recommended way is to generate a one-time password upon first run using the MYSQL_RANDOM_ROOT_PASSWORD and MYSQL_ONETIME_PASSWORD variables, and then set a secure password after the container initialization is complete. This will lead to only limited exposure of the password in the presumably short interval between container init and first time use, and is thus strongly recommended over the other available options.
Because managing secrets securely in Docker containers is a relatively common need for many Docker users, it was to widespread acclaim that Docker introduced a new mechanism for managing sensitive data with Docker Secrets in version 1.13. It has been stated that this feature only works with Docker Swarm, but the Docker Compose documentation gives the impression that you can leverage the secrets framework on ‘regular’ containers through the use of Docker Compose. We thought we’d check out whether this could be used for management of passwords in MySQL containers.
The Docker Secrets documentation states that when running in Swarm mode, secrets are securely stored in the encrypted Raft log and replicated to the other Swarm managers. Docker also provides tools for granting access to additional secrets, revoking access, and rotating secrets. However, when run with ‘regular’ containers, the secrets are much less secure, as we shall see.
Setting up a container with a secret using Docker Compose is relatively straightforward. We’ll define our secret in the bottom section, and tell MySQL to use that secret as the root password.
version: "3.1"
services:
mysql:
image: mysql/mysql-server:latest
container_name: mysql
environment:
MYSQL_ROOT_PASSWORD: /run/secrets/my_secret
secrets:
- my_secret

secrets:
my_secret:
file: ./my_secret.txt
The observant reader may have spotted that the secret points to a file on the host computer’s file system. The weakness here is that this file has to hold the secret in plain text. This is obviously not desirable. We overlook this weakness for now and create the ./my_secret.txt file with a test password and use docker-compose up -d to create our container.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
aaf5d45eb2fe mysql/mysql-server:latest "/entrypoint.sh my..." 24 seconds ago Up 24 seconds 3306/tcp, 33060/tcp mysql
All apparently seems well, our container is running and we can connect to the MySQL server with the root password we set. However, a docker inspect shows us what’s really happening under the hood. As can be seen, it’s a simple bind-mount that mounts the password file into the container, with a few special permissions such as making the file read-only.
This isn’t much more than what is already available in Docker, only that it’s now branded under the secrets name, giving it a (dangerous) sense of security when it really isn’t secure. All the typical problems with regards to mounting password files would apply here as well. In addition, Docker’s surrounding mechanisms for dynamically managing secrets aren’t available when running ‘regular’ containers.
As it currently stands, the recommended way to launch MySQL containers is very much the same as before: Use the MYSQL_RANDOM_ROOT_PASSWORD and MYSQL_ONETIME_PASSWORDmechanisms for MySQL 5.6 and newer. Better support for managing secrets in ‘regular’ containers would be a welcome addition to the Docker ecosystem.

Wednesday, 16 August 2017

50 Unique and Useful Websites TECH 50 UNIQUE AND USEFUL WEBSITES


In the internet world when we surfing the browser we can see millions of websites, blogs, gaming sites. Websites are categorized as personal resource, travel, education, general internet etc. But if you visit a website that may be useful and interested for you but another one feels that’s not special for him.
Internet is an amazing source and they offer some useful websites for the users. Here we go with the list of 50 unique and useful websites on the internet useful for everyone.
1. Alexa.com – The web information company provides commercial web traffic data for everyone.
2. SpeedTest.net – Easy way to test your broadband speed.
3. Iconfinder – Free Icon search engine.
4. Archive.org – The wayback machine to see how the website looks in the past.
5. Goo.gl – Url shortener from Google. Allows you to track, in real-time, the clicks and referrers. You can see your existing links and avoid duplication.
6. StumbleUpon – Website discovery engine. Collection of best pages on the Internet.
7. About.me – A complete professional page about you.
8. Imgur.com – Worlds greatest image hosting and sharing service.
9. Askboth.com – One search and get results from Google, Bing and Twitter
10. Wolframalpha.com – Computation knowledge engine.
11. Evernote – Save your notes for life time.
12. ResizeYourImage.com – Resize your image, its free and easy.
13. GoogleWebDesigner –  A free and easy tool to create animated, 3 HTML5 Ads in minutes.
14. StatsCrop.com – Free Website Analyzer
15. RankSignals.com – Free Backlink checker, can easily categorize nofollow, dofollow, hot links for your website.
16. WeTransfer.com – Share big files for free and secure. Can send up to 2GB in single time.
17. PrivNote.com – Send notes that will self-destruct after being read.
18. Xmarks.com – A powerful tool to Bookmark, Sync and Search.
19. MyFonts.com – Fonts for prints, products and screens. Determine the font name from an image.
20. Chipin.com – Easy way to collect money for events etc.
21. GTMetrix.com – Check your websites speed.
22. Sleepytyi.me – The Bedtime calculator.
23. Snapito.com – Take full length website screenshots.
24. WordCounterTool.com – Accurate word counter and also can use to test your typing speed.
25. SmallSEOTools.com – Prefect plagiarism checker.
26. OnlineConcersion.com – Convert anything to anything.
27. Plaxo.com – Plaoxo helps you to organize, manage, and access your contacts in one place.
28. MiiCard.com – Your online internet identity.
29. TwitterFeed.com – Create feeds and connect with your Twitter account, Facebook profile or pages and LinkedIn profile.
30. ManageFlitter.com – Advanced Twitter profile management tool.
31. Paper.li – News curation platform. Become a news publisher with paper.li and Twitter.
32. Ustream.tv – Worlds best and easiest way to stream live video.
33. Join.me – Free screen sharing with anyone on the web.
34. IMDb.com – Specially for movie lovers. To find who has been in which film and what the name of that actor is.
35. TypingWeb.com – Learn to type. Free typing tutor and lessons.
36. TwitLonger.com – Send tweets longer than 140 characters.
37. TwitterSpirit.com – Set an expiration date or time to your Twitter tweets.
38. Zamzar.com – Online file conversion site that works for hundreds of formats.
39. Google Translate –  Translate texts just typing or as document.
40. Vocaroo.com – Simple online voice recorder and you can download in different formats.
41. Cutmp3.net – Easily cut MP3 files online.
42. Similarsites.com – Find similar websites that you liked.
43. HootSuite.com – Manage multiple social networks from a single dashboard.
44. Quora.com – Source for knowledge. Question and Answer Website.
45. LeanDomainSearch.com – Domain searching tool that helps users to find their favorite domains related domains easily with one click. Lean Domain Search shows thousands of related domains that are available to register.
46. PayPal – Worlds faster and secure online money transferring system. Pay and get paid.
47. Who.is – Find information on any domain name or website.
48. PeekYou.com – Free people search engine. To find your friends other Social Network profiles by username, first name or last name.
49. Safeweb.norton.com – Is your website? Look up a site and get rating.
50. Unfurlr.com – Find the original link behind the short link.

Tuesday, 15 August 2017

Hamilton App Takes the Stage

The Cloud Where It Happens

We love to spend time designing beautiful UIs, testing new interactions, and iterating with clients, and we don't want to be distracted by setting up and maintaining servers. To stay focused on the app and our users, we implemented a full serverless architecture and made heavy use of Firebase.
A key feature of the app is the ticket lottery, which offers fans a chance to get tickets to the constantly sold-out Hamilton show. We used Cloud Functions for Firebase, and a data flow architecture we learned about at Google I/O, to coordinate the lottery workflow between the mobile app, custom business logic, and partner services.
For example, when someone enters the lottery, the app first writes data to specific nodes in Realtime Database and the database's security rules help to ensure that the data is valid. The write triggers a Cloud Function, which runs business logic and stores its result to a new node in the Realtime Database. The newly written result data is then pushed automatically to the app.

What'd I miss?

Because of Hamilton's intense fan following, we wanted to make sure that app users could get news the instant it was published. So we built a custom, web-based Content Management System (CMS) for the Hamilton team that used Firebase Realtime Database to store and retrieve data. The Realtime Database eliminated the need for a "pull to refresh" feature of the app. When new content is published via the CMS, the update is stored in Firebase Realtime Database and every app user automatically sees the update. No refresh, reload, or pull required!

Cloud Functions Left Us Satisfied

Besides powering our lottery integration, Cloud Functions was also extremely valuable in the creation of user profiles, sending push notifications, and our #HamCam — a custom Hamilton selfie and photo-taking experience. Cloud Functions resized the images, saved them in Cloud Storage, and then updated the database. By taking care of the infrastructure work of storing and managing the photos, Firebase freed us up to focus on making the camera fun and full of Hamilton style.

Developing UI? Don't Wait For It.

With only three months to design and deliver the app, we knew we needed to iterate quickly on the UX and UI. Flutter's hot reload development cycle meant we could make a change in our UI code and, in about a second, see the change reflected on our simulators and phones. No rebuilding, recompiling, or multi-second pauses required! Even the state of the app was preserved between hot reloads, making it very fast for us to iterate on the UI with our designers.
We used Flutter's reactive UI framework to implement Hamilton's iconic brand with custom UI elements. Flutter's "everything is a widget" approach made it easy for us to compose custom UIs from a rich set of building blocks provided by the framework. And, because Flutter runs on both iOS and Android, we were able to spend our time creating beautiful designs instead of porting the UI.
The FlutterFire project helped us access Firebase Analytics, Firebase Authentication, and Realtime Database from the app code. And because Flutter is open source, and easy to extend, we even built a custom router library that helped us organize the app's UI code.

What comes next?

We enjoyed building the Hamilton app in a way that allowed us to focus on our users and experiment with new app ideas and experiences. And based on our experience, we'd happily recommend serverless architectures with Firebase and customized UI designs with Flutter as powerful ways for you to save time building your app.
For us, we already have plans how to continue and develop Hamilton app in new ways, and can't wait to release those soon!
If you want to learn more about Firebase or Flutter, we recommend the Firebase docs, the Firebase channel on YouTube, and the Flutter website.
Whether it's opening night for a Broadway musical or launch day for your app, both are thrilling times for everyone involved. Our agency, Posse, collaborated with Hamilton to design, build, and launch the official Hamilton app... in only three short months.
We decided to use Firebase, Google's mobile development platform, for our backend and infrastructure, while we used Flutter, a new UI toolkit for iOS and Android, for our front-end. In this post, we share how we did it.

Friday, 11 August 2017

SWAP SEX FIELD


Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
For example:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
After running your query, the above salary table should have the following rows:| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |

Solution :
Approach 1:update salary
  set sex =
  case
  when sex='m' then 'f'
  when sex='f' then 'm'
  else sex
  end
Approach 2:update salary
set sex = case sex
when 'm' then 'f' else 'm'
end

Thursday, 10 August 2017

BINARY TREE ALL IN ONE



A binary tree is either empty or consists of a node called the root together with two binary trees called the left subtree and the right subtree.
        root
     /       \
  left      right
 /    \      /  \

SOME FACTS:

  • If h = height of a binary tree,
  • max # of leaves = 2h
  • max # of nodes = 2h + 1 – 1
  • Total number of binary trees having n nodes
    • = number of stack-realizable permutations of length n
    • = number of well-formed parentheses (with n left parentheses and n right parentheses)
    • =(1/n+1)(2n C n) [Catalan Number]A binary tree with height h and 2h + 1 – 1 nodes (or 2h leaves) is called a full binary tree
  • A binary tree with n nodes is said to be complete if it contains all the first n nodes of the following numbering scheme
        1
    /      \
    2      3
    / \     /
    4  5  6
  • .Following is not complete binary tree
       4
    /   \
    2     7
    / \     \
    1   3     9
  • In a (balanced) binary tree with m nodes, moving from one level to the next requires one comparison, and there are log_2(m) levels, for a total of log_2(m) comparisons.
  • In contrast, an n-ary tree will require log_2(n) comparisons (using a binary search) to move to the next level. Since there are log_n(m) total levels, the search will require log_2(n)*log_n(m) = log_2(m) comparisons total. So, though n-ary trees are more complex, they provide no advantage in terms of total comparisons necessary.
  • The reason that binary trees are used more often than n-ary trees for searching is that n-ary trees are more complex, but usually provide no real speed advantage.

BINARY TREE TRAVERSAL:

1. Preorder
Visit root, visit left subtree in preorder, visit right subtree in preorder
2. Postorder
Visit left subtree in postorder, right subtree in postorder, then the root
3. Inorder
Visit left subtree in inorder, then the root, then the right subtree in inorder
<strong>Example 1:</strong>
 1
  /    \
2       3

Pre: 123 (root, left, right)
In : 213 (left, root, right)
Post : 231 (left, right, root)
<strong>Example 2 :</strong>
1
  \
   2
      \
        3

Pre: 123 (root, left, right)
In : 123 (left, root, right)
Post : 321 (left, right, root)

PROGRAMMING PERSPECTIVE

A binary tree is a structure comprising nodes, where each node has the following 3 components:
  1. Data element: Stores any kind of data in the node
  2. Left pointer: Points to the tree on the left side of node
  3. Right pointer: Points to the tree on the right side of the node
As the name suggests, the data element stores any kind of data in the node.
The left and right pointers point to binary trees on the left and right side of the node respectively.
If a tree is empty, it is represented by a null pointer.
Commonly-used terminologies
  • Root: Top node in a tree
  • Child: Nodes that are next to each other and connected downwards
  • Parent: Converse notion of child
  • Siblings: Nodes with the same parent
  • Descendant: Node reachable by repeated proceeding from parent to child
  • Ancestor: Node reachable by repeated proceeding from child to parent.
  • Leaf: Node with no children
  • Internal node: Node with at least one child
  • External node: Node with no children

BINARY TREE JAVA IMPLEMENTATION :/*
 *  Binary Tree Java Implementation
 *  Includes tree traversal. (Preorder, Postorder, Inorder)
 */

 import java.util.Scanner;

 /* Class BTNode */
 class BTNode
 {  
     BTNode left, right;
     int data;

     /* Constructor */
     public BTNode()
     {
         left = null;
         right = null;
         data = 0;
     }
     /* Constructor */
     public BTNode(int n)
     {
         left = null;
         right = null;
         data = n;
     }
     /* Function to set left node */
     public void setLeft(BTNode n)
     {
         left = n;
     }
     /* Function to set right node */
     public void setRight(BTNode n)
     {
         right = n;
     }
     /* Function to get left node */
     public BTNode getLeft()
     {
         return left;
     }
     /* Function to get right node */
     public BTNode getRight()
     {
         return right;
     }
     /* Function to set data to node */
     public void setData(int d)
     {
         data = d;
     }
     /* Function to get data from node */
     public int getData()
     {
         return data;
     }    
 }

 /* Class BT */
 class BT
 {
     private BTNode root;

     /* Constructor */
     public BT()
     {
         root = null;
     }
     /* Function to check if tree is empty */
     public boolean isEmpty()
     {
         return root == null;
     }
     /* Functions to insert data */
     public void insert(int data)
     {
         root = insert(root, data);
     }
     /* Function to insert data recursively */
     private BTNode insert(BTNode node, int data)
     {
         if (node == null)
             node = new BTNode(data);
         else
         {
             if (node.getRight() == null)
                 node.right = insert(node.right, data);
             else
                 node.left = insert(node.left, data);            
         }
         return node;
     }    
     /* Function to count number of nodes */
     public int countNodes()
     {
         return countNodes(root);
     }
     /* Function to count number of nodes recursively */
     private int countNodes(BTNode r)
     {
         if (r == null)
             return 0;
         else
         {
             int l = 1;
             l += countNodes(r.getLeft());
             l += countNodes(r.getRight());
             return l;
         }
     }
     /* Function to search for an element */
     public boolean search(int val)
     {
         return search(root, val);
     }
     /* Function to search for an element recursively */
     private boolean search(BTNode r, int val)
     {
         if (r.getData() == val)
             return true;
         if (r.getLeft() != null)
             if (search(r.getLeft(), val))
                 return true;
         if (r.getRight() != null)
             if (search(r.getRight(), val))
                 return true;
         return false;        
     }
     /* Function for inorder traversal */
     public void inorder()
     {
         inorder(root);
     }
     private void inorder(BTNode r)
     {
         if (r != null)
         {
             inorder(r.getLeft());
             System.out.print(r.getData() +" ");
             inorder(r.getRight());
         }
     }
     /* Function for preorder traversal */
     public void preorder()
     {
         preorder(root);
     }
     private void preorder(BTNode r)
     {
         if (r != null)
         {
             System.out.print(r.getData() +" ");
             preorder(r.getLeft());            
             preorder(r.getRight());
         }
     }
     /* Function for postorder traversal */
     public void postorder()
     {
         postorder(root);
     }
     private void postorder(BTNode r)
     {
         if (r != null)
         {
             postorder(r.getLeft());            
             postorder(r.getRight());
             System.out.print(r.getData() +" ");
         }
     }    
 }

 /* Class BinaryTree */
 public class BinaryTree
 {
     public static void main(String[] args)
    {          
        Scanner scan = new Scanner(System.in);
        /* Creating object of BT */
        BT bt = new BT();
        /*  Perform tree operations  */
        System.out.println("Binary Tree Test\n");        
        char ch;      
        do  
        {
            System.out.println("\nBinary Tree Operations\n");
            System.out.println("1. insert ");
            System.out.println("2. search");
            System.out.println("3. count nodes");
            System.out.println("4. check empty");

            int choice = scan.nextInt();          
            switch (choice)
            {
            case 1 :
                System.out.println("Enter integer element to insert");
                bt.insert( scan.nextInt() );                    
                break;                        
            case 2 :
                System.out.println("Enter integer element to search");
                System.out.println("Search result : "+ bt.search( scan.nextInt() ));
                break;                                        
            case 3 :
                System.out.println("Nodes = "+ bt.countNodes());
                break;    
            case 4 :
                System.out.println("Empty status = "+ bt.isEmpty());
                break;          
            default :
                System.out.println("Wrong Entry \n ");
                break;  
            }
            /*  Display tree  */
            System.out.print("\nPost order : ");
            bt.postorder();
            System.out.print("\nPre order : ");
            bt.preorder();
            System.out.print("\nIn order : ");
            bt.inorder();

            System.out.println("\n\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);                      
        } while (ch == 'Y'|| ch == 'y');              
    }
 }

APPLICATIONS OF BINARY TREES

  • Binary Search Tree – Used in many search applications where data is constantly entering/leaving, such as the map and set objects in many languages’ libraries. These are a data structure in which searching, insertion, and removal are all very fast (about log(n) operations).
  • Binary Space Partition – Used in almost every 3D video game to determine what objects need to be rendered.
  • Binary Tries – Used in almost every high-bandwidth router for storing router-tables.
  • Hash Trees – used in p2p programs and specialized image-signatures in which a hash needs to be verified, but the whole file is not available.
  • Heaps – Used in implementing efficient priority-queues, which in turn are used for scheduling processes in many operating systems, Quality-of-Service in routers, and A* (path-finding algorithm used in AI applications, including robotics and video games). Also used in heap-sort.
  • Huffman Coding Tree – used in compression algorithms, such as those used by the .jpeg and .mp3 file-formats.
  • GGM Trees – Used in cryptographic applications to generate a tree of pseudo-random numbers.
  • Syntax Tree – Constructed by compilers and (implicitly) calculators to parse expressions.
  • Treap – Randomized data structure used in wireless networking and memory allocation.
  • T-tree – Though most databases use some form of B-tree to store data on the drive, databases which keep all (most) their data in memory often use T-trees to do so.
  • a Manipulate hierarchical data
  • Make information easy to search (see tree traversal)
  • Manipulate sorted lists of data
  • Use as a workflow for compositing digital images for visual effects
  • Use in router algorithms