Thursday, January 4, 2024

Graph QL Simple working example

Here's a simple working tutorial on creating a GraphQL server using Node.js and Express, with a basic query and mutation. We'll be using the Apollo Server Express library to create the GraphQL server.

  1. Install Node.js: If you don't have Node.js installed, download and install it from the official website: https://nodejs.org/
  1. Create a new project folder: Create a new folder for your project and navigate to it in your terminal or command prompt.
  1. Initialize the project: Run the following command to initialize a new Node.js project:


npm init -y

  1. Install required packages: Install Express, Apollo Server Express, and GraphQL using the following command:

npm install express apollo-server-express graphql

  1. Create the GraphQL schema: Create a file named schema.graphql in your project folder and add the following schema definition:

type Query { hello: String } type Mutation { setMessage(message: String!): String }

Here we define a simple query hello that returns a string and a mutation setMessage that takes a string as input and returns a string.

  1. Create the server: Create a file named index.js in your project folder and add the following code:

const express = require("express"); const { ApolloServer, gql } = require("apollo-server-express"); const fs = require("fs"); // Read the schema from the schema.graphql file const typeDefs = gql(fs.readFileSync("schema.graphql", "utf8")); // Set up the resolvers const resolvers = { Query: { hello: () => "Hello, world!", }, Mutation: { setMessage: (_, { message }) => message, }, }; // Create the Apollo Server const server = new ApolloServer({ typeDefs, resolvers }); // Create the Express app const app = express(); // Apply the Apollo middleware to the Express app server.applyMiddleware({ app }); // Start the server const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`GraphQL server running at http://localhost:${PORT}${server.graphqlPath}`) );

In this code, we create a simple Express app and an Apollo Server with the schema and resolvers. The hello query returns a static string, and the setMessage mutation returns the input message.

  1. Start the server: Run the following command in your terminal or command prompt:

node index.js

Your GraphQL server should now be running at http://localhost:4000/graphql.

  1. Test your GraphQL server: Open a web browser and navigate to http://localhost:4000/graphql. You should see the GraphQL Playground interface. Run the following query and mutation in the playground:

query { hello } mutation { setMessage(message: "This is a test message!") }

You should see the appropriate responses for the query and mutation.

That's it! You now have a simple working GraphQL server using Node.js, Express, and Apollo Server Express. You can expand the schema and resolvers to handle more complex data and operations as needed.

Saturday, November 4, 2023

Sorting on the basis of multiple fields

 function sortObjects(arr) {

arr.sort(function(a, b) { if (a.adviserid < b.adviserid) { return -1; } else if (a.adviserid > b.adviserid) { return 1; } else { if (a.cutomer_id < b.cutomer_id) { return -1; } else if (a.cutomer_id > b.cutomer_id) { return 1; } else { if (a.account_id < b.account_id) { return -1; } else if (a.account_id > b.account_id) { return 1; } else { if (a.product_type === b.product_type) { if (a.account_id > b.account_id) { return -1; } else if (a.account_id < b.account_id) { return 1; } } return 0; } } } }); // Group the array by adviserid var groupedArr = []; var currentAdviserId = null; for (var i = 0; i < arr.length; i++) { var obj = arr[i]; if (obj.adviserid !== currentAdviserId) { currentAdviserId = obj.adviserid; groupedArr.push([]); } groupedArr[groupedArr.length - 1].push(obj); } return groupedArr; }

Here's how you would use this function:

// Example array of objects var arr = [ { adviserid: 1, cutomer_id: "abc", account_id: 10, product_type: "A" }, { adviserid: 1, cutomer_id: "abc", account_id: 20, product_type: "A" }, { adviserid: 1, cutomer_id: "def", account_id: 30, product_type: "B" }, { adviserid: 2, cutomer_id: "ghi", account_id: 40, product_type: "A" } ]; // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log(sortedArr);

In this example, the arr array contains four objects with adviserid, cutomer_id, account_id, and product_type properties. The sortObjects function sorts the array based on the three fields you specified (in ascending order), and then groups the sorted array by adviserid. The sorted and grouped array is then printed to the console.

In the sorting logic, the function first sorts by adviserid, then by cutomer_id, and then by account_id. If two objects have the same product_type, they are sorted by account_id in descending order. If two objects have the same adviserid, they are grouped together in the output array.




Sure, here's an example JavaScript function that sorts an array of objects based on the three fields you specified:

function sortObjects(arr) { arr.sort(function(a, b) { if (a.adviserId < b.adviserId) { return -1; } else if (a.adviserId > b.adviserId) { return 1; } else { if (a.priority < b.priority) { return -1; } else if (a.priority > b.priority) { return 1; } else { if (a.accountId < b.accountId) { return 1; } else if (a.accountId > b.accountId) { return -1; } else { return 0; } } } }); return arr; } // Example array of objects var arr = [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ]; // Print the input array console.log("Input: ", arr); // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log("Output: ", sortedArr);

In this example, the arr array contains four objects with adviserId, priority, and accountId properties. The sortObjects function sorts the array based on the three fields you specified, with priority being sorted in ascending order. If two objects have the same priority, they are sorted by accountId in descending order. The input and output arrays are then printed to the console.

The output of this function will be:

Input: [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ] Output: [ { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 2, priority: 1, accountId: 40 }, { adviserId: 2, priority: 1, accountId: 10 } ]

Wednesday, August 2, 2023

Decorator Design Pattern

Decorator Design Pattern in Java


The Decorator design pattern is a structural pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It is used when we want to add new functionality to an object without modifying its structure.


The pattern involves creating a decorator class, which wraps the original object and provides additional functionality by dynamically adding new behavior to it. The decorator class has the same interface as the original object, allowing it to be used interchangeably with the original object.


The Decorator pattern consists of four main components:


  1. Component: This is the interface that defines the methods that will be implemented by the concrete components and decorators.
  1. Concrete Component: This is the class that provides the basic implementation of the component interface.
  1. Decorator: This is the abstract class that implements the component interface and contains a reference to the component object. The decorator class has a constructor that takes a component object as an argument, and it can add new behavior to the component by overriding its methods.
  1. Concrete Decorator: This is the class that extends the decorator class and adds new behavior to the component.

The Decorator pattern is useful when we want to add new functionality to an object at runtime, without modifying its structure. It allows us to mix and match different behaviors dynamically, providing greater flexibility and modularity to the code.



Example:


//Component interface

interface Pizza {

 public String getDescription();

 public double getCost();

}




//Concrete component

class BasicPizza implements Pizza {

 public String getDescription() {

     return "Pizza with tomato sauce and cheese";

 }

 public double getCost() {

     return 10.00;

 }

}




//Decorator

abstract class ToppingDecorator implements Pizza {

 protected Pizza decoratedPizza;

 public ToppingDecorator(Pizza pizza) {

     decoratedPizza = pizza;

 }

 public String getDescription() {

     return decoratedPizza.getDescription();

 }

 public double getCost() {

     return decoratedPizza.getCost();

 }

}




//Concrete decorator

class Pepperoni extends ToppingDecorator {

 public Pepperoni(Pizza pizza) {

     super(pizza);

 }

 public String getDescription() {

     return decoratedPizza.getDescription() + ", pepperoni";

 }

 public double getCost() {

     return decoratedPizza.getCost() + 2.50;

 }

}




//Client code

public class DecoratorPizzaShop {

 public static void main(String[] args) {

     Pizza basicPizza = new BasicPizza();

     System.out.println("Basic pizza: " + basicPizza.getDescription() + " - Cost: $" + basicPizza.getCost());


     Pizza pepperoniPizza = new Pepperoni(basicPizza);

     System.out.println("Pepperoni pizza: " + pepperoniPizza.getDescription() + " - Cost: $" + pepperoniPizza.getCost());

 }

}


//Output:


Basic pizza: Pizza with tomato sauce and cheese - Cost: $10.0

Pepperoni pizza: Pizza with tomato sauce and cheese, pepperoni - Cost: $12.5


In this example, we have a Pizza interface that defines the methods for getting the description and 
cost of a pizza. 


The BasicPizza class is a concrete implementation of the Pizza interface.


The ToppingDecorator abstract class is a decorator that implements the Pizza interface and contains 
an instance of the Pizza interface. 


The Pepperoni class is a concrete decorator that extends the ToppingDecorator class 
and adds a pepperoni topping to the pizza.


In the PizzaShop class, we create a basic pizza and a pepperoni pizza using the decorator pattern. 
We first create a BasicPizza object, and then we create a Pepperoni object that takes the BasicPizza object as a parameter in its constructor. 


This creates a pizza with tomato sauce, cheese, and pepperoni. We then print out the descriptions 
and costs of both pizzas.




Sunday, July 9, 2023

Java (JVM) Memory Model - Switches

 

VM SwitchVM Switch Description
-XmsFor setting the initial heap size when JVM starts
-XmxFor setting the maximum heap size.
-XmnFor setting the size of the Young Generation, rest of the space goes for Old Generation.
-XX:PermGenFor setting the initial size of the Permanent Generation memory
-XX:MaxPermGenFor setting the maximum size of Perm Gen
-XX:SurvivorRatioFor providing ratio of Eden space and Survivor Space, for example if Young Generation size is 10m and VM switch is -XX:SurvivorRatio=2 then 5m will be reserved for Eden Space and 2.5m each for both the Survivor spaces. The default value is 8.
-XX:NewRatioFor providing ratio of old/new generation sizes. The default value is 2.

Wednesday, July 14, 2021

Consumer Example in Java 8

 

Consumer Example in Java 8 


forEach in Iterable.java interface which uses Consumer: 

default void forEach(Consumer<? super T> action) 

{

    Objects.requireNonNull(action);

    for (T t : this) {

        action.accept(t);

    }

}



@FunctionalInterface
public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

This is a functional interface whose functional method is accept(Object).

Method:

void accept(T t)
  • andThen

    default Consumer<T> andThen(Consumer<? super T> after)
    Returns a composed Consumer that performs, in sequence, this operation followed by the after operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after operation will not be performed.
    Parameters:
    after - the operation to perform after this operation
    Returns:
    a composed Consumer that performs in sequence this operation followed by the after operation
    Throws:
    NullPointerException - if after is null

Example:

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;


public class ConsumerEx {


public static void main(String[] args) {


List<String> list = Arrays.asList("india", "uk", "fiji");


Consumer<String> consumer = (t) -> {

System.out.println(t.toUpperCase());

};


list.forEach(consumer);


}


}


Output:

INDIA

UK

FIJI

Tuesday, January 12, 2021

Docker: Important Docker Commands Help

Docker: Important Docker Commands Help


Dockerfile:


FROM adoptopenjdk/openjdk11:latest

EXPOSE 8080

ADD "target/docker-demo-0.0.1-SNAPSHOT.jar" "docker-demo.jar"

ENTRYPOINT ["java","-jar","docker-demo.jar"]

Docker Commands:


 Build Docker Image:

docker build -t docker-demo .

 Tag Docker Image: 

docker tag docker-demo dineshnithdocker/docker-demo

Push Docker Image to Docker Hub 

docker push dineshnithdocker/docker-demo

Check docker Images present in local: 

docker images

Remove Local Docker Images:  

docker rmi docker-demo dineshnithdocker/docker-demo

 Pull Docker Images from Docker Hub and run:

docker run -p 8080:8080 dineshnithdocker/docker-demo


Wednesday, November 25, 2020

Leet Code Problems Solutions

Intersection of Two Arrays I

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Code : Solution 1 - 




public class ArrayIntersection {

	public static int[]  intersect(int[] nums1, int[] nums2) {

		if (nums1.length > nums2.length) {
			return intersect(nums2, nums1);
		}

		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		List<Integer> list = new ArrayList<Integer>();

		for (int i : nums1) {
			map.put(i, map.getOrDefault(i, 0) + 1);
		}

		for (int i : nums2) {
			int count = map.getOrDefault(i, 0);
			if (count > 0) {
				list.add(i);
				map.put(i, count - 1);
			}
		}

		int[] result = new int[list.size()];

		for (int i = 0; i < result.length; i++) {
			result[i] = list.get(i);
		}

		return result;
	}

	public static void main(String... aa) {
		int[] nums1= {1,2,2,1};
		int[] nums2= {2,2};
	
		System.out.println(intersect(nums1,nums2));
	}
}

Plus One

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

 

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3:

Input: digits = [0]
Output: [1]

 

Constraints:

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

Java

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts