Monday, July 27, 2020

Data Structures

Infix to Postfix expression conversion using stack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
 
namespace InfixToPostfix
{
    class Program
    {
        const string StrRegex = @"[A-Za-z0-9]";
        private static Regex _regex;
 
        public static Regex Regex
        {
            get
            {
                if (_regex == null)
                    _regex = new Regex(StrRegex);
                return _regex;
            }
        }
 
        static void Main(string[] args)
        {
            //Infix to Postfix
            //Req: Give only valid exp, as exp validation is not done in this code.
            var operandStack = new Stack<char>();
            var operatorStack = new Stack<char>();
 
            var infixExpression = "(A+B)+a/b+c*d+(c*(d+e))";
            infixExpression.Trim();
 
            foreach (char item in infixExpression)
            {
                if (IsNotOperator(item))
                {
                    operandStack.Push(item);
                    PrintStackState(operandStack, operatorStack);
                    continue;
                }
 
                if (item == '(')
                    operatorStack.Push(item);
                else if (item == ')')
                {
                    do
                    {
                        var op = operatorStack.Pop();
                        if (op == '(')
                            break;
 
                        operandStack.Push(op);
                    } while (true);
                }
                else
                {
                    AddOperator(operandStack, operatorStack, item);
                }
 
                PrintStackState(operandStack, operatorStack);
            }
 
            while (operatorStack.Count > 0)
            {
                var op = operatorStack.Pop();
                operandStack.Push(op);
            }
 
            PrintStackState(operandStack, operatorStack);
 
            var resultSet = operandStack.Reverse().Select(x => x.ToString()).ToList();
            var result = string.Join("", resultSet);
            Console.WriteLine("PostFix: " + result);
            Console.ReadLine();
        }
 
        private static void PrintStackState(Stack<char> operandStack, Stack<char> operatorStack)
        {
            Console.WriteLine("/**********/");
            Console.WriteLine($"OperandStack {string.Join(",", operandStack.Select(x => x.ToString()).ToList())}");
            Console.WriteLine($"OperatorStack {string.Join(",", operatorStack.Select(x => x.ToString()).ToList())}");
            Console.WriteLine("/**********/");
        }
 
        private static void AddOperator(Stack<char> operandStack, Stack<char> operatorStack, char item)
        {
            if (operatorStack.Count == 0 || IsCorrectPrecedence(item, operatorStack.Peek()))
            {
                operatorStack.Push(item);
                return;
            }
            else
            {
                var op = operatorStack.Pop();
                operandStack.Push(op);
                AddOperator(operandStack, operatorStack, item);
            }
        }
 
        private static bool IsCorrectPrecedence(char item, char operatorStackTop)
        {
            if (operatorStackTop == '(')
                return true;
 
            if (item == '/')
                return true;
            else if (operatorStackTop == '/')
                return false;
            else if (item == '*')
                return true;
            else if (operatorStackTop == '*')
                return false;
 
            return true;
        }
 
        static bool IsNotOperator(char item)
        {
            return Regex.IsMatch(item.ToString());
        }
    }
}

Postfix to Infix expression conversion using stack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
 
namespace PostfixToInfix
{
    class Program
    {
        const string StrRegex = @"[A-Za-z0-9]";
        private static Regex _regex;
 
        public static Regex Regex
        {
            get
            {
                if (_regex == null)
                    _regex = new Regex(StrRegex);
                return _regex;
            }
        }
 
        static void Main(string[] args)
        {
            // Postfix to Infix
            //Req: Give only valid exp, as exp validation is not done in this code.
            var operandStack = new Stack<string>();
 
            var postfixExpression = "AB+ab/cd*cde+*+++";
            postfixExpression.Trim();
 
            foreach (char item in postfixExpression)
            {
                if (IsNotOperator(item))
                {
                    operandStack.Push(item.ToString());
                }
                else
                {
                    var rhsOperand = operandStack.Pop();
                    var lhsOperand = operandStack.Pop();
                    var result = $"({lhsOperand}{item}{rhsOperand})";
                    operandStack.Push(result);
                }
 
                PrintStackState(operandStack);
            }
 
            Console.WriteLine("PostFix: " + operandStack.Pop());
            Console.ReadLine();
        }
 
        private static void PrintStackState(Stack<string> operandStack)
        {
            Console.WriteLine("/**********/");
            Console.WriteLine($"OperandStack {string.Join(",", operandStack.Select(x => x.ToString()).ToList())}");
            Console.WriteLine("/**********/");
        }
 
        static bool IsNotOperator(char item)
        {
            return Regex.IsMatch(item.ToString());
        }
    }
}

Thursday, July 23, 2020

new Date() issue in Javascript, Get UTC date in Javascript

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
  var d = new Date("2020-07-01");
  document.getElementById("demo").innerHTML = d + ' ' + d.getTimezoneOffset();;
  d= new Date(d.getTime() + d.getTimezoneOffset() * 60000)
  document.getElementById("demo1").innerHTML =  d
</script>
</body>
</html>

Tuesday, October 9, 2018

HTML2CANVAS and Google Maps Screenshot Cropping / Partial Image Issue Fixed with below Example.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Google Maps Multiple Markers</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]&callback=InitMap">
    </script>
    <script type="text/javascript" src="html2canvas.js"></script>
</head>
<body>
    <div id="map" style="width: 640px; height: 480px;"></div>
    <input type="button" value="Take Screenshot Of Div" onclick="Screenshot();" />
    <div id="img-out" width="640px" height="480px"></div>
    
    <script type="text/javascript">
        var map;
        function InitMap(){
        var locations = [
          ['Bondi Beach', -33.890542, 151.274856, 4],
          ['Cronulla Beach', -34.028249, 151.157507, 3],
          ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
          ['Maroubra Beach', -33.950198, 151.259302, 1]
        ];

        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 11,
      disableDefaultUI: true,
          center: new google.maps.LatLng(-33.92, 151.25),
          mapTypeId: google.maps.MapTypeId.TERRAIN
        });

        var marker, i;
        for (i = 0; i < locations.length; i++) {
          marker = new google.maps.Marker({
    title: locations[i][0],
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
          });
        }
    }

    function Screenshot(){
    //Inspect the element and find .gm-style>div:first>div:first>div:last>div -> May vary from versions
    var transform=$(".gm-style>div:first>div:first>div:last>div").css("transform");
    console.log(transform);
    var comp=transform.split(",") //split up the transform matrix
    var mapleft=parseFloat(comp[4]) //get left value
    var maptop=parseFloat(comp[5])  //get top value
    $(".gm-style>div:first>div:first>div:last>div").css({ 
    "transform":"none",
    "left":mapleft,
    "top":maptop,
    });
    html2canvas(document.getElementById('map'),
    {
    useCORS: true
    }).
    then(function(canvas)
    {
    $("#img-out").append(canvas);
    $(".gm-style>div:first>div:first>div:last>div").css({
    left:0,
    top:0,
    "transform":transform
    })
    }
    );
    }
    </script>
</body>
</html>

OUTPUT:


REF :  https://github.com/niklasvh/html2canvas/issues/1568  & https://stackoverflow.com/questions/24046778/html2canvas-does-not-work-with-google-maps-pan/24281734#24281734

Tuesday, July 4, 2017

Linking 2 SQL DBs in diff servers


Scenario LINK DB 1 in server 1 and DB 2 in server 2, to fetch the data from  DB2 in DB 1

Creating a link in DB1

USE master;
GO
EXEC sp_addlinkedserver  
   N'server2',
   N'SQL Server';
GO

--Set up login mappings.
EXEC sp_addlinkedsrvlogin N'server2', 'false', NULL, 'username', 'password';
 
GO

select * from [server2].[dbname].[dbo].[tablename] 

Sunday, July 2, 2017

Angular Basics


Angular: Is a JS framework which helps us to build web pages effectively. SPA(Single Page Applications) can be implemented using Angular.

SPA > Only one HTML page is served from the server along with a bundle of JS, the JS bundle controls and renders the DOM elements on the page based on the user routes.This helps to avoid server calls for each page and increases the performance of the Application and re-activeness of the Web page.

Angular CLI(Command Line Instruction) > Is a set of tools that can be used to create, manage and build angular applications.

Core Parts of an Angular app:

  • Main.ts=> Part where the execution of our application starts, it specifies the bootstrap module and other configs
  • Module=> Modules are the place where we declare the various objects(directives, services, other imported modules, bootstrap component etc.) we use in our application. Basically, modules declare and set up the environment in which our app runs. 
  • Directives=> Directives are used to specify the special meaning to the DOM elements in our HTML file.
  • Services=> Singleton services help us in organizing and sharing the code base across our app. Services are mainly used in organizing http calls and shared data across the app.

MODULES are identified by @ngModule Decorator and have sections like Declarations(to declare the directives, pipes etc), Providers(to declare the services both custom and built-in), Imports(to declare the built-in modules used and user-defined modules), Bootstrap(to declare the bootstrap component of the application)

DIRECTIVES are of 3 types:
  • Structural directives(modify/inject the DOM elements structures based on the conditions).
  • Attribute directives(alter the attribute/properties of the DOM element custom attribute directives can be created using @Directive decorator).
  • Components(it is a special type of directive which has an HTML template associated with it. Components are the building blocks of our app. Components inject the associated HTML templates where ever the component selector is present. Components are identified by the @Component decorator).
PIPES help us in transforming the data to the appropriate form and displaying to the user. Custom pipes can be created using the @pipes directive. Some of the built-in pipes are date, lowercase, uppercase, currency etc.


Steps to set up an angular project:

  1. Install Node JS from https://nodejs.org/en/. (though we are not going to code in node, it is a requirement for the CLI),
  2. Install angular CLI by running the command : npm install -g @angular/cli
  3. Create a new angular project by using command : ng new project-name (eg: C:\Project> ng new SampleProject)
  4. To run the application navigate into the new project and use the command ng serve (eg: C:\Project\SampleProject> ng serve).This will run a local server which will host the application. You can view the output/application by using the localhost URL specified in the console.
Example:localhost:4200
 




  1. The project can be opened using Sublime, VS code etc.
  2. The  project structure looks like the following: 
  3. The index.html file will be the only html file served by the server, and all other components will be bundled and sent to the browser.
  4. main.ts file is the first/start file to be executed in the application, which provides the information about bootstrap module and enable prod mode.
  5. By default AppModule is the bootstrap module. (Module is nothing but the container/package of components. It has 4 attributes, Declarations: List of Components the system must know and use. Imports: To declare the custom modules in the application, which in turn is a module by itself. Bootstrap: Which component must be know by the index,html on startup. Providers: To declare the services).                                        
  6. By default in app.module.ts, AppComponent is set as bootstrap component. Thus, AppComponent is the component to be known by index.html at first.
  7. The contents of index.html is:                          the custom tag "<app-root></app-root>", is nothing but the selector of a "bootstrap-component" which will be replaced by the template of the particular component. In this case,
    "<app-root></app-root>" is the selector of AppComponent, thus the tag
    "<app-root></app-root>" is replaced by the tempate specified in appcomponent.
 


Adding a new component and using it in app.component:
  1.  We can either add modules manually or create them using the following command ng g c component-name
    (eg: C:\Project\SampleProject> ng g c newComponent)
After a new component is created in order to use them, we must make the system to know there is a component which is done by adding a entry on the app.module.ts inside the declarations. Once this is done, we can use the selector of this new component in any others and its template will be rendered.


Output:





FORMS:

  • TEMPLATE DRIVEN FORM
  • REACTIVE FORM(MODEL DRIVEN FORM)

TEMPLATE DRIVEN FORMS the form-controls are not generated from the code side rather (hardcoded on the template file) generated and managed by the directives. They are asynchronous in nature as the work of rendering is deligated and managed by parent and child directives. This leads to a special type of error "Changed after checked" when the form is very much reactive in nature.

REACTIVE FORM, on the other hand, all the controls are generated and managed form the ts files and they are synchronous in nature. The 3 basic components in a Reactive form are FormControl, FormGroup, FormArray.

eg.
ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { User } from './user.interface';

@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
    heroForm:FormGroup;
   name=new FormControl("initialvalue",Validators.required);
    sampleFormGrp=new FormGroup({
        controlInsideForm:new FormControl("Control inside form",Validators.required)
    });   
       
    constructor(private _fb: FormBuilder) {
     
    }

    ngOnInit() {
         this.heroForm = this._fb.group({
        name: ['using formbuilder it is easy to manage and maintain the formgrps', Validators.required ],
        });
    }
    }

html:
<form>
    <input type="text" [formControl]="name" />
    {{name.status}}
    </form> 
   
    <form [formGroup]="sampleFormGrp">
      <input type="text" formControlName="controlInsideForm" />
      </form>
sampleFormGrp values: {{sampleFormGrp.value| json}}
controlInsideForm value: {{sampleFormGrp.get("controlInsideForm").value}}
controlInsideForm status: {{sampleFormGrp.get("controlInsideForm").status}}
sampleFormGrp status: {{sampleFormGrp.status}}



<form [formGroup]="heroForm">
      <input type="text" formControlName="name" />
      </form>