Thursday, June 13, 2024

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws 



const express = require('express');

const redis = require('redis'); const app = express(); const port = 3000; // Replace with your actual hostname and port const client = redis.createClient({ host: 'your-elasticache-hostname', port: your-elasticache-port }); client.on('error', (err) => { console.log("Error " + err); }); app.get('/flushall', (req, res) => { client.flushdb((err, succeeded) => { if (err) { res.status(500).send({ error: 'Failed to flush Redis cache' }); } else { res.send({ message: 'Redis cache successfully flushed' }); } }); }); app.listen(port, () => { console.log(`App running on port ${port}`); });

===============================
Method 2: with lamda 

const Redis = require('ioredis'); exports.handler = async (event, context) => { const redis = new Redis({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); try { // Ping Redis to check connection const ping = await redis.ping(); console.log('Ping:', ping); // Clear all keys await redis.flushdb(); console.log('Cache cleared'); return { statusCode: 200, body: 'Cache cleared' }; } catch (error) { console.log('Error:', error); return { statusCode: 500, body: 'Error clearing cache' }; } finally { // Disconnect from Redis await redis.quit(); } };

=============================================
Methos 3: with redis dependency: const redis = require('redis'); exports.handler = async (event, context) => { return new Promise((resolve, reject) => { const client = redis.createClient({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); client.on('connect', function() { console.log('Connected to Redis'); client.flushdb(function (err, succeeded) { if (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); } else { console.log('Cache cleared'); resolve({ statusCode: 200, body: 'Cache cleared' }); } // Disconnect from Redis client.quit(); }); }); client.on('error', function (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); }); }); };

Sunday, May 19, 2024

Calculate your Age

Calculate Age Age Calculator

Age Calculator

Friday, February 16, 2024

what is meant by --max-request-journal-entries and --no-request-journal in wiremock configuration

max-request-journal-entries and no-request-journal in wiremock configuration


In WireMock, the request journal is a built-in feature that keeps a record of incoming requests and their corresponding responses. It can be helpful for debugging and analysis purposes.


--max-request-journal-entries is an option that allows you to set a limit on the number of requests that the request journal stores. When this limit is reached, older requests will be removed from the journal to make room for new ones. By setting this option, you can control the memory usage of the request journal.


For example, using --max-request-journal-entries=10000 will limit the request journal to store a maximum of 10,000 requests.


--no-request-journal is an option that disables the request journal entirely. When this option is used, WireMock will not store any requests or responses in the request journal. Disabling the request journal can help reduce memory consumption and improve performance, especially during load testing or in production environments where request logging is not necessary.


In summary:


--max-request-journal-entries: Sets a limit on the number of requests stored in the request journal.

--no-request-journal: Disables the request journal completely.

Thursday, January 18, 2024

Sort an array of 0s, 1s and 2s | Dutch National Flag problem

Sort an array of 0s, 1s and 2s |

Dutch National Flag problem


👀👀👀👀👀


/*

* This program defines a sortArray() method that sorts

* an array of 0s, 1s, and 2s using

* the Dutch National Flag algorithm.

*/


public class Sort012 {


public static void swap(int[] arr,int i,int j) {

int temp;

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

public static void sortArray(int[] arr) {

int low =0;

int mid =0;

int high =arr.length-1;

while(mid<=high) {

switch (arr[mid]) {

case 0:

swap(arr,low,mid);

low++;

mid++;

break;

case 1:

mid++;

break;

case 2:

swap(arr,mid,high);

high--;

break;

default:

break;

}

}

}


public static void main(String... aa) {

int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};

sortArray(arr);

for(int i:arr) {

System.out.print(i+" ");

}

}

}


Output:

0 0 0 0 1 1 1 1 2 2 2 2



Wednesday, January 17, 2024

Merge two sorted linked lists


Merge two sorted linked lists


public class MergeLinkedLists {

static class ListNode {

int val;

ListNode next;

public ListNode() {}


public ListNode(int val) {

this.val = val;

}


public ListNode(int val, ListNode next) {

this.val = val;

this.next = next;

}

}

public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

ListNode mergedList = new ListNode();

ListNode current = mergedList;


while (list1 != null && list2 != null) {

if (list1.val <= list2.val) {

current.next = list1;

list1 = list1.next;

} else {

current.next = list2;

list2 = list2.next;

}

current = current.next;

}


if (list1 != null) {

current.next = list1;

} else {

current.next = list2;

}


return mergedList.next;

}


public static void main(String[] args) {

// Example usage:

ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));

ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));


ListNode mergedList = mergeTwoLists(list1, list2);

while (mergedList != null) {

System.out.print(mergedList.val + " ");

mergedList = mergedList.next;

}

}

}


Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space


Output:


1 1 2 3 4 4


Geeks link:

    Merge To Linked List


Monday, January 15, 2024

Python script to automate login and extract cookie

 pip install requests

*****************create file*****************

import requests

url_login = "https://example.com/login" # Replace with the actual login URL url_after_login = "https://example.com/next" # Replace with the actual URL after login # Replace with your actual username and password payload = { "username": "your_username", "password": "your_password" } # Create a session to persist cookies session = requests.Session() # Perform the login response_login = session.post(url_login, data=payload) # Check if login was successful (replace '200' with the appropriate success status code) if response_login.status_code == 200: print("Login successful") # Perform the action after login (e.g., skip OTP) response_after_login = session.get(url_after_login) # Get the value of the desired cookie (replace 'cookie_name' with the actual cookie name) cookie_value = session.cookies.get("cookie_name") if cookie_value: print(f"The value of the cookie is: {cookie_value}") else: print("The desired cookie was not found.") else: print("Login failed.")

**********************************************

save login_script.py
python login_script.py

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.




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