Friday, 29 January 2021

Custom single threaded java server

 package com.diffengine.csv;


import java.io.*;

import java.net.*;

import java.util.Date;


public class Server {


public static void main(String[] args) {

System.out.println("starting");

try (ServerSocket serverSocket = new ServerSocket(3333)) {

System.out.println("Server is listening on port " + 3333);

while (true) {

Socket socket = serverSocket.accept();

System.out.println("New client connected");

OutputStream output = socket.getOutputStream();

PrintWriter writer = new PrintWriter(output, true);

writer.println("HTTP/1.1 200 OK\r\n\r\n" +new Date().toString());

writer.close();

output.close();

socket.close();

}

} catch (IOException ex) {

System.out.println("Server exception: " + ex.getMessage());

ex.printStackTrace();

}

}

}


Friday, 22 March 2019

Tensor Flow from novice to expert - Part1

https://github.com/tensorflow/nmt

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 21:21:01 2017

@author: krishgu
"""

import tensorflow as tf
node1 = tf.constant(3.0,tf.float32)
node2 = tf.constant(4.0)
# Printing it
print("Printing node1 node2 - %s" % node1,node2)

# Performing the operations in graph using session
sess=tf.Session()
print("Printing node1 node2 values - %s" % sess.run([node1,node2]))


#sample computation with constant value
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)

d=tf.multiply(a,b)
e=tf.add(c,b)

f=tf.subtract(d,e)

sess=tf.Session()
outs=sess.run(f)
sess.close()

print("outs = {}".format(outs))


#performing it with dynamic value
a= tf.placeholder(tf.float32)
b= tf.placeholder(tf.float32)

adder_node = a+b
sess= tf.Session()
print(sess.run(adder_node,{a:[1,2,3,4,5],b:[1,2,3,4,5]}))


#Perfroming it with variable values
w = tf.Variable([.3],tf.float32)
b = tf.Variable([-.3],tf.float32)
x = tf.placeholder(tf.float32)

linear_model=w*x+b;
init = tf.global_variables_initializer()
print(w)
print(b)
sess = tf.Session()
sess.run(init)
print(sess.run(w))
print(sess.run(b))
print(sess.run(linear_model,{x:[1,2,3,4]}))

linkedin

package com.linkedin.messaging;

User contacts and direct messaging are obtained through the features “r_network” and “w_messages,” respectively, both of which will be retired with this change. With this retirement, any direct sharing or contact related features that utilize LinkedIn contacts will no longer function after May 12th, 2015.


import java.util.Scanner;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.apis.LinkedInApi;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class LinkedInTest2 {
private static final String PROTECTED_RESOURCE_URL = "https://api.linkedin.com/v1/people/~";
private static String API_KEY = "81tqxy39b";

private static String API_SECRET = "bQg1l1hQzcKtL4";
private LinkedInTest2() {
}

public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
final OAuth10aService service = new ServiceBuilder(API_KEY).apiSecret(API_SECRET).callback("https://www.google.co.in")
.build(LinkedInApi.instance());
final Scanner in = new Scanner(System.in);

System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();

// Obtain the Request Token
System.out.println("Fetching the Request Token...");
final OAuth1RequestToken requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();

System.out.println("Now go and authorize ScribeJava here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
final String oauthVerifier = in.nextLine();
System.out.println();

// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();

// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());

System.out.println();
System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)");
}
}

JSPDF with Angular (Acro forms are not included)

JSPDF :- If you want to print a pdf from web page

1. Run below commands to get the code base.
npm install jspdf --save

typings install dt~jspdf --global --save

npm install @types/jspdf --save

2. Create html and wire to Angular component :- Invoke printAdapter from there

3. Create a class in typescript : - Copy paste below code

const jsPDF = require('jspdf'); // or import * as jsPDF from 'jspdf' or import jsPDF from 'jspdf'
printValues(img) {
const doc = new jsPDF();
doc.addImage(img, 'PNG', 2, 5, 60, 30);
doc.text(70, 20, 'Web');
doc.setTextColor(255, 0, 0);
doc.text(140, 20, 'Confidential');
const reportTitle = 'This is a confidential report';
const splitTitle = doc.splitTextToSize(reportTitle, 180);
doc.text(2, 44, splitTitle);
doc.setTextColor(0, 0, 0);
doc.setLineWidth(0.5);
doc.text(60, 64, 'list section').setFillColor(0, 0, 0);
doc.text(2, 69, 'name :');
doc.text(50, 69, 'India');
doc.line(50, 69.5, 68, 69.5);
doc.text(2, 79, 'Code :');
doc.text(50, 79, 'INH');

doc.setDrawColor(0);
doc.setFillColor(211, 211, 211);
doc.rect(1, 99, 200, 10, 'F');


doc.setFontSize(12);
doc.setFontType('bold');
doc.text('ComboBox:', 10, 105);

doc.rect(20, 120, 5, 5); // empty square
doc.line(20, 120, 18, 118);
doc.text(20, 120, '✓');

doc.rect(40, 120, 10, 10, 'F'); // filled square

doc.setDrawColor(255, 0, 0);
doc.rect(60, 120, 10, 10); // empty red square

doc.setDrawColor(255, 0, 0);
doc.rect(80, 120, 10, 10, 'FD'); // filled square with red borders

doc.setDrawColor(0);
doc.setFillColor(255, 0, 0);
doc.rect(100, 120, 10, 10, 'F'); // filled red square

doc.setDrawColor(0);
doc.setFillColor(255, 0, 0);
doc.rect(120, 120, 5, 5, 'FD'); // filled red square with black borders

doc.setDrawColor(0);
doc.setFillColor(255, 255, 255);
doc.roundedRect(140, 120, 5, 5, 3, 3, 'FD'); // Black square with rounded corners

doc.save('FirstSample.pdf');
}

printAdapter() {
this.getImageFromUrl('http://localhost:4200/assets/images/logo.png'); // Path to image
}

getImageFromUrl(url) {
const current = this;
const img = new Image();
img.onload = function () {
current.printValues(img);
};
img.src = url;
}

Wednesday, 18 April 2018

FTL looping over map

FTL interating over a map :-

List<String> cityList1 = new ArrayList<String>();
cityList.add("Washington DC");

List<String> cityList2 = new ArrayList<String>();
cityList2.add("Berlin");
cityList2.add("Paris");
cityList2.add("Rome");

Map<String,List<String>> map = new HashMap<String,List<String>>();
map.put("US",cityList1);
map.put("UK",cityList2);

approach 1 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 2 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map.values[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 3 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map?values[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 4 :-
<#list map.entrySet() as entry>
    //looping map valuesfor the key we can set it to UI component
    <#list entry.key as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 5 :-
<#list map.entrySet() as entry>
     <#assign keyValue="${entry.key}">
    //looping map valuesfor the key we can set it to UI component
    <#list keyValue as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 6 :-
<#list map?keys as key>
    <#assign keyValue="map[key]">
    //looping map valuesfor the key we can set it to UI component
    <#list keyValue as city>
       <b> ${city} </b>
     </#list>
</#list>

Tuesday, 13 February 2018

HTML parser

package org.tiaa.indiatraining.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;

import java.net.URLConnection;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanEngine {
private static final Logger LOGGER = Logger.getLogger(ScanEngine.class.getName());
List<String> tags = Arrays.asList("<title>,</title>", "<body>,</body>");
private static final String HTML_A_TAG_PATTERN = "(?i)<a([^>]+)>(.+?)</a>";
private static final String HTML_IMG_TAG_PATTERN ="(?i)<img\\s+(.*?)/?>";

public static URLConnection connect(String connectionString) {
URL url;
URLConnection conn = null;
try {
url = new URL(connectionString);
conn = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}

public static BufferedReader getStream(URLConnection con) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
return in;
}

public static StringBuilder parse(BufferedReader in){
       StringBuilder sb = new StringBuilder();
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
       return sb;
}

public static void invokeScanEngine(String url) {
try {
URLConnection con = connect(url);
LOGGER.log(Level.INFO,"Hostname :-"+ getHost(con));
LOGGER.log(Level.INFO,"IpAddress :-"+ getIpAddress(con));
BufferedReader in  = getStream(con);
if(in!=null){
StringBuilder sb = parse(in);
LOGGER.log(Level.INFO,"Submitted On :-"+getTime());
LOGGER.log(Level.INFO,"Title :-"+extractTag(sb,"<title>","</title>").trim());
LOGGER.log(Level.INFO,"Body :-"+extractTag(sb,"<body","</body>").trim());
LOGGER.log(Level.INFO,"Count of links :-"+countTag(sb,HTML_A_TAG_PATTERN));
LOGGER.log(Level.INFO,"Count of images :-"+countTag(sb,HTML_IMG_TAG_PATTERN));
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static String getIpAddress(URLConnection con) throws UnknownHostException {
InetAddress address = InetAddress.getByName(getHost(con));
String ip = address.getHostAddress();
return ip;
}

private static String getHost(URLConnection con) {
return con.getURL().getHost();
}

public static String extractTag(StringBuilder sb ,String startElement,String endElement){
int start = sb.indexOf(startElement);
int end = sb.indexOf(endElement);
String title = sb.substring(start+startElement.length(),end);
return title;
}

public static void main(String args[]){
invokeScanEngine("http://intranet.ops.tiaa-cref.org/");
//System.out.println("krishna".substring(0,"krishna".length()-1));
}

public static String getTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String date = sdf.format(timestamp);
return date;
}

public static int countTag(StringBuilder sb ,String expression){
Pattern patternTag = Pattern.compile(expression);
Matcher matcherTag = patternTag.matcher(sb);
        int count = 0;
while (matcherTag.find()) {
count = count +1;
}
return count;
}
}

Thursday, 6 July 2017

Angular $broadcast ,$On and $emit for novice

Intercommunication and eventing :- $brodcast and $emit falls under intercommunication between controllers. There are other ways also like having data in parent and root controller and one other way is getting data from service. $on is unitized for event registering on scopes. Broadcast is like jms broadcasting it will send a copy to everyone. Emit will send it only to its parents  its something like inheritance in java. Please have a look at below program and output to understand it clearly.

Example :- 
<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script >
"use strict";
var allScopes = {};
      var angModule = angular.module("app",[]);
function globalController(ctrlName){
  return function($scope){
  console.log("entering controller");
          //Registering event on individual scope
     $scope.$on("customMessage",function(e,opt){
     console.log("Controller :-"+ ctrlName + " recievedMessage "+opt.message);
 })
allScopes[ctrlName]=$scope;
  };  
}
angModule.controller("tcmController",globalController("tcmController"))
.controller("projectController",globalController("projectController"))
.controller("defectsController",globalController("defectsController"))
.controller("jiraController",globalController("jiraController"))
.controller("rtcController",globalController("rtcController"))
.run(function($timeout,$rootScope){
 console.log("entering run");
          //Registering event on global scope
  $rootScope.$on("customMessage",function(e,opt){
     console.log("root Controller recievedMessage "+opt.message);
 });
  allScopes["root"]= $rootScope;  
  $timeout(function(){
   console.log("entering timeout");
//broadcast will communicate to everyone in the scope
     $rootScope.$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //emit will communicate to everyone in the inheritance heiracrhy scope
     allScopes["projectController"].$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //To see the result run them individually by commenting them out
  },1000);
});
</script>
 
  </head>
  <body>
 <div  ng-app="app">
    <div  ng-controller="tcmController">
       <div  ng-controller="projectController">
       </div>
  <div  ng-controller="defectsController">  
       </div>
   </div>
       <div  ng-controller="jiraController">  
       </div>
  <div  ng-controller="rtcController">  
      </div>
</div>
  </body>
</html>

Output for $emit :- 
Controller :-projectController recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
 root Controller recievedMessage broadcasting from root


Output for $broadcast:-
root Controller recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
Controller :-projectController recievedMessage broadcasting from root
Controller :-defectsController recievedMessage broadcasting from root
Controller :-jiraController recievedMessage broadcasting from root
Controller :-rtcController recievedMessage broadcasting from root

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...