Java code examples

import java.util.HashMap;

import java.util.Map;

public class PeopleAddressList { private Map<String, String> addressList; public PeopleAddressList() { addressList = new HashMap<>(); }

public void addPerson(String name, String address) { addressList.put(name, address); }

public String getAddress(String name) { return addressList.get(name); }

public void removePerson(String name) { addressList.remove(name); }

public int size() { return addressList.size(); }

public void clear() { addressList.clear(); }

public void printAddressList() { for (String name : addressList.keySet()) { System.out.println(name + ” : ” + addressList.get(name)); } }

public static void main(String[] args) { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”); list.printAddressList(); }}

//Main class as below

import java.util.HashMap;

import java.util.Map;

public class AddressSummary {

private PeopleAddressList addressList; public void setAddressList(PeopleAddressList addressList) { this.addressList = addressList; }

public String toString() { StringBuilder sb = new StringBuilder(); for (String name : addressList.keySet()) { sb.append(name + ” : ” + addressList.get(name) + “\n”); } return sb.toString(); }

public static void main(String[] args) { AddressGeneration generation = new AddressGeneration(); PeopleAddressList list = generation.getPeopleAddressList(); AddressSummary summary = new AddressSummary(); summary.setAddressList(list); System.out.println(summary); }}

public class AddressGeneration {

public PeopleAddressList getPeopleAddressList() { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”);

return list; }}

//Facade Design pattern

import java.util.HashMap;
import java.util.Map;

public class AddressSummaryFacade {

private AddressGeneration generation;
private AddressSummary summary;

public AddressSummaryFacade() {
    generation = new AddressGeneration();
    summary = new AddressSummary();
}

public String getAddressSummary() {
    summary.setAddressList(generation.getPeopleAddressList());
    return summary.toString();
}

}

public class Main {

public static void main(String[] args) {
    AddressSummaryFacade facade = new AddressSummaryFacade();
    System.out.println(facade.getAddressSummary());
}

}

tablesaw vs apachepoi

import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import tech.tablesaw.api.Table;import org.openjdk.jmh.annotations.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;@BenchmarkMode(Mode.Throughput)@Warmup(iterations = 3, time = 1)@Measurement(iterations = 5, time = 1)@State(Scope.Benchmark)public class ExcelReadBenchmark { private File excelFile; private Table tablesawTable; @Setup public void setup() { // Initialize your Excel file and Tablesaw table here excelFile = new File(“your-excel-file.xlsx”); // Replace with your Excel file path tablesawTable = Table.read().csv(“your-csv-file.csv”); // Replace with your CSV file path } @Benchmark public void readAndPrintWithTablesaw() { // Perform reading and printing using Tablesaw String column1 = tablesawTable.column(“Column1”).toString(); // Print or process column1 here } @Benchmark public void readAndPrintWithApachePOI() throws IOException { // Perform reading and printing using Apache POI FileInputStream inputStream = new FileInputStream(excelFile); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet for (Row row : sheet) { Cell cell = row.getCell(0); // Access the first cell (column 1) if (cell != null) { String cellValue = cell.toString(); // Print or process cellValue here } } workbook.close(); inputStream.close(); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); }}

read from 100 to 200

import tech.tablesaw.api.*;
import tech.tablesaw.io.csv.CsvReadOptions;

public class ReadCSVWithTablesaw {

public static void main(String[] args) {
    // Define the path to your CSV file
    String csvFilePath = "path/to/your/file.csv"; // Replace with your CSV file path

    // Define the range of rows you want to read (100 to 200)
    int startRow = 100;
    int endRow = 200;

    try {
        // Define read options
        CsvReadOptions options = CsvReadOptions.builder(csvFilePath)
                .header(true) // Assuming the CSV file has a header row
                .build();

        // Read the CSV file into a Table
        Table table = Table.read().csv(options);

        // Extract the desired rows (100 to 200) from column 1
        Column<String> column1 = table.column(1).subList(startRow, endRow + 1).asStringColumn();

        // Print or process the values in column1
        for (String value : column1) {
            System.out.println(value);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

// SpringBoot

//YourService

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class YourService {

public Mono<Address> fetchAddress(String branch, String filename) {
    return WebClient.create()
            .get()
            .uri("https://bitbucket.org/{filename}?branch={branch}")
            .retrieve()
            .bodyToMono(String.class)
            .map(json -> parseAddressFromJson(json)); // Custom parsing logic
}

private Address parseAddressFromJson(String json) {
    // Implement your JSON parsing logic to convert JSON string to Address object
    // For example, using Jackson ObjectMapper:
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.readValue(json, Address.class);
    } catch (JsonProcessingException e) {
        // Handle parsing exception
        throw new RuntimeException("Error parsing JSON", e);
    }
}

}

//Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping(“/api/addresses”)
public class AddressController {

private final YourService yourService;

@Autowired
public AddressController(YourService yourService) {
    this.yourService = yourService;
}

@GetMapping("/{branch}/{filename}")
public Mono<ResponseEntity<Address>> getAddress(
        @PathVariable String branch,
        @PathVariable String filename) {
    return yourService.fetchAddress(branch, filename)
            .map(ResponseEntity::ok)
            .defaultIfEmpty(ResponseEntity.notFound().build());
}

}

// Detailed implementation

//AddressService

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;

@Service
public class AddressService {

private final WebClient webClient;
private final String repositoryUrl;
private final String branch;

public AddressService(WebClient.Builder webClientBuilder,
                      @Value("${bitbucket.repositoryUrl}") String repositoryUrl,
                      @Value("${bitbucket.branch}") String branch) {
    this.webClient = webClientBuilder.build();
    this.repositoryUrl = repositoryUrl;
    this.branch = branch;
}

public Mono<Address> getAddressFromBitbucket(String filename) {
    // Construct the URL to the JSON file in the Bitbucket repository
    String url = String.format("%s/%s/%s/%s", repositoryUrl, branch, filename);

    // Make a GET request using WebClient
    return webClient.get()
            .uri(url)
            .retrieve()
            .bodyToMono(String.class)
            .flatMap(this::parseAddressFromJson);
}

private Mono<Address> parseAddressFromJson(String jsonResponse) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode jsonNode = mapper.readTree(jsonResponse);

        // Extract address data from the JSON node
        Address address = new Address();
        address.setStreet(jsonNode.get("street").asText());
        address.setCity(jsonNode.get("city").asText());
        address.setState(jsonNode.get("state").asText());
        address.setCountry(jsonNode.get("country").asText());
        address.setPostalCode(jsonNode.get("postalCode").asText());

        return Mono.just(address);
    } catch (IOException e) {
        return Mono.error(e);
    }
}

}

// app prop / yaml

bitbucket.repositoryUrl=https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/src
bitbucket.branch=master

// your service

@Service
public class YourService {

private final AddressService addressService;

public YourService(AddressService addressService) {
    this.addressService = addressService;
}

public Mono<Address> getAddress(String filename) {
    return addressService.getAddressFromBitbucket(filename);
}

}

// controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping(“/api”)
public class AddressController {

private final YourService yourService;

@Autowired
public AddressController(YourService yourService) {
    this.yourService = yourService;
}

@GetMapping("/address/{filename}")
public Mono<ResponseEntity<Address>> getAddress(@PathVariable String filename) {
    return yourService.getAddress(filename)
            .map(ResponseEntity::ok)
            .defaultIfEmpty(ResponseEntity.notFound().build());
}

}

Addl java examples

@Service
public class BitbucketService {
private final WebClient webClient;

public BitbucketService() {
    webClient = WebClient.builder()
            .baseUrl("https://api.bitbucket.org/2.0/")
            .build();
}

public String getJsonFile() {
    String repoOwner = "your-repo-owner";
    String repoName = "your-repo-name";
    String filePath = "path/to/your/json/file.json";

    String url = String.format("repos/%s/%s/contents/%s", repoOwner, repoName, filePath);
    return webClient.get().uri(url).retrieve().bodyToMono(String.class).block();
}

}

@RestController
public class JsonController {
private final BitbucketService bitbucketService;

public JsonController(BitbucketService bitbucketService) {
    this.bitbucketService = bitbucketService;
}

@GetMapping("/json")
public String getJson() {
    return bitbucketService.getJsonFile();
}

}

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.fasterxml.jackson.databind.ObjectMapper; // For JSON parsing

public class JsonReader {
public static void main(String[] args) {
String jsonUrl = “https://your_git_repo_url/abc.json”; // Replace with your file’s URL

    try {
        URL url = new URL(jsonUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String jsonString = reader.lines().collect(Collectors.joining());
        reader.close();

        // Deserialize JSON (assuming you have a suitable class 'MyData')
        ObjectMapper mapper = new ObjectMapper();
        MyData dataObject = mapper.readValue(jsonString, MyData.class);

        System.out.println(dataObject); // Access your data 
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

some python examples

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
“The first document is about space exploration.”,
“The second document is about machine learning.”,
“The third is about gardening.”
]

vectorizer = TfidfVectorizer(stop_words=’english’)
tfidf_matrix = vectorizer.fit_transform(corpus)

def answer_question(query):
query_vector = vectorizer.transform([query])
similarities = cosine_similarity(query_vector, tfidf_matrix)[0]
most_similar_doc_idx = similarities.argmax()
print(“Most relevant document:”, corpus[most_similar_doc_idx])

question = “What is machine learning?”
answer_question(question)

AI Agentic LLM tasks

Anon and deanon examples

AnonymizerRefined:

from functools import wraps
import re
from faker import Faker
import spacy
from DeanonymizerRefined import DeanonymizerRefined
from datetime import datetime

class AnonymizerRefined:
def init(self, custom_patterns=None):
self.fake = Faker()

    # Define default regex patterns
    phone_pattern = r"\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}"  # noqa
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    credit_card_pattern = r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}'
    address_pattern = r'\d{1,5}\s\w+(\s\w+)*,\s\w+,\s\w+(\s\w+)*'

    # Initialize pattern functions
    self.pattern_functions = [
        self.create_anonymize_function(phone_pattern,
                                       self.fake.phone_number),
        self.create_anonymize_function(email_pattern,
                                       self.fake.email),
        self.create_anonymize_function(credit_card_pattern,
                                       self.fake.credit_card_number),
        self.create_anonymize_function(address_pattern,
                                       self.fake.address),
    ]

    # Add any custom patterns
    if custom_patterns:
        for pattern, func in custom_patterns.items():
            self.pattern_functions.append(
                self.create_anonymize_function(pattern, func))

def generate_unique_fake(self, original, generator_func):
    fake_value = generator_func()
    while fake_value == original:
        fake_value = generator_func()
    return fake_value

def create_anonymize_function(self, pattern, fake_func):
    try:
        re.compile(pattern)
    except re.error:
        raise ValueError(f"Invalid pattern: {pattern}. Must be a regular expression.")  # noqa

    def anonymize_func(sentence, anon_sentence, mappings):
        data_map = {}
        for data in re.findall(pattern, sentence):
            # If data is a tuple, join it into a string
            if isinstance(data, tuple):
                data = ' '.join(data)
            fake_data = self.generate_unique_fake(data, fake_func)
            data_map[data] = fake_data
            anon_sentence = anon_sentence.replace(data, fake_data)
        mappings[pattern] = data_map
        return anon_sentence

    return anonymize_func

def anonymize_data(self, sentence):
    anon_sentence = sentence
    mappings = {}
    for pattern_function in self.pattern_functions:
        anon_sentence = pattern_function(sentence, anon_sentence, mappings)
    return anon_sentence, mappings

def anonymize(self, *args_to_anonymize):
    def inner_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for arg_name in args_to_anonymize:
                if arg_name in kwargs:
                    anonymized_data, _ = self.anonymize_data(
                        kwargs[arg_name])
                    kwargs[arg_name] = anonymized_data
            return func(*args, **kwargs)

        return wrapper

    return inner_decorator

Create an instance of the AnonymizerRefined class

anonymizer = AnonymizerRefined()

Create an instance of the DeanonymizerRefined class

deanonymizer = DeanonymizerRefined()

Open the text file

with open(‘mydata.txt’, ‘r’) as file:
# Read the content of the file
content = file.read()
# Anonymize the content
anonymized_content, _ = anonymizer.anonymize_data(content)

Anonymized content and mappings

anonymized_content, mappings = anonymizer.anonymize_data(content)
print(‘ ###################### anonymized_content ###################### ‘)
print(anonymized_content)
print(‘######### mapping ##########’)
print(mappings)

Deanonymize the content

deanonymized_content = deanonymizer.deanonymize(anonymized_content, mappings)

print(‘ ###################### deanonymized_content ###################### ‘)

Print the deanonymized content

print(deanonymized_content)

Get the current date and time

now = datetime.now()

Format the date and time

timestamp = now.strftime(“%Y-%m-%d %H:%M:%S”)

Open the output file in append mode

with open(‘output.txt’, ‘a’) as file:
# Write the timestamp, anonymized content, mappings, and deanonymized content to the file
file.write(“\n”)
file.write(f” ############### ############### ############### ############### Timestamp: {timestamp}\n”)
file.write(” ############### ############### ############### ############### Anonymized content:\n”)
file.write(anonymized_content + “\n”)
file.write(“\n”)
file.write(” ############### ############### ############### ############### Mappings:\n”)
file.write(str(mappings) + “\n”)
file.write(“\n”)
file.write(” ############### ############### ############### ############### Deanonymized content:\n”)
file.write(deanonymized_content + “\n”)
file.write(“\n”)
file.write(“\n”)

DeanonymizerRefined:

class DeanonymizerRefined:
def deanonymize(self, text, mappings):
# Loop through each pattern mapping and replace the anonymized values
# back to the original ones
for _, pattern_map in mappings.items():
for original_value, fake_value in pattern_map.items():
text = text.replace(fake_value, original_value)
return text

chainlet chatbot

# python -m chainlet run ui.py
# python -m chainlet run ui.py --debug
# python -m chainlet run ui.py --debug --verbose
# python -m chainlet run ui.py --debug --verbose --port 8000
# python -m chainlet run ui.py --debug --verbose --port 8000 --host
import os
import sys
from llama_index.core.tools import FunctionTool
from llama_index.core.agent import ReActAgent
from llama_index.llms.ollama import Ollama
#from llama_index.llms.core import Settings
# from llama_index.indices.service_context import ServiceContext
import nest_asyncio
import chainlet as cl
# from llama_index.llms import Ollama


nest_asyncio.apply()
llm = Ollama(model="llama3", request_timeout=120.0)
# Settings.llm = llm
# service_context = ServiceContext.from_defaults(
# llm=Ollama(temperature=0.7, max_tokens=1024)
# )

# llama_index.set_global_default(
# llm=Ollama(model="llama3"),
# chunk_size=512,
# )

# 2. Initialize LLM with the ServiceContext
# llm = Ollama(service_context=service_context)

# 1. create custom tools
def multiply(a: int, b: int) -> int:
"""Multiply two numbers together."""
return a * b


def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b


def subtract(a: int, b: int) -> int:
"""Subtract two numbers together."""
return a - b


def divide(a: int, b: int) -> int:
"""Divide two numbers together."""
return a / b


multiply_tool = FunctionTool.from_defaults(fn=multiply)
add_tool = FunctionTool.from_defaults(fn=add)
subtract_tool = FunctionTool.from_defaults(fn=subtract)
divide_tool = FunctionTool.from_defaults(fn=divide)

agent = ReActAgent.from_tools([multiply_tool, add_tool, subtract_tool, divide_tool], llm = llm, verbose = True,)

# 2. create a custom agent
@cl.on_chat_start
async def on_chat_start():
await cl.Message(content="Hello! I am a simple calculator bot. Please enter the first number.")
cl.user_session.set("agent", agent)


@cl.on_message
async def on_message(message: cl.Message):
agent = cl.user_session.get("agent")
response = agent.chat(message.content)
await cl.Message(content=str(response)).send()

Selenide

Selenide is a wrapper jar to Selenium automation projects.

How to get Selenide jars – reference selenide.org

How does I disable webdriver manager api calls to github to avoid driver.exe pulls?

system property -Dselenide.driverManagerEnabled=false can avoid pulling driver exes and you could define driver binary path in selenium project configurations itself

Angular 12.1 new features

Angular 12.1 new features:

Improved CLI performanceng build defaults to prod, that avoids accident production deployment from development builds

New @use syntax points to new Saas API in Angular 12.1. Automatically happens when you do ng update on Angular 12.1

Angular components supports in line Saas in styles field in @component decorator

Strict mode can be enabled via CLI to catch errors early in development cycle

Webpack 5 module is Production ready

Unused methods will be removed to improve performance by DomAdaptor

Custom router outlet implementations are allowed

min max validators for forms are added

TypeScript 4.2 support has been added and dropped support for TypeScript 4.0 and 4.1

Deprecating support for IE11

Above some of the features, please go through official Angular docs for detailed info.

How to handle Webtable in Selenium

Simple way to handle Webtable in Selenium Web Automation

Steps/coding/dom inspecting logic:

  1. Right Click and Inspect html for table
  2. Identify the patern for colum 1 of table
  3. Carefully observe the xpath of column 1 row 1 to row 3
  4. Notice that xpath has “tr[1]/td[1]”, “tr[2]/td[1]” , “tr[3]/td[1]” etc for following rows in colmn 1
  5. Use For loop and replace tr[1],tr[2],tr[3] with for loop variable “i”

What is a proxy server?

What is a proxy server?

Proxy server is a server that acts like a middle-man between your computer and internet.

Why Proxy servers are used?

Main prupose is security by hiding your machine ip from internet.

Also tracking employee activity on various aite they access

What is VPN and why VPN is used?

Virtual private Network is used for data protection and building secure connection between your computer and internet.

VPN creates a virtual tunnel between your computer and internet or external server where you request info from.

Selenium tutorials

Selenium # Selenium Implicit and Explicit wait

//Implicit Wait
driver.manage()
.timeouts().implicitlyWait(10,
TimeUnit.SECONDS)
// Explicit wait
WebDriverWait wait = new
WebDriverWait(driver,
20);
wait.until(Expected
Conditions.textTo
BePresent
InElementLocated

Selenium # Selenium Keyboard and Mouse events
keyDown(); keyUp(); sendKeys();doubleClick();

Code Example:
Actions builder = new Actions(driver);
Action actions = builder
.moveToElement(“logintextbox”)
.click()
.keyDown(“logintextbox”, Keys.SHIFT)
.sendKeys(“logintextbox”, “hello”)
.keyUp(“logintextbox”, Keys.SHIFT)
.doubleClick(“logintextbox”)
.contextClick()
.build();
actions.perform() ;

What is Cucumber BDD for Selnium tests

Cucumber BDD (Behaviourdriven development):Cucumber is a testing toolused for Software testingwith behaviour drivendevelopment approach.Cucucmber BDD comes with feature file, whereacceptance, functional,regression tests are written in plain english called Gherkin language…Sample feature file inGherkin language is like below:

Feature: my app login test

Scenario: positve test on login

Given user enters correct credentials

Then user should be able to login

Scenario: login negative test

Given user enters wrong password

Then login is not allowed

in the above feature file,each line below to

Scenario, i. e Given, Then steps are mapped with java methods to perform selenium Automation tests

What is TestRunner in Cucumber:

TestRunner is a programused in Cucumber toaccess Feature fileTestRunner drives theselenium automationfeatures executionFeature file is somethingthat has user requirementscenarios written in Englishwhich gives more readabilityand understandability ofthe requirement which iscalled Gherkin language#shorts

Unit testing mocks, stubs

Mocks replaces external Interface. Mocks are not to check thereturn value but to verify function level call happened,called correctly etc.Stubs are replacement ofreturn value and is to test behavior of code.Stubs generates the pre defined output fakes to replace actual implemention like to replaceweb server with local httpserver or replace db serverwith fake in memory db to generate db response

TestNG Parameterization:

Approach 1: feed input parameters via TestNGand receive using@Parameters annotation at the target method

Approach 2: use Dataprovider when complex parameters like data from database, xls,property file, arraylist etc

What is Single slash ‘/’in Xpath in selenium:

Single slash ‘/’ is usedwhen absolute Xpathis considered for Elementidentification for SeleniumWebDriver

What is Double slash ‘//’in Xpath in selenium:

Double slash ‘//’ is usedwhen relative Xpathis considered for Element identification for SeleniumWebDriverRelative Xpath ‘//’is better Element identification strategy


What is Polymorphism:
Polymorphism is one
of the OOPs concepts
where many forms or
characteristics shown
by single  java  method

Different types of
Polymorphism are,

1. compile time/static
Polymorphism
2. Runtime/Dynamic
Polymorphism

1. Compile time/static
Polymorphism is
achieved by Method
overloading
2. Runtime/Dynamic
Polymorphism is
achieved by Method
overriding

Method overloading
is feature where
many methods having
same name but different
argument types
Method overriding is
a feature where child
class method override the
parent class method


#Interface:

Interface is like
class having variables
and methods but methods
are abstract by default.

abstract methods mean
no body/implementation

Any class can
implement Interface and
achieve abstraction and
multiple inheritance

#encapsulation#java#selenium#OOPS is binding of data or variableswith code/methodsas a sigle unit from classthis helps hiding datafrom other classes whendata is declared as private.and keeping methods/codeas public, other class canget data.

#shorts#Abstractclass#cpncreatclassAbstract class:a class declaredusing abstract keywordand has abstract methodsAbstract methodsdoes not haveimplementationor bodyConcreat class:Concreat class extendsAbstract class and implements the methodsfrom Super Abstract classConcreta class does notuse Abstract keywordSelenium classes:Selenium classesextends Concreatclass and instantiateConcreat class touse the implementedmethods from Concreat class


#selenium
#captcha
Selenium: Handling Captcha using Sikuli

Purpose of Captcha
is to avoid Automation.

However some level
of Captcha automation
can be done using Sikuli

Sikuli can capture
image captcha having
numbers or letters
as contents and store
as string values
to continue Automation

Sikuli is a library
that works based
on image recognition

Sikuli can read text from
image and that can be
used for some level of
captcha Automation

#shorts
#dybamicobjects
#selenium

Selenium:
Handling
dynamic
elements

Dynamic Objects
are those it’s id or
other properties
are changing
during page load
or other
user actions

How to handle
dynamic objects:

1. use XPath axes
methods :
use child, parent, sibling
elements to write Xpath

2. use dynamic Xpath
having “contains,
or starts with
or  ends with  etc

#shorts
What is SelectorsHub?

It is a Browser extension
helps to auto suggest
XPath or CSS Selector

How to setup SelectorsHub

1. download and install from
www.selectorshub.com
for browser type
chrome, opera, edge, firefox

2. after adding extention to
browser, it will appear
as browser toolbar item

3. after restarting
browser  inspect any
WebElement,
SelectorHub will be
displayed on Elements
tab on right

4. start typing XPath or
CSS Selector, you
would notice SelectorsHub
auto suggesting
Xpath or CSS Selector

Ref : www.selectorshub.com

#shortsSwitch to Frame:driver.switchTo().frame(“frame name/frame index”);Switch backfrom Frame:driver.switchTo().defaultContent();note: commandsare single line

#shorts
#selenium
#locators
Different
Selenium Locators :

By.id()
By.name()
By.tagName()
By.className()
By.xpath
By.cssSelector()
By.linkText()
By.partialLinkText()

#shorts
#selenium
#Exceptions
Different
WebDriver Exceptions :

   1.WebDriver
Exception
2.Timeout
Exception
         3. NoAlertPresent
Exception
        4. Nosuchwindow
Exception
         5. NoSuchElement
Exception

#shorts
#selenium
#css
#xpath
#seleniumlocator

XPath:
1. XPath(XML Path)
is used to find element
in HTML DOM
2. XPath is the locator
type used in Selenium
3. High success rate
in finding elemet
4. Xpath is slower in IE

CSS(Cascading Style
Sheet )
1. CSS Selector, a
selenium locator type,
used to find
elements using style
language
2. Faster in all
Browsers but may not
work on certain browser
elements

#shorts
1. W3C standard protocol
is used by Selenium 4
WebDriver to
communicate
to Browser, which makes
communication
standardised
and no API encoding
/decoding required

2. Logging and tracing are
improved for better
monitoring
3. Better documentation on
selenium features
4. enabled two url
opening on two browser
tabs

5. Relative Locators
like. toRightOf(),
above(), near()
6.Opera and
PhantomJs support
are removed

7. Optimized
SeleniumGrid
by fixing open issues

#shorts
for chrome:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

for Firefox:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new FirefoxDriver(caps);
// Pass the capabilities
as an argument to driver object

DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

#shorts// to retrieve the current URL of the webpagegetCurrentUrl() // to retrieve the current page source of the webpagegetPageSource() //to retrieve the text of the specified web elementgetText() //to retrieve the value specified in the attributegetAttribute() //to retrieve the current title of the webpagegetTitle()getCurrentUrl() getPageSource() getText()getAttribute() getTitle()

Driver will switch to specific
frame using
Name or ID or index
:::
driver.switchTo.frame
(“frameName value”)

or
driver.switchTo
.frame(“ID value”)

or
driver.switchTo.frame(0)

Fluent Wait in Selenium is used for defining the maximum time for the webdriver to wait for a condition, and also the frequency with which we want to check the condition before throwing Exception

Handle multiple Browser windows and tabs
getWindowHandle()

//to retrieve the handle of the current page

getWindowHandles() vs getWindowHandle()

driver.close(); // closes the current browser window
driver.quit(); //This method Closes all browser windows opened by the WebDriver

Python short videos for interview preparations

Python #2 handling file not found error

Python # 15 Lambda function in Python 3 onwards

Python #7 Exceptions | AttributeError — happens when an attribute reference or assignment fails

Paython #8 Exception |IOError — happens when I/O operation open() function fails like file not found

Python #9 Exception | ImportError happens when import statement cannot locate the module definition

Python # 10 Exception | IndexError  happens when a sequence subscript is out of range

Python #11 Exception KeyError :happens when a dictionary key isn’t found in the set it existing keys

Python # 12 Exception | NameError happens when a local or global name can’t be found

Python # 14 Nested If statements to check multiple conditions

Python # 16 How to find highest value in an array

Python #13 What is if __name__ == “__main__”: in python

Python # 6 if elif else condtion code example for python | code logic

Python #5 How to define own function code example | python automation | programming

Python #4 argparse standard library for taking commandline arguments into python program

Python #1 for looping  | Python programming

Python #3 logging usage | import logging

Python # 19 Python 3.9 features | new features in Python 3.9

DevOps tool chain and important tools and frameworks

  1. Source code management:
    GitHub, BitBucket, GitLab
  2. Programming Languages:
    Java, Python,JavaScript,
    Typescript
  3. Build management tools:
    Gradle, Maven, Ant
  4. Configuration management:
    Ansible, Chef, Puppet,
    Salt Stack
  5. Container:
    Docker, LXC, RKT
  6. Container orchastrators:
    Kubernetes, Docker swarm,
    Openshift, NoMad
  7. Infrastructure Provisioning:
    Terraform, Azure template,
    AWS cloud formation,
    Google Deployment Manager
  8. Monitoring :
    DataDog, Grafana, Zabbix,
    Prometheus, Checkmk,
    New Relic
  9. Logging:
    Splunk, ELK, Graylog
  10. Clouds:
    Azure, AWS, GCP, OpenStack ,
    IBM Bluemix, Alicloud
  11. CI/CD:
    Jenkins, Travis CI, Circle CI
    TeamCity, AWS CodePipeline,
    Google Cloudbuild, Gitlab CI
    Bitbucket pipeline, Github action
  12. Web Server:
    Apache, Nginx, IIS,
    Jetty, Tomcat
  13. Caching Server:
    MemCache, Redis
  14. NoSQL Database:
    MongoDB, Cassandra,
    Google datastore,
    AWS Dynamo db
  15. SQL Database:
    Oracle, MySQL, MsSQL
    PstgreSQL

Kubernetes concepts, cluster, nodes, docker container, image, Dockerfile

Kubernetes concepts to remember:

1. Kubernetes Cluster: combination of large number of node machines

2. node machines:where Kubernetes software is installed and docker containers are hosted

3. docker container:each node machines contain large number of docker containers

4. docker image:Docker instructions are build and stored as image

5.Dockerfile:Docker instructions are written in markup language and stored in Dockerfile

Docker more info:

  1. Docker image can be run in terminal interactive mode while container started.
  2. While running in the terminal interactive mode, any program runtime, or filesystem can be added to the live container.
  3. A commit on container can create another fresh image.
    4.Fresh image from container can be tagged for easy use.
  4. Now the fresh image will have ubundu and the additional file system, runtime(like Java runtime) associated.

Git basic concepts to remeber

Git basic concepts
to remeber:

  1. working directory:
    this is local folder where
    coding is done using IDE
  2. staging area:
    git add command move
    code from working directory (1)
    to staging area
  3. local repository:
    git commit command will move
    code to local repo with a commit id
  4. remote repository :
    During git push code will get moved to remote repo that will be git/bitbucket

git fetch will move remote
repo commits to local repo

git merge moves code from local
repo to working directory