What is a Docker file, image, container !

What is Dockerfile, Docker image and Docker container?

When I started reading about Docker, I was confused about the relationship between Docker file vs docker image vs docker container !

  • Docker file is where I need to script my steps on what actions to be done before I make a docker image.
    a sample docker file as below: here below in the code,
  • I am pulling JDK environment in line 1.
  • Then copying a java class to app directory in line 2,
  • Then setting app as working directory in line 3 for my docker container after i convert image to container.
  • Then finally running my app in line 4.
    FROM java:8-jdk-alpine
    COPY HelloWorl.class /app/
    WORKDIR /app
    ENTRYPOINT [“java”,”HelloWorld”]
  • Docker image is created using the above docker file by building it. (command : docker build -t myhelloworldapp . )
    • Note: dockerfile generates read only layers during the image conversion. These read only layers are created based the dockerfile commandline instructions. Images are considered as executable packages and is predefined. Once it is made, it can not be changed unless new dockerfile is created.
  • then spin up the container by using command : docker run myhelloworldapp

What is Amazon S3

Amazon S3 enables companies to store massive amount of data in a secure way. S3 enables companies to store, retrieve data. 

Benefits:

  • High durability, availability, and scalability. S3 provides the most comprehensive compliance capabilities.
  • S3 allows  data storage up to 5 terabytes 
  • S3 provides a REST web services interface supporting any internet development tool kit.
  • S3 is available in any AWS region worldwide

 

 

 

 

Components of 3 tier architecture – Web server vs Application server vs Database server

  • Web server serves a web content (HTML and static content) over the HTTP protocol.
  • Application server is a container on which one can build and expose business logic and processes to client applications through various protocols like HTTP. Some cases it will have internal web server. Application server is heavy in terms of resource usage.
  • Database server refers to the back-end system of a database application using client/server architecture. The database server performs tasks such as data analysis, storage, data manipulation, archiving, and other non-user specific tasks

 

What is amazon aws

amazon-aws

Amazon Web Services (AWS) is a subsidiary of amazon.com. AWS currently provides more than 100 services and helps to setup high computing power, data storage, queuing, notification, machine learning, security, monitoring services available under AWS management console.

AWS Free Tier includes 750 hours of Linux and Windows t2.micro instances each month for one year as per Amazon website. Please check  //aws.amazon.com or //aws.amazon.com/ec2/ website for more accurate details and to confirm this.
 
The quickest way to learn AWS is by creating free tier aws account by clicking below link.
 

Different AWS cloud services?

VPC, EC2, S3, SNS, SQS,  ML, Developer tools, Analytics, IAM, Media services etc.
 

VPC

What is VPC?

VPC lets us to place our AWS resources in a virtual network the way we wanted. As you can see below VPC 3 tier architecture holds the resources and makes a secure communication between the internet and your VPC.
 
VPC 3 tier architecture using AWS cloud services as below:
 

Amazon VPC – 3 tier architecture

here in the above diagram, Availability zone 1 has Web server 1, App server 1 and DB server 1 orchestrated 

Similarly, Availability zone 1 has Web server 2, App server 2 and DB server 2 orchestrated. 

The load balancer is placed to handle the load between the servers

EC2

 

What is EC2?

EC2 stands for Amazon Elastic Compute Cloud is a cloud service provides secure, resizable compute capacity. In simple terms it allows us to setup a windows, Linux servers in 2-3 minutes.

How to setup a Windows server and Linux server?

Steps:
AWS Free account gives access to AWS console.
Create a free account and select Linux and Windows t2.micro instances under EC2 option under AWS Dashboard.
Follow the instructions and make sure select “Free Tier Eligible servers” and after learning the process, terminate servers as to avoid the usage of computing services and storage.
 
 
Benefits?
Quick – easy to create/terminate servers.
Inexpensive – Gives an option to select the matching server configurations to reduce cost.   
Secure – EC2 works along with VPC to provide high security with robust networking features.
Elastic Web scale computing – enable to increase/decrease server capacity in minutes by adding/removing 100 of servers simultaneously. 
Integration – easy integration to VPC, S3, RDS etc.
 
Please click on S3Amazon Simple Storage Service (Amazon S3) 
 
Please click on RDS Amazon Relational Database Service (Amazon RDS)
 
Please click on VPC– Amazon Virtual Private Cloud (Amazon VPC)
 
Please click on RPA Amazon Relational Database Service (Amazon RDS)

How to run selenium on linux server using Firefox binary

How to run selenium on linux server using Firefox binary

String Xport = System.getProperty(“lmportal.xvfb.id”, “:1”); // setup firefox binary to start Xvfb
final File ffPath = new File(System.getProperty(“lmportal.deploy.firefox.path”, “/usr/bin/firefox”));
FirefoxBinary ffBinary = new FirefoxBinary(ffPath);
ffBinary.setEnvironmentProperty(“DISPLAY”, Xport);

WebDriver driver = new FirefoxDriver(ffBinary, null);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(“URL”);

How to handle the error popup on site security certificate is not trusted with chrome selenium python automation

How to handle the error popup on site security certificate is not trusted with chrome selenium python automation

For Chrome, add –ignore-certificate-errors in following code
options = webdriver.ChromeOptions()
options.add_argument(‘–ignore-certificate-errors’)
driver = webdriver.Chrome(chrome_options=options)
driver.get(‘URL’)

For the Internet Explorer, set acceptSslCerts desired capability as true:
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities[‘acceptSslCerts’] = True
driver = webdriver.Ie(capabilities=capabilities)
driver.get(‘URL’)

For Firefox, set accept_untrusted_certs as true

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
driver.get(‘URL’)

What are the limits in Salesforce

What are the limits in Salesforce

  1. Master detail relationships – 2
  2. Look up relationships – 40
  3. No.of dashboard components – 20
  4. Total Workflow rules per object – 500
  5. Active workflow rules – 50
  6. Approval process – 500
  7. Sharing rules (Criteria and Ownership based) – 300
  8. Sharing rules (Criteria based only) -50
  9. Validation rules – 100
  10. Field tracking – 20 (Additional 20 with chatter)
  11. No. of custom objects – 2000
  12. No. of custom fields – 500

Nia’s readings

Nia’s readings from Library,

  1. Ms. Leakey Is Freaky! – by Dan Gutman
  2. Ms. Hannah Is Bananas! – by Dan Gutman
  3. Nancy Drew and the Clue Crew- Case of the Sneaky Snowman by Carolyn Keene
  4. Diary of a Wimpy Kid Rodrick Rules by Jeff Kinney
  5. Help your Kids with Computer Coding 
  6. The phantom bully by Jeffrey Brown.
  7. Goosebump series Be careful what you wish for Samantha Byrd
  8. Goosebump series Night of the Living dummy Lindy Powell
  9. Goosebump series Night of the Living dummy Kris Powell
  10. Goosebump series Say Cheese and die Greg Banks
  11. Goosebump series Say Cheese and die Shari Walkar
  12. Goosebump series Be careful what you wish for – Samantha Byrd
  13. Goosebump series Stay out of the basement
  14. Carolines secret message
  15. Coach Hyatt is a Riot ! by Dan Gutman
  16. The Riddle of the Robin
  17. out of this world
  18. Dan Gutman – oh Valendtine we’ve lost our minds
  19. Sarah Mlynowski – whatever after dream on
  20. Sarah Mlynowski – whatever after bad hair day
  21. Lacey Little Mermaid Fairy
  22. Nancy Drew and the Clue Crew
  23. Miss Lazar is Bizarre
  24. Gemma and the Ultimate Standoff
  25. Owl Diaries Eva and Baby Mo
  26. A J’s Rules for school
  27. My first monologue
  28. When the Ghost Dog Howls
  29. Cinderella
  30. Harry Potter series, 8/8 books 
  31. Wings of fire, 13/15 
  32. Percy Jackson series 5/5 

Salesforce Admin Syllabus

Salesforce Admin Syllabus

  • Types of Objects & Fields
    • Standard Objects (Sample video link below)
    • Custom Objects (Sample video link below)
    • Standard Fields
    • Custom Fields

https://www.youtube.com/watch?v=8G27oLuUTVA

  • Types of Relationships, Field Dependency
  • Visualforce
  • Custom, Console application
  • Field Accessibility
  • Grant Login Access
  • Calendar, Console Tab
  • Trusted IP Ranges
  • Session Settings
  • Different types of Email templates
    • Text
    • HTML (using Letterhead)
    • Custom (without using Letterhead)
  • Different types of tabs
    • Custom Object Tab
    • Web Tab
    • Visualforce Tab
  • Field History Tracking in Salesforce, Feed Tracking
  • View setup audit trail
  • Organization Wide Default
  • Roles, Role Hierarchy
  • Sharing Rules
  • Profiles
  • Permission Sets
  • Password Policies
  • Developer console
  • Validation Rules
  • Approval process
  • Reports and Dashboards
  • Scheduling reports
  • Report Types
  • Adding dashboards in Home page
  • Chatter, Chatter Desktop
  • Queues
  • Public Groups
  • Assignment Rules, Auto Response Rule
  • Views
  • Domain Registration
  • Workflow rules
    • Email Alert
    • Task
    • Field Update
    • Outbound Message
  • Search Layouts
  • Search Results
    • Lookup Dialogs, Phone Dialogs
    • Accounts Tab
    • Accounts List View
    • Search Filter Fields
  • Page Layout
  • Mini Console View
  • Mini Page Layout
  • Record Types
  • Apex Data loader tool
  • com Explorer tool, Sites
  • Data Management
    • Analytic Snapshots
    • Import Accounts/Contacts, Leads, Solutions, Custom Objects
    • Data Export
    • Storage Usage
    • Mass Transfer Records
    • Mass Delete Records
    • Mass Transfer Approval Requests
    • Mass Update Addresses
    • Data Loader
  • Tags in Salesforce
  • Live Agent
  • Public Solutions
  • Chatter Answers
  • Entitlement Management
  • How to access Salesforce from all IP Ranges – App Exchange application
  • Mass Edit, Delete – App Exchange application
  • Login Hours restriction for Profiles
  • Edit, Delete and Clone Buttons
  • App Exchange, Chat Settings(Chat Window)
  • Email to Case
  • Web-to-Lead
  • Web-to-Case
  • Schema Builder
  • Visualforce page
  • Actions in Salesforce
  • How to expire all the users password in Salesforce?
  • How Salesforce login works?
  • Account, Opportunity and Case teams
  • Manual Sharing
  • Renaming Tab Names and Labels
  • Io, Data.com
  • Merge tool
  • Chatter Approval Request
  • https://success.salesforce.com
  • Opportunity Split
  • Workbench, Work.com
  • Escalation Rules
  • Adding Multiple Users
  • Account Hierarchy
  • Multi-Tenant Architecture
  • Creating Custom Tab Style in Salesforce
  • Historical Trend Reporting
  • Splash Page creation

QA Automation Interview questions

QA Automation Interview questions

  1. Differentiate final , finally, finalize (Short Ans: final method can’t be overridden, final variable can’t be changed, finally goes with try/catch, finalize is garbage collector)
  2. how to handle exceptions in java (Ans: try catch, throws, etc)
  3. how to use parameters in cucumber/testNG (Ans: scenario outline,tidy gherkin plugin, vs testng.xml-suite,test,class,method;)
  4. compare TestNG and Cucumber BDD (Ans: testng.xml, POM,vs feature file,Junit testrunner,stepDefention, POM)
  5. how to validate flatfiles , db using Java (Ans: input filestream, driver class connection, server name, instance , authentication, sql statement)
  6. how to skip method/test in TestNG, Cucumber BDD (Ans: testng.xml, annotation, cucumber tags on testrunner)
  7. differentiate encapsulation , abstraction
  8. what are interface and explain the methods – webdriver interface, driver object reference, FF/IEdriver class (Since interface can not be instantiated)
  9. write programs – sort array, print number in reverse, print string reverse, etc
  10. how does SSL works , public key-private key, session encryption etc
  11. method overridden vs method overloading (super class methods are overridden by child class when both has same methods, overload – one class has multiple methods with same method name but different parameters)
  12. Selenium automation challenges (ajax – webdriver wait methods, frames switch, alert.accept, multiple windows handlers, pdf in webpage, alert vs modal confuse, dynamic id,name-use xpath contains, etc)
  13. handle dropdown – select class
  14. feature file extension
  15. bufferbuilder usage
  16. what is background, scenarios outline, before/afterhooks vs tags, 
  17. usage of autoit, robotclass, javascript executor, 
  18. Jenkins schedule batch, report generation, 
  19. grid setup, hub and node, run on dos prompt, or use JSON file to configure nodes and run JSON on commandline..then connect in Jenkins 
  20. how to manage Git versions between two teams
  21. What is data structure and use of it test automation

If else program in Java

If else program in Java

import java.util.Scanner;

class IfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;

passingMarks = 40;

Scanner input = new Scanner(System.in);

System.out.println(“Input marks scored by you”);

marksObtained = input.nextInt();

if (marksObtained >= passingMarks) {
System.out.println(“You passed the exam.”);
}
else {
System.out.println(“Unfortunately you failed to pass the exam.”);
}
}
}

Nested Java program loops

Nested Java program loops

import java.util.Scanner;

class NestedIfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;
char grade;

passingMarks = 40;

Scanner input = new Scanner(System.in);

System.out.println(“Input marks scored by you”);

marksObtained = input.nextInt();

if (marksObtained >= passingMarks) {

if (marksObtained > 90)
grade = ‘A’;
else if (marksObtained > 75)
grade = ‘B’;
else if (marksObtained > 60)
grade = ‘C’;
else
grade = ‘D’;

System.out.println(“You passed the exam and your grade is ” + grade);
}
else {
grade = ‘F’;
System.out.println(“You failed and your grade is ” + grade);
}
}
}

Summary of Web services and API testing using UFT

Summary of Web services and API testing using UFT

 

Web services

 
Demand of Web services is already high in the new internet era since applications are built in different technology / databases and connected through internet. So communication between is only possible through a commonly accepted media which are Web services
 
Web services are XML format based services which use media as HTTP to communicate and it is loosely coupled where there no hard binding with client.
 

WSDL

 
WSDL is a document in XML format which describes a web service and defines which transactions are available and data should be structured to send to those transactions.

WSDL (Web services description language) helps client to initiate the correct web service

Webserver client needs WSDL to initiate Web services and Web server providers generates WSDL.
 

UDDI

UDDI is the online directory which has all the WDSL available and all web services client gets that from UDDI.

Web services has two implementations.
1. SOAP

2. REST

SOAP

 
SOAP is the XML based implementation for web service and it has 3 main components which are
a. Envelope – represents root elements
b. Header – stores authentication, routing id for web service transaction.
c. Body – stores all data which are intended to transfer to webservice client.

SOAP uses HTTP as media for transferring data. Format used in XML.

REST

 
REST is more flexible implementation as it uses text format and media other than HTTP as well.
 

API testing using UFT

 
UFT is a software automation tool. Apart from automation test scenarios it supports API testing. Following AP testing are supported.
 

Web service

REST

 
In UFT user can create a new API project by clicking File > New > Test..
Select the  API Test type
Then navigate to tool box in the left
Click on Network once it’s exploded,
Drag HTTP Request to Test flow
Right click and select the properties
Fill the URL, select HTTP method as GET
Also you can configure the checkpoints.

Maven TestNG framework with reporting features and switching pages

Maven TestNG framework with reporting features and switching pages

 

1.  Setup a Maven project in Eclipse with POM file as below

Refer the Post-Man plugin highlighted below in yellow

Refer the reporting directory path highlighted below in yellow

 

POM file sample as below – you can copy paste this contents for any Maven TestNG project.

 

<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>

  <modelVersion>4.0.0</modelVersion>

  <groupId>MavenProject</groupId>

  <artifactId>MavenProject1</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <dependencies>

       <dependency>

              <groupId>junit</groupId>

              <artifactId>junit</artifactId>

              <version>3.8.1</version>

       </dependency>

       <dependency>

              <groupId>org.testng</groupId>

              <artifactId>testng</artifactId>

              <version>6.8</version>

       </dependency>

         <dependency>

                  <groupId>com.relevantcodes</groupId>

                  <artifactId>extentreports</artifactId>

                  <version>2.41.1</version>

         </dependency>

       <dependency>

              <groupId>org.seleniumhq.selenium</groupId>

              <artifactId>selenium-java</artifactId>

              <version>2.45.0</version>

       </dependency>

 

       <dependency>

              <groupId>net.sourceforge.jexcelapi</groupId>

              <artifactId>jxl</artifactId>

              <version>2.6.12</version>

       </dependency>

       <dependency>

              <groupId>org.apache.poi</groupId>

              <artifactId>poi</artifactId>

              <version>3.17</version>

       </dependency>

  </dependencies>

  <dependencyManagement>

       <dependencies>

              <dependency>

                     <groupId>org.jxl</groupId>

                     <artifactId>jxl</artifactId>

                     <version>2.6</version>

              </dependency>

       </dependencies>

  </dependencyManagement>

 

   <build>

        <plugins>

              <!– Suirefire plugin to run xml files –>

               <plugin>

                     <groupId>org.apache.maven.plugins</groupId>

                     <artifactId>mavensurefireplugin</artifactId>

                     <version>2.18.1</version>

                     <configuration>

                           <suiteXmlFiles>

                                  <!– TestNG suite XML files –>

                                  <suiteXmlFile>testng.xml</suiteXmlFile>

                           </suiteXmlFiles>

                     </configuration>

              </plugin>

       <!– Post-Man plugin –>

              <plugin>

                     <groupId>ch.fortysix</groupId>

                     <artifactId>maven-postman-plugin</artifactId>

                     <executions>

                           <execution>

                          

                           <id>send an email</id>

                           <phase>testEmail</phase>

                           <goals>

                           <goal>send-an-email</goal>

                           </goals>

                           <inherited>true</inherited>

                          

                           <configuration>

                                  <!– From Email address –>

                                  <from>[email protected]</from>

                                 

                                  <!–  Email subject –>

                                  <subject>Test Report</subject>

                                 

                                  <!– Fail the build if the mail doesnt reach –>

                                  <failonerror>true</failonerror>

                                 

                                  <!– host –>

                                  <mailhost>smtp.gmail.com</mailhost>

                                  <!– port of the host –>

                                  <mailport>465</mailport>

                                  <mailssl>true</mailssl>

                                  <mailAltConfig>true</mailAltConfig>

                                 

                                  <!– Email Authentication(USername and Password) –>

                                  <mailuser>[email protected]</mailuser>

                                  <mailpassword>pwd</mailpassword>

                                 

                                  <receivers>

                                         <!– To Email address –>

                                         <receiver>[email protected]</receiver>

                                  </receivers>

                                 

                                  <fileSets>

                                  <fileSet>

                                         <!– Report directory Path –>

                                         <directory>C://Projects//Eclipse//workspace//Mavenproject//Reports</directory>

                                         <includes>

                                                <!– Report file name –>

                                                <include>**/*.html</include>

                                         </includes>

                                         <!—as mentioned above Regular Expression **/*.html to send all the html files reports–>

                                         </fileSet>

                                  </fileSets>                      

                          

                           </configuration>

                           </execution>

                     </executions>

              </plugin>

      

       </plugins>          

  </build>

    

</project>

 

2.      Setup a Page factory package where all the object locators are stored. E.g. code like this below.

 

package ProjectPageFactory;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.util.Iterator;

import java.util.List;

import java.util.NoSuchElementException;

import static org.testng.AssertJUnit.assertEquals;

import java.io.FileInputStream;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.ie.InternetExplorerDriver;

import org.openqa.selenium.support.CacheLookup;

import org.openqa.selenium.support.FindBy;

import org.openqa.selenium.support.PageFactory;

import org.openqa.selenium.support.ui.Select;

import org.testng.annotations.BeforeSuite;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.annotations.Test;

 

 

public class yourFirstpageofApplication {  // this is were you can build the locators repository.

               

                WebDriver driver;

                               

                @FindBy(linkText=”LocatorHyperlinkTextName”)  // type the Locator Hyperlink Text Name

                @CacheLookup  // use CacheLookup for any non dynamic objects , this will improve exection performance.

                WebElement Hyperlink1;

               

                @FindBy(xpath=”html/body/form/divXXXXXXX/xxxx”)

                // @CacheLookup – do not use CacheLookup for any dynamic objects

                WebElement objectName1;

 

2.   Setup a test script code that communicates to Pageobject repository

 

public class applicationPageName extends initialiseDriver  // refer step 3 for initialiseDriver example.

{

      

       //WebDriver driver;

       yourFirstpageofApplication AppObj;

 

       @Test(priority = 1)

       public void Excel() throws Exception

       {

                    

              AppObj = new yourFirstpageofApplication(driver);

              AppObj.ordinqclick();  // this will navigate to PageObject repository code and do action on application.

 

          Note: Basically both classes (Test scripts and Pageobject repository script) will communicate.

 

3.   Reporting code

 

package TestscriptProject;

 

import java.io.File;

import java.io.FileInputStream;

import java.util.List;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.ie.InternetExplorerDriver;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.WebDriver;

import org.testng.annotations.AfterClass;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

 

import com.relevantcodes.extentreports.ExtentReports;

import com.relevantcodes.extentreports.ExtentTest;

import com.relevantcodes.extentreports.LogStatus;

 

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

 

 

import PageFactoryProject.ApplicatonPageScriptClass;  // make sure you import that to this class

 

public class orderInquiryPage extends driverInitialise

{

      

       //WebDriver driver;

       yourFirstpageofApplication AppObj;

                     ExtentReports report;

              ExtentTest logger;

 

       @Test(priority = 1)

       public void Excel() throws Exception

       {

                     report = new ExtentReports(“./Reports/OrderInquiryReport.html”);

                     logger = report.startTest(“csvFile”);

              logger.log(LogStatus.INFO, ” test case started”);

      

             

                     //Pass the test in to report

                     logger.log(LogStatus.PASS,”Test verified Pass for particular functionality”);

                          

                     //End of the test

                     report.endTest(logger);

                                        

                     //clear the data in report

              report.flush();

 

4.   Switching between child window/page and parent window/page

 

To switch to a child window or page

public void childWindowHandle()

{

       childHandle = driver.getWindowHandles().toArray()[y].toString();   // y = 1

       driver.switchTo().window(childHandle);

}

 

To switch to a parent window or page

 

public void parentWindowHandle()

{     

       parentHandle = driver.getWindowHandles().toArray()[x].toString(); // x = 0

       driver.switchTo().window(parentHandle);

}

Cucumber Scenario data table and Scenario Outline data table

4 Dimensional Arrays in Java

Summary on Cloud, Machine learning, Artificial intelligence and other emerging technologies

Summary on Cloud, Machine learning, Artificial intelligence and other emerging technologies

Salesforce

Salesforce.com is an American cloud computing company.
Salesforce offers Software as a Service (SaaS) platform which helps in Customer Relationship Management.
It has a multi-tenant architecture and subscriptions.

 The following are the application clouds in Salesforce CRM.

  1. Sales Cloud
    2. Service Cloud
    3. Marketing Cloud
    4. Data cloud
    5. App Cloud
    6. Analytics Cloud
    7. Community Cloud

Salesforce also offers Platform as a Service (PaaS) using Force.com sites.

People involved in Salesforce Implementation
1. End User ( Customer)
2. Administrator
3. Developer
4. Consultant

The following are the list of Salesforce Certifications.

  1. Certified Administrator
    2. Certified Advanced Administrator
    3. Certified Sales Cloud Consultant
    4. Certified Service Cloud Consultant
    5. Certified Force.com Platform App Builder
    6. Certified Force.com Platform Developer I
    7. Certified Force.com Platform Developer II
    8. Certified Technical Architect

 

What is Apex?

  • Apex is a programming language for salesforce (only).
  • Object Oriented Program, in which the data types have to defined.
  • Allows developers for flow execution in force.com platforms.
  • Enables developers to add business logic to most system events including button clicks, related record updates and visualforce pages.

Datatypes in Apex

  • Primitives

Apex primitives include the following datatypes.

  1. Integer
  2. Boolean
  3. Decimal
  4. Double
  5. Date
  6. Date Time
  7. Time
  8. String
  9. Long
  10. ID- Any valid salesforce.com Id.
  • sObjects
  • Any  object that can be stored in force.com platform database.
  • sObject variable unlike primitive variable refers to row of data in salesforce. That is a complete record as a variable.

Hadoop MapReduce

Hadoop MapReduce is the main core components of Hadoop and is a programming model Hadoop MapReduce helps implementation for processing and generating large data sets, it uses parallel and distributed algorithms on a cluster. Hadoop MapReduce can handle large scale data: petabytes, exabytes.
Mapreduce framework converts each record of input into a key/value pair.

What is Blockchain and cryptocurrency

To understand more about Blockchain and crypto currency, lets explain about current Banking system works.

Current Banking systems : when a user does an online or ATM transaction , the centralized banking ledger verifies and confirm the authenticity of accounts. For that work, every bank or third party sites charges to user.

Blockchain is not like banking centralized ledger but this software uses a decentralized ledger across the thousands of computers and every transactions are updated in each and every ledger. That means everyone is aware of the transactions rather than a centralized bank stores all information and charges for that. There are volunteering systems who does this effort of maintaining all ledgers for block chain. 

Block chain uses cryptography mythology to protect the ledger information so that no one can modify or destroy this.

Block chain concept is utilized by Crypto currency , online voting system, signature system, agreement systems etc.

Top 20 cryptocurrency 2017

bitcoin BTC
ethereum ETH
bitcoincash BCH
ethereumclassic ETC
litecoin LTC
einsteinium EMC2
dash DASH
ripple XRP
bitcoingold BTG
zcash ZEC
eos EOS
qtum QTUM
syscoin SYS
neo NEO
monero XMR
vertcoin VTC
iota IOT
powerledger POWR
omisego OMG
santiment SAN

Summary about Jmeter and performance testing

Summary about Jmeter and performance testing

Jmeter recording

How to create Jmeter scripts?

Recording Jmeter scripts using Jmeter’s HTTP(S) Test Script recorder. There are two ways

1)      Manually adding scripts ( Test plan >> Tread Group >> Add>> Sampler >> HTTP Request )

2)      Recording using Jmeter’s HTTP(S) Test Script recorder

How to record Jmeter scripts using HTTP(S) Test Script recorder

Prior doing that we need to configure browser and learn about the Proxy setup

Jmeter to Application server communication need to be routed through a browser Proxy for this recording purpose. For that you may need to select the Browser (here we can use Firefox browser”

1)      Navigate to Firefox >> Tools >> options >> Advanced >> Network >> Settings

2)      Select Manual Proxy configuration >> HTTP Proxy = localhost & Port = 8080

How to run Jmeter in Jenkins

steps:

Jenkins setup and performance plugin setup:
1) copy performance plugin into Jenkin’s home directry before you start the test.
2) to do that – you can download the performance plugin “performance.hpi” from the site https://wiki.jenkins-ci.org/display/JENKINS/Performance+Plugin
3) how to find the home directry of jenkins – to do that you can navigate to jenkins home page (localhost:8080) and then
4) click on “Manage Jenkins” and then click on “Configure system” the you will notice “Home directy” path in there.

Configure Jmeter and create a basic script in Jmeter:
5) download Jmeter Binary zip file from Jmeter site http://jmeter.apache.org/download_jmeter.cgi
6) unzip it and go to the “bin” directory of the Jmeter folder, wherre you will notice “user.properties” file.
7) open the file in notepad or notepad++ or any other text editor
8) add a line “jmeter.save.saveservice.output_format=xml” to that. Save and close the “user.properties” file
9) create a Jmeter script and make sure you can run it in non GUI mode i.e either in DOS mode or using shell scripts in MAC (note down the commands used in respective OS and it could be used in Jenkins job setup)
Note: for windows command line run, you can use the following commands

C:\[JMETER BIN directory]\jmeter.bat -Jjmeter.save.saveservice.output_format=xml -n -t C:\[JMETER script “.jmx” file] -l Jmeter_test_results.jtl

Note 1: For detailed topics on Jmeter scripts creation , please visit Jmeter , Jmeter recording 

setup Jenkin’s job to run Jmeter scripts
9) go to Jenkins home page (localhost:8080) and then click on “New Item” on “Freestyle project”
10) in the “New item” page, give some name in the item name field and go to below to section “Build” and add build step
11) add build step can be either a) “execute windows batch command” for windows or b) “Execute shell” for MAC
12) provide your command in there and save.
13) Click on “Build now” which would call the Jmeter (jmx) file and run the program
14) after the run, you can verify the Jenkins console to review the results.

Summary about Jenkins, Selenium and QTP automation frameworks

Summary about Jenkins, Selenium and QTP automation frameworks

How to run Jenkins locally

1) go to https://jenkins.io and download Jenkins.war file
2) place the war file in a folder (e.g. C:\Jenkins\Jenkins.war )
3) then open command prompt (windows start menu > run > cmd will open command prompt )
4) in command prompt, go to folder C:\Jenkins\ ( command : “CD C:\Jenkins\” )  and then run command ” java -jar Jenkins.war ”
5) this will exract a folder name “.jenkins” into your user folder ( the path is usually “C:\users\”your login”\.jenkins”
6) copy “.jenkins” folder and paste to folder C:\Jenkins\, so that you have “C:\Jenkins\.jenkins” as the folder path.
7) Now you setup a Enviroment variable (to set up that go to Control panel > system > Advanced System settings )
8) then add Enviroment variable as “JENKINS_HOME” and value as “C:\Jenkins\.jenkins”

You all set to run Jenkins on your machine!

Open a browser and type “localhost:8080” to see Jenkins session.

Selenium features

Selenium supports Cross Browser Testing and parallel testing. The Selenium tests can be run on multiple browsers and multiple machines and multiple Operating systems. Selenium offers open source tools and supports test automation for web applications

Supports several scripting languages like Java, Python, C#, and PHP

Reporting are very easy and extensible,  Selenium uses Browser native commands. It locates and actions applied on UI elements

TestNG quick summary:

TestNG’s is Selenium + reporting features. It is easy to generate reports using Listeners and Reporters in TestNG

Features of TestNG includes the following,

1)      Annotations – please refer my annotation blog Annotation – TestNG’s test case priority

2)      Supports parameterization/ data driven testing

3)      Test cases can be grouped and parallel testing is allowed.

Automaton testing using Cucumber – Behavior driven development (BDD)

Application behavior is the main focus on BDD. The requirements are written in English which gives more readability and understandability of the requirement.

So any roles in the company (Tester, developer, end user, and techno functional person) can read it and understand it. Also this will reduce the complication in terms of missing requirement or misrepresenting or misunderstanding requirements between different roles (Developer /tester / end user)

Gherkin is a business readable language – refer below for an example. Below feature file is integrated with Selenium and are having user stories as below.

Please refer below – “feature, Scenario, Given, When, And, Then “are the Keywords below to understand on how to write a feature file.

What is TestRunner in Cucumber

In order to link Cucumber with Selenium WebDriver, you need to start a Java project in eclipse IDE.

Then, add both Cucumber and Selenium jar files

Write test runner code and execute the same . Please refer BDD testing details on Selenium Cucumber

Selenium jenkins integration steps are as below:

Jenkin related steps:
1) start jenkins by running command in DOS prompt (detailed steps in here )
2) then make sure you are able to access url : localhost:8080
3) then you need to configure jenkins to run the selenium scripts – for that click on “Manage Jenkins”
4) then click on Configure systems
5) Find out the jdk files are installed (usually in C:\ program files … folder path) and copy paste the path in JDK section “JDK Installations” in ” Configure systems” which you are already in.
6) Give JDK name “JAVA_HOME” and provide Java path below in the next field.

Selenium related steps:
3) Open eclipse IDE and start new Java project
4) make sure you added selenium jars (Selenium server standalone jar file which you can download add to new project) to support selenium framework for your automation testing.
5) then create a simple selenium script – make sure it is running and completing successfully in Eclipse.
6) Also create a xml file give a name “Xml1.xml”  Make sure Run “Xml1.xml” as “TestNG Suite” is working fine in Eclipse. Also notedown the xml file path in selenium project. create a lib folder in that and add all jar files which are required.

Commmand prompt:
7) navigate to that project folder in command prompt and set all required classpath like bin and lib etc which are already in xml file folder in selenium project which you got from selenium project in eclipse.
8) then type command “Java org.testng.testNG Xml1.xml” which will display results in command prompt/DOS screen
9) now create a batch file “Batch1.bat” which contains the above command and also a command for compiling as e.g “java -cp bin;lib/* org.testng.testNG Xml1.xml”

Jenkins setup to build and run the file:
10) in Jenkins, create a “new item” with selection of “Freestyle project”
11) then select “Advance options” and put the Selenium project home directory path in there.
12) the build trigger section, select Batch file execution option in there, then put the batch file name “Batch1.bat”
13) click and save the new item
14) click on “Build Now” and verify the “Console output”

 

How to configure Hub & Node machines for selenium parallel test execution

Configuring Hub machine

1) Start the command prompt/DOS prompt

2) Navigate to the folder location where the Selenium server jar file is kept.

3) Type java –jar selenium-server-standalone-[VERSION].jar –role hub

Note: [VERSION] is the one your downloaded version of selenium-server-standalone Jar file.

Selenium Hub

4) Now type: http://localhost:4444 in browser

Your will see the below screen

5) Now type: http://localhost:4444/console in browser

Configuring Node machines

Follow the same steps 1 to 2 in node machines

Then type,

Java –jar selenium-server-standalone-[VERSION].jar –role node –hub http://yourHUBmachineIP:4444/grid/register

How to run selenium tests in Jenkins

Jenkins configuration:

To run selenium scripts in Jenkins, Jenkins needs to started.

To make Jenkins server start, please use the following command in the Jenkins folder of your machine when Jenkins.warfile is downloaded from internet…

  1. “java -jar jenkins.war” in DOS / command prompt mode.
  2. Then you need to bring the browser up and type “localhost:8080” to see jenkins web UI ready.
  3. Then navigate to Jenkins >> Manage Jenkins and click on “Configure system”
  4. Then scroll down to see the “JDK installations” section in the pag
  5. There you enter “JAVA_HOME” for “JDK name” field.
  6. Provide the Java-JDK file folder path for “JAVA_HOME” field.

Note:  Java-JDK file folder path is usually “C:\Program files\Java\JDK….”

Note: Disable “Install Automatically” check box else it will update with new Java versions and your selenium program might get conflicts

Selenium script development:

  1. create a package and class in Eclipse
  2. and then create a small test script – like print some message based on UI or Browser title name etc
  3. you could create a TestNG project
  4. Then TestNG.xml file will be created in Eclipse

Note: to get the XML folder path in project home directory, you could go to Eclipse project and right click to see properties.

Note: you also need to put all the jar files required for selenium testing under the lib folder(you may need to create”lib” folder)

Just to test your TestNG scripts are working, you can navigate to Project home directly (XML located) through DOS/Command prompt and then type as below:

Note: before that you need to set class path as bin directory of Project home folder. Command : “set classpath=C:\Selenium\project\bin;” as an example for binary file

Note1: similarly lib files, Command : “set classpath=C:\Selenium\project\lib\*” as an example

or command: set classpath=C:\Selenium\project\bin;C:\Selenium\project\lib\*;

Then execute testng.xml file through command prompt

command : java org.testng.TestNG testng.xml

Batch file creation for Jenkin execution

Create a batch file using notepad – steps

  1. Type the below contents in Notepad without quotes.

‘ java -cp bi;lib/* org.testng.TestNG testng.xml ‘

2) save the notepad as “runSelenium.bat” which will create a bat file. Place it in project home directory.

Jenkins job creation:

  1. Open Jenkins, then click on “New item”
  2. Enter item name as “JenkinSeleniumTest”
  3. Select “Freestyle project” , click Ok
  4. Then click on “Advance” button under the “Advance projects options”
  5. Then select “Use custom workspace”, then give the project home directory path in “Directory” field.
  6. Then “Add build setup” under “Build” and select “Execute Windows batch Command”
  7. Then type “runSelenium.bat” in the command field, click apply and save it.
  8. Then in the “JenkinSeleniumTest”, then click on “Build Now” which will call the batch file and then Selenium script internally.
  9. Verify the “Console output” in “JenkinSeleniumTest” which will show the Selenium execution results.

How to send email at every build with Jenkins

Jenkins default configuration setting allows to send email notification for build failure, someone breaks the build etc.

  1. To send email for every build Install Email-ext plugin.
  2. Once it is installed, click on Configure System
  3. Then in “Jenkins Location” section & “Extended E-mail Notification” – enter your email ids
  4. In “E-mail Notification” section, enter the SMTP server name to “SMTP server”
  5. Click “Advanced”, Click “Use SMTP Authentication” to enter required information
  6. verify “Test configuration by sending test e-mail”
  7. Configure a project to send email at every build
  8. Click “Add post-build action” and then Click “Editable Email Notification”
  9. Go to  “Advanced Settings” to “Add Trigger”
  10. then Click “Always” , Save

Qtp script to close all open browsers ..

Call CloseAllBrowsers_ExcludingALM()

Function CloseAllBrowsers_ExcludingALM()
‘To ceclare Variables
Dim objDes, objList, objIndex

‘To Create Object Description for all opened browsers opened.
Set objDes=Description.Create
objDes.Add “micClass”,”Browser”

‘To get all the opened browsers objects from Desktop
Set ObjList=Desktop.ChildObjects(objDes)

‘Indexing always starts from “0”
For objIndex=0 to objList.count-1
‘To cverify the name of the browser is “HP Application Lifecycle Management”
If lcase(objList(objIndex).GetROproperty(“name”))<>”HP Application Lifecycle Management” then
‘Close the Browser
objList(objIndex).close
Exit For
End If
Next

Jenkins reset user password :

First stop the Jenkins service if you are already running jenkins

Go to the folder where jenkin’s config.xml file is stored (generally C:\jenkins\.jenkins\config.xml)

Open config.xml file using notepad++ or any text editor

Search for <useSecurity>true</useSecurity> and change that to <useSecurity>false</useSecurity>, Save the file.

re-start Jenkins service (using Java -jar jenkins.war in commandline)

You should not be seeing login prompt but directly accessing Jenkins home page when you type localhost:8080 in browser.

QTP integration with Jenkins

Create a “.vbs” file as below and save the file as “AOM.vbs” in C:\QTP\VBS folder.
In Jenkins create Job, Select ‘Execute Windows Batch Command’ in Build Step. Enter below command.
and then use that in Jenkins.
Note: To learn how to create a Jenkins job or how to start Jenkins – please refer create a Jenkins job and Run Jenkins locally in my site.
Below code is the “AOM.vbs” which is called by Jenkins Job.
Call QTP()
Public function QTP()
‘Create Quick test pro(QTP/UFT) object
Set objQTP = CreateObject(“QuickTest.Application”)
objQTP.Launch
objQTP.Visible = True
‘to open QTP Test
objQTP.Open “Test file path “, True
Set objResults= CreateObject(“QuickTest.RunResultsOptions”)
objResults.ResultsLocation = “Result path of qtp”  ‘Set the results location
‘to run qtp script results
objQTP.Test.Run objResults
‘to close QTP
objQTP.Test.Close
objQTP.Quit
End function

Summary on Web testing and mobile apps

Summary on Web testing and mobile apps

 

What is the difference between Web Layer (Presentation Tier) vs Application Layer (Logic Tier) vs Database Layer (Data Tier)

  1. Presentation Layer is the interface to outside world e.g. web site.
  2. Application Layer is a framework to create the interface to the Web site or Presentation Tier
  3. Database Layer is the database and associated logic needed to query details.

Web Layer (Presentation Tier)

Contains Virtual Machines and Physical Machines with OS can be Windows, UNIX or Linux

Contains Apache web Server, Apache tomcat, Sun Java Web Server or MS Internet Information Services (IIS)

Application Layer (Logic Tier)

Contains Virtual Machines and Physical Machines with OS can be Windows, UNIX or Linux

Contains Apache tomcat, Red Hat JBoss, BEA Web Logic or IBM WebSphere app server

Database Layer (Data Tier)

Contains Virtual Machines and Physical Machines with OS can be Windows, UNIX or Linux

Contains SQL or Oracle

 

How to Use WhatsApp in a Web Browser?

1) Go to web.whatsapp.com in a web browser on a computer.
2) Then, on your iOS/Android/Windows mobile phone, open WhatsApp and press the Options on top right corner side
3) then press WhatsApp Web from the options.
4) use iOS/Android/Windows mobile phone to scan the QR code shown on the browser on your computer.

Headless web browsers

headless web browsers or programs are used to stimulate the browsers where there is no GUI is used for browser actions,

If you want to do browser operations or collect data from UI, there programming concepts will be used.

headless web browsers are listed as below,

HtmlUnit – No GUI browser for Java programmers and its pure java implementation, Open source programs. JavaScript support/DOM emulated. mainly used for used for testing purposes or to retrieve information from web sites.

Spynner – Programmatic web browsing module having AJAX support for Python

Ghost – it is a webkit web client written in python. it is WebKit-based. JavaScript supported and Open source.

Watir-webdriver- it an open source Ruby library for automating tests. Complete JAva script Support via Browsers

Twill – Allows users to browse the Web using command-line interface . Supports automated testing on web applications and Open source.

Awesomium –  is Chromium-based. and supports JavaScript and provides HTML-powered interfaces.

ZombieJS – Open source headless testing using Node.js. JavaScript support/emulated DOM.

SimpleBrowser – Open source web browser engine designed for automation tasks. It is built for .Net framework and No JavaScript support.

Successful test automation

Successful test automation approach – simplest way to build cost effective automation frameworks which can give better ROI.

To maximize automation benefits in terms of best output and cost effectiveness is by implementing best matching framework based on your product line.

When an organization plans for cost effective automation frameworks, they can always consider 2 types of frameworks to start having maximized results with less effort and cost. Basically optimizing your efforts and get better ROI relatively in less time. 

  1. User acceptance testing – Find out a Behavioral driven development (BDD) framework – either cucumber selenium or Robot Framework. I will explain about Cucumber Selenium framework in this article and will explain the reason for including one BDD Framework for your automation. With the help of Business team, identify the most critical applications and most critical functionalities. Once you have BDD framework is ready, you can make sure it is running every day and sending our reports using Jenkins integration. Which will make your automation is ready to Join the DevOps culture. As most of the companies like google, amazon etc have already adopted DevOps while ago.
  1. Regression testing – You can follow any regular automation approach and adopting DevOps, continuous testing, monitoring and reporting. You can opt data driven or keyword or hybrid based on your expertise and application type. 

Let me give an example when you consider the type 1 which is BDD for acceptance testing. 

The very reason for BDD is that it can utilize business user’s collaboration in automation. This is the easiest way to get business team’s association on your automation efforts.

In my opinion, when you compare within different BDDs, cucumber has upper edge as opposed to Robot Framework as simplicity in it that will help business user involve easily.

As an e.g. cucumber frameworks need feature file and typical feature file example will have user scenarios as below,

Feature: Login Action

Scenario: User successfully Login to application with valid user id and password

            Given User is on application login prompt page

            When User enters User name and password

            Then Message displayed as Login is successful

Scenario Outline: data parameter test

            When User navigates to application search screen

            Then user input “<InputInfo>” as “InputVal”

Examples:

            | InputInfo |

            | ABC1  |

            | ABC2 |

In the above example you can see that a business user can simply follow the format for above 2 test cases which is written in feature file.

1)    Scenario

2)    Scenario Outline:

Later automation architect or engineer can develop test runner file and convert this as automation test scripts. Please refer link for more details about cucumber framework.

Benefits

  1. User collaboration
  2. Due to user collaboration, we can make sure all the critical application are automated
  3. Due to user collaboration, we can make sure all the critical features in every important applications are automated
  4. Due to Jenkins integration, you can make sure test can be scheduled for every day run, to make application as robust in terms of quality.

What is Block chain and cryptocurrency

What is Blockchain and cryptocurrency

To understand more about Blockchain and cryptocurrency, lets explain about current Banking system works.

Current Banking systems : when a user does an online or ATM transaction , the centralized banking ledger verifies and confirm the authenticity of accounts. For that work, every bank or third party sites charges to user.

Blockchain is not like banking centralized ledger but this software uses a decentralized ledger across the thousands of computers and every transactions are updated in each and every ledger. That means everyone is aware of the transactions rather than a centralized bank stores all information and charges for that. There are volunteering systems who does this effort of maintaining all ledgers for block chain. 

Block chain uses cryptography mythology to protect the ledger information so that no one can modify or destroy this.

Block chain concept is utilized by Cryptocurrency , online voting system, signature system, agreement systems etc.

To know more about top rated cryptocurrency names – please click here

Top 20 cryptocurrency 2017

Top 20 cryptocurrency 2017

bitcoin BTC
ethereum ETH
bitcoincash BCH
ethereumclassic ETC
litecoin LTC
einsteinium EMC2
dash DASH
ripple XRP
bitcoingold BTG
zcash ZEC
eos EOS
qtum QTUM
syscoin SYS
neo NEO
monero XMR
vertcoin VTC
iota IOT
powerledger POWR
omisego OMG
santiment SAN

How to Implement Maven TestNG Selenium Grid project

How to Implement Maven TestNG Selenium Grid project

High level Steps:
note: I will be adding detailed description for each steps below,

1. Install Eclipse Editior
2. In Eclipse, navigate to “Help >> Install New Software” then install Maven plugin.
3. Create a Maven project, which will have a pom.xml having the option to add all dependencies jars.
     like TestNG, XLS API jars, Reporting jars etc.
4. Once that is made, convert the project into TestNG project that process will generate another xml file. (name it as testng.xml)
5. Now in Eclipse project, create a package and class. Write your programs in it.
6. In the testng.xml, mention the class names which will be included while run.
7. Now right click on pom.xml file and run as “Maven test” which will download dependency jars and store to project and then run the program.

How to reverse an array in java

How to reverse an array in java

package arrays;
import java.util.Arrays;
 
public class ArrayReverse 
{  
 
public static void main(String[] args) 
{
 
int abc[] = {2, 3, 4, 5, 6,7, 8, 9, 10};
System.out.println(“Before Reverse, Arrays are like this : “+Arrays.toString(abc));
 
int temp;
int arrayloop = abc.length/2;
 
for (int i = 0; i < arrayloop; i++) 
{
temp = abc[i];
abc[i] = abc[abc.length-1-i];
abc[abc.length-1-i] = temp;
}
System.out.println(“After Reverse, Arrays are like this  : “+Arrays.toString(abc));
 
 
}
}

What is LinkedList and an example in Java?

What is LinkedList and an example in Java?

LinkedList is a linear collections of data elements.

     // Declaring LinkedList

       LinkedList<String> abclinked = new LinkedList<String>();

 

 

       abclinked.add(“a”);

       abclinked.add(“b”);

       abclinked.add(“c”);

   

system.out.println(“the linked list is ” + abclinked )

 

 

Linked Lists are Dynamic size and this feature certainly has an endge over Array. insertion and deletion also possible for Linked Lists which may not be done on Array which is already defined.

 

 

The downside of Linked Lists is that the extra memory space for a pointer is required with each element of the list. Also accessing elements are sequential manner starting from the first node is difficult.

How to reverse an array in java – Please click here

What is Thanksgiving?

What is Thanksgiving?

Thanksgiving is a national holiday of USA, Canada etc. In USA, it is celebrated on 4th Thursday of November. This day is to give thanks for the blessing of the harvest. Modern Thanksgiving has been changed a lot. Everyone are curious about the Thanksgiving deals 🙂 and it has been well celebrated as a holiday. Most of the organization gives holidays on 4th Thursday & Friday of November making it a long weekend. One can look for Thanksgiving recipes, deals, restaurants to make the holidays more enjoyable.

What is DevOps?

What is DevOps?

DevOps is the latest Development Methodology where Dev team and Operations team are collaborated for better productivity , Improving the time to market of the product releases etc.

DevOps uses lots of tool like Git for Version controlling , Jenkins for Integrating multiple DevOps tools, helps on better communications between Developers, Testers, Operations team etc. Selenium is another tool used as part of DevOps which is a test automation and Jenkins controls and manages Selenium execution.

Puppet is another DevOps tool used for configuration management. Configuration script will be stored in puppet server and puppet agents on various VMs or target machines will be communicating puppet master. There are build management tools like Maven will be part of DevOps. Nagios is another DevOps tool which monitors systems, servers, infrastructures to make sure the deployed applications are running on production servers without any issues.

For testing specific requirements, Jenkins will help to send notification to Tester when a build is available for testing. Jenkins will trigger the selenium scripts and after execution, the results will be send out to target users including developers, management teams etc.

 

How to use JMeter for login authentication?

How to use JMeter for login authentication?

Regular Expression Extractor is used to handle this situation. Following steps may be used,

  1. First find out the GET request where the authentication required & POST request that posts the credential to login
  2. The response from the GET request should have tokens which needs to be be extracted and sent as a parameter in the POST request.
  3. Add a Regular Expression Extractor to store these tokens and include the tokens as parameter in the POST request

What is polymorphism in java with example

What is polymorphism in java with example

polymorphism means one object can take multiple forms. lets explain this using a method poly() in java class.

steps:

  1. create a package polymorphismPkg in eclipse
  2. create a class polymorphismClass  in eclipse
  3. now write below code in the class polymorphismClass  

package polymorphismPkg;

public class polymorphismClass {

public static void main(String[] args) {

polymorphismClass obj1 = new polymorphismClass();

obj1.poly(1, 2);
obj1.poly(1, 2, 3);
obj1.poly(1, 22.11);

}

public static void poly(int a, int b)

{
System.out.println(“this is first method for polymorphism”);
}

public static void poly(int n, int b, int c)

{
System.out.println(“this is like first method but number of argument is different in signature “);

}

public static void poly(int n, double b)

{
System.out.println(“this is like first method but argument order is different in the signature “);

}

}

 

 

 

What is Inheritance in Java with example

What is Inheritance in Java with example

One class in Java can get the methods and properties from other class – this helps reducing the coding efforts , increase code reusability and maintainability.

e.g. 

public class classB extends classB {

}

in the above Java code, classB class gets the methods and properties from classA class.

steps,

  1. create a meaningful project and a package in eclipse
  2. create 2 classes classA and classB under the package (Codes are below)

Code for classA class as below:

package inheritancePkg;

public class classA {

public void A()

{

System.out.println(“this is from father class”);
}

}

 

Code for classB class as below:

package inheritancePkg;

public class classB extends classA // extends classA is inheritance from classA class to classB

// so we are able to write obj1.add() from father.

{
public static void main(String[] args)
{

classB obj1 = new classB();
obj1.A();
obj1.B();

}

public void B()

{
System.out.println(“this is from son class “);

}

}

 

Top 5 sql interview questions and answers

Top 5 sql interview questions and answers

What is DDL, DML, DCL, TCL in SQL ?

DDL refers to Data Definition language. DDL is used to create/modify the structure of Database. e.g. CREATE, ALTER, DROP statement..

DML refers to Data Manipulation language. DML is used to retrieve, modify, delete, insert and update data in database. e.g. SELECT, UPDATE, INSERT statement

DCL refers to Data Control Language. DCL is used to create roles, permissions, and control access to database. e.g. GRANT, REVOKE statement.

TCL refers to Transactional Control Language. TCL is used to manage different transactions occurring within a database. e.g COMMIT, ROLLBACK statement

What is the difference between UNION vs UNION ALL?

          UNION and UNION ALL are used for merging two tables which has similar structure.

the difference between UNION and UNION ALL is that the UNION removes the duplicates while merging tables but UNION ALL do not and retain all duplicates.

UNION is slower in performance  as it has additional task of removing duplicates which causes more time in  execution.

What is the difference between query and subquery?

A Query is a code written to fetch information from the database where as subquery is a query within another query.  Basically subquery is an inner query. SubQuery is designed to executed first. The result of subquery is passed on to the main query which then process using the subquery output.

What is a stored procedure?

Stored Procedure is a function having several SQL statements. Stored procedure can be executed to process all SQL statements in it.

What is the difference between WHERE clause and HAVING clause?

Both WHERE and HAVING are used for filtering out records based conditions. WHERE clause can only be applied for static non-aggregated column whereas HAVING for aggregated columns.
SELECT * FROM Cricketbat WHERE batlenght > 2 feet
SELECT COUNT(Cricketbat)
FROM Bat
GROUP BY Team
HAVING COUNT(Cricketbat) > 2 feet;

What is DELETE and TRUNCATE commands?

DELETE command is used to remove selected rows from a table. A WHERE clause can be used to specify the rows to be deleted

 

What is difference between select and select distinct

Top 5 Salesforce Interview questions

Top 5 Salesforce Interview questions

1. What is object in salesforce?

Objects are database tables used to store specific data. There are two types of objects. 1. Standard objects 2. Custom objects.

2. What are different types of relationship in salesforce?

There are two different types of relationship in salesforce.
1. Master detail relationship
2. Lookup relationship

3. What is a trigger in salesforce ?

A Trigger is a code that is executed before or after a record is inserted or updated.

4. How many reports can be added to salesforce dashboard ?

20

5. What is validation rule ?

While creating or modifying a record, based on certain conditions validation rule helps to display error message.

6. What are escalation rules in sales force?

Escalation rules can be created on sales force case object and based on priority escalation emails can be sent.

Top 20 sql interview questions and answers

Top 20 sql interview questions and answers

What is DDL, DML, DCL, TCL in SQL ?

DDL refers to Data Definition language. DDL is used to create/modify the structure of Database. e.g. CREATE, ALTER, DROP statement..

DML refers to Data Manipulation language. DML is used to retrieve, modify, delete, insert and update data in database. e.g. SELECT, UPDATE, INSERT statement

DCL refers to Data Control Language. DCL is used to create roles, permissions, and control access to database. e.g. GRANT, REVOKE statement.
TCL refers to Transactional Control Language. TCL is used to manage different transactions occurring within a database. e.g COMMIT, ROLLBACK statement

What is the difference between UNION vs UNION ALL?

          UNION and UNION ALL are used for merging two tables which has similar structure.

the difference between UNION and UNION ALL is that the UNION removes the duplicates while merging tables but UNION ALL do not and retain all duplicates.

UNION is slower in performance  as it has additional task of removing duplicates which causes more time in  execution.

What is the difference between query and subquery?

A Query is a code written to fetch information from the database where as subquery is a query within another query.  Basically subquery is an inner query. SubQuery is designed to executed first. The result of subquery is passed on to the main query which then process using the subquery output.

What is a stored procedure?

Stored Procedure is a function having several SQL statements. Stored procedure can be executed to process all SQL statements in it.

What is the difference between WHERE clause and HAVING clause?

Both WHERE and HAVING are used for filtering out records based conditions. WHERE clause can only be applied for static non-aggregated column whereas HAVING for aggregated columns.
SELECT * FROM Cricketbat WHERE batlenght > 2 feet
SELECT COUNT(Cricketbat)
FROM Bat
GROUP BY Team
HAVING COUNT(Cricketbat) > 2 feet;

What is DELETE and TRUNCATE commands?

DELETE command is used to remove selected rows from a table. A WHERE clause can be used to specify the rows to be deleted

What is TRUNCATE commands?

TRUNCATE is used for removing all rows from the table. Truncate operation cannot be reversed but but delete can be reversed/rollback.

What is Log Caches of SQL Server?

Log cache is a memory pool allocated to read/write the log pages. A group of cache pages are available in each log cache.

What is Inner join?

Inner join is used for returning rows when there is at least one match of rows between the tables used in the inner join query.

What is Full Join?

Full join is used for returning all the rows from the left side table and all the rows from the right side table.

What is Right Join?

Right join return all rows of Right hand side table and matched rows in left hand table. Non matched rows will show null values for left had side.
Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand side table.

What is Left Join?

Left join return all rows of Left hand side table and matched rows in right hand table. Non matched rows will show null values for right hand side.

What are the SQL MAX() and MIN() Functions?

The MAX() function returns the largest value in the selected column.

The MIN() function returns the smallest value in the selected column.

SELECT MAX(Weight) AS LargestWeight

FROM CricketBats;

SELECT MIN(Weight) AS SmallestWeight

FROM CricketBats;

What are the SQL AVG(), COUNT() and SUM() Functions

The SQL AVG() function returns the average value in a numeric values column.

e.g.

SELECT AVG(Weight)

FROM Cricketbats;

The SQL COUNT() function returns the number of rows count that matches with a specified criteria.

SELECT COUNT(ProductID)

FROM Cricketbats;

The SQL SUM() function returns the total sum of a numeric values in a specific column.

e.g

SELECT SUM(Weight)

FROM Cricketbats;

What is SQL UPDATE Statement?

The SQL UPDATE statement is used for modifying the existing records in the selected table.

e.g as below:

UPDATE Users

SET UserContactName=’First name Last name’, City=’City1′

WHERE UserID=1;

What is SQL ORDER BY Keyword?

The purpose of ORDER BY keyword is to sort the results in ascending or descending order.

example for ascending order

SELECT * FROM Users

ORDER BY State ASC;

or

SELECT * FROM Users

ORDER BY State;

example for descending order

SELECT * FROM Users

ORDER BY State DESC;

What is a NULL Value in SQL?

NULL values can not be compared using operators =, <, or <> so we will need to use the “IS NULL” or “IS NOT NULL” operators instead.

SELECT UserName, UserContactName, Address FROM Persons

WHERE Address IS NULL;

SELECT UserName, UserContactName, Address FROM Persons

WHERE Address IS NOT NULL;

What is SQL INSERT INTO Statement?

The INSERT INTO statement is used for inserting new records to a table.

e.g.

INSERT INTO Users (UserName, UserContactName, UserAddress, City, ZipCode, State, Country)

VALUES (‘Test1′,’Firstname last name’,’address 1, 2,3 ‘,’City namer’,’99999′,’Statename’,’Countryname’);

What is SQL INSERT INTO SELECT Statement?

The SQL INSERT INTO SELECT statement is used for copying data from one table and then to insert to someother table.

e.g. as below:

INSERT INTO Users (UserName, UserCity, Country)

SELECT VendorName, VendorCity, Country FROM Vendors;

What is the SQL DELETE Statement?

The SQL DELETE statement is used for deleting the existing records in the selected table.

e.g as below:

DELETE FROM Users

WHERE UserName=’Firstname1 Lastname1′;

What is AND, OR and NOT Operators in SQL?

AND, OR, and NOT operators are combined with the WHERE clause to get the desired filtered results.

e.g

SELECT * FROM Users

WHERE State =’illinois’ AND City=’Chicago’;

SELECT * FROM Users

WHERE City=’Chicago’ OR City=’New York’;

SELECT * FROM Users

WHERE NOT State =’Chicago’;

What is SQL WHERE Clause?

SQL WHERE clause is used to filter records and its added as below

e.g.

SELECT States FROM Users where Usersgroup = ‘1’;

What is the SQL SELECT TOP Clause ?

The SELECT TOP clause is used to specify the number of records to return.

e.g as below:

SELECT TOP 100 * FROM Users;

How to send email at every build with Jenkins

How to send email at every build ?

Jenkins default configuration setting allows to send email notification for build failure, someone breaks the build etc.

  1. To send email for every build Install Email-ext plugin
  2. Once it is installed, click on Configure System
  3. Then in “Jenkins Location” section & “Extended E-mail Notification” – enter your email ids
  4. In “E-mail Notification” section, enter the SMTP server name to “SMTP server”
  5. Click “Advanced”, Click “Use SMTP Authentication” to enter required information
  6. verify “Test configuration by sending test e-mail”
  7. Configure a project to send email at every build
  8. Click “Add post-build action” and then Click “Editable Email Notification”
  9. Go to  “Advanced Settings” to “Add Trigger”
  10. then Click “Always” , Save

Jenkins reset user password

Jenkins reset user password :

First stop the Jenkins service if you are already running jenkins

Go to the folder where jenkin’s config.xml file is stored (generally C:\jenkins\.jenkins\config.xml)

Open config.xml file using notepad++ or any text editor

Search for <useSecurity>true</useSecurity> and change that to <useSecurity>false</useSecurity>, Save the file.

re-start Jenkins service (using Java -jar jenkins.war in commandline)

You should not be seeing login prompt but directly accessing jenkins home page when you type localhost:8080 in browser.

To run Jenkins locally click here

Summary of SQL

What are the SQL MAX() and MIN() Functions?

The MAX() function returns the largest value in the selected column.

The MIN() function returns the smallest value in the selected column.

SELECT MAX(Weight) AS LargestWeight

FROM CricketBats ;

SELECT MIN(Weight) AS SmallestWeight

FROM CricketBats ;

What are the SQL AVG(), COUNT() and SUM() Functions

The SQL AVG() function returns the average value in a numeric values column.

e.g.

SELECT AVG(Weight)

FROM Cricketbats;

The SQL COUNT() function returns the number of rows count that matches with a specified criteria.

SELECT COUNT(ProductID)

FROM Cricketbats;

The SQL SUM() function returns the total sum of a numeric values in a specific column.

e.g

SELECT SUM(Weight)

FROM Cricketbats;

What is SQL UPDATE Statement?

The SQL UPDATE statement is used for modifying the existing records in the selected table.

e.g as below:

UPDATE Users

SET UserContactName=’First name Last name’, City=’City1′

WHERE UserID=1;

What is SQL ORDER BY Keyword

The purpose of ORDER BY keyword is to sort the results in ascending or descending order.

example for ascending order

SELECT * FROM Users

ORDER BY State ASC;

or

SELECT * FROM Users

ORDER BY State;

example for descending order

SELECT * FROM Users

ORDER BY State DESC;

What is a NULL Value in SQL?

NULL values can not be compared using operators =, <, or <> so we will need to use the “IS NULL” or “IS NOT NULL” operators instead.

SELECT UserName, UserContactName, Address FROM Persons

WHERE Address IS NULL;

SELECT UserName, UserContactName, Address FROM Persons

WHERE Address IS NOT NULL;

What is SQL INSERT INTO Statement?

The INSERT INTO statement is used for inserting new records to a table.

e.g.

INSERT INTO Users (UserName, UserContactName, UserAddress, City, ZipCode, State, Country)

VALUES (‘Test1′,’Firstname last name’,’address 1, 2,3 ‘,’City namer’,’99999′,’Statename’,’Countryname’);

What is SQL INSERT INTO SELECT Statement?

The SQL INSERT INTO SELECT statement is used for copying data from one table and then to insert to someother table.

e.g. as below:

INSERT INTO Users (UserName, UserCity, Country)

SELECT VendorName, VendorCity, Country FROM Vendors;

What is the SQL DELETE Statement?

The SQL DELETE statement is used for deleting the existing records in the selected table.

e.g as below:

DELETE FROM Users

WHERE UserName=’Firstname1 Lastname1′;

What is AND, OR and NOT Operators in SQL

AND, OR, and NOT operators are combined with the WHERE clause to get the desired filtered results.

e.g

SELECT * FROM Users

WHERE State =’illinois’ AND City=’Chicago’;

SELECT * FROM Users

WHERE City=’Chicago’ OR City=’New York’;

SELECT * FROM Users

WHERE NOT State =’Chicago’;

What is SQL WHERE Clause?

SQL WHERE clause is used to filter records and its added as below

e.g.

SELECT States FROM Users where Usersgroup = ‘1’;

What is the SQL SELECT TOP Clause ?

The SELECT TOP clause is used to specify the number of records to return.

e.g as below:

SELECT TOP 100 * FROM Users;

How to Use WhatsApp in a Web Browser?

Solution:

1) Go to web.whatsapp.com in a web browser on a computer.
2) Then, on your iOS/Android/Windows mobile phone, open WhatsApp and press the Options on top right corner side
3) then press WhatsApp Web from the options.
4) use iOS/Android/Windows mobile phone to scan the QR code shown on the browser on your computer.

Whatsapp tricks & cheats

How to locate important messages in Whatsapp easily?

Solution: WhatsApp selected messages can be starred.

How to do: Hold down the message and select the star icon on top of whatsapp.

Then You can see all your starred messages directly from your WhatsApp homescreen(View contact >> started message)

How to Use WhatsApp in a Web Browser

1) go to web.whatsapp.com in a web browser on a computer.

2) Then, on your iOS/Android/Windows mobile phone, open WhatsApp and press the Options on top right corner side

3) then press WhatsApp Web from the options.

4) use iOS/Android/Windows mobile phone to scan the QR code shown on the browser on your computer.

How to restrict the view on profile photo and personal status in Whatsapp

Solution: Settings > Account > Privacy and press the right sub-menus for profile photo, status etc.

How to turn it off / hide the Last seen time in WhatsApp?

Follow the path Settings > Account > Privacy > Last Seen

How to turn it off / hide the Read Receipts indication.

Settings > Account > Privacy > Read Receipts

How to reference an old message in WhatsApp and wanted to respond to that.

Hold down the message, then press the left arrow on Android/’reply’ button on iOS. Then type the message that you wanted to display as a response to the old message. This is helpful when multiple conversations are happening in a group chat and you want to respond to a particular message.

How to hide the WhatsApp message previews?

Solution: Go to Settings > Notifications > Show Preview, change the settings.

WhatsApp – how to format the text message

             -it-  => it

             *it* =>    it

            ~it~ =>   it

WhatsApp- Sending voice message instead of typing

            In Android phones – tap on mic icon in WhatsApp and record your voice or use Google’s speech to text engine

            In iPhone phones – tap on mic icon in WhatsApp and record your voice

   ...   ...   ...   ...   ...   ...  ...   ...   ...

How to use while loop in java

While loop in Java

import java.util.Scanner;

class WhileLoop {
public static void main(String[] args) {
int i;

Scanner input = new Scanner(System.in);
System.out.println(“Please input an integer value”);

while ((i = input.nextInt()) != 0) {
System.out.println(“You have entered ” + i);
System.out.println(“Please input an integer value”);
}

System.out.println(“Gone out of loop”);
}
}

How to implement Multiplication program in java

How to implement Multiplication program in java:

import java.util.Scanner;

class TableForMultiplication
{
public static void main(String args[])
{
int i, j;
System.out.println(“Enter an integer to display it’s multiplication table…”);
Scanner in = new Scanner(System.in);
i = in.nextInt();
System.out.println(“Multiplication table of “+i+” is :-“);

for ( j = 1 ; j <= 10 ; j++ )
System.out.println(i+”*”+j+” = “+(i*j));
}
}

What is AND, OR and NOT Operators in SQL

AND, OR, and NOT operators are combined with the WHERE clause to get the desired filtered results.

 

e.g SELECT * FROM Users

WHERE State =’illinois’ AND City=’Chicago’;

 

e.g SELECT * FROM Users

WHERE City=’Chicago’ OR City=’New York’;

 

e.g SELECT * FROM Users

WHERE NOT State =’Chicago’;

What is SQL WHERE Clause

SQL WHERE clause is used to filter records and its added as below
SELECT States FROM Users where Usersgroup = ‘1’;

Selenium Tutorial 

Karate framework

Selenium features
Selenium features – what are the main features of selenium.
Selenium IDE
How to Validate the XPATH is correct in Selenium automation
How to take snapshot of browser using selenium
How to run selenium on linux server using Firefox binary
How to handle the error popup on site security certificate is not trusted with chrome selenium python automation
How to Implement Maven TestNG Selenium Grid project
How to Install TestNG in Eclipse IDE for Selenium WebDriver automation testing
How to run selenium tests in jenkins
Selenium jenkins integration
Selenium grid hub and node configuration
Protractor vs Selenium
Robot framework and Selenium2Library
Apache poi selenium webdriver supports Selenium projects

Breaking while loop in Java

import java.util.Scanner;

class TestingBreakWhileLoop {
public static void main(String[] args) {
int i;

Scanner input = new Scanner(System.in);

while (true) {
System.out.println(“Input an integer for this test program”);
i = input.nextInt();

if (i == 0) {
break;
}
System.out.println(“You have entered …  ” + i);
}
}
}

What is SQL ORDER BY Keyword

The purpose of ORDER BY keyword is used to sort the results in descending or ascending order

 

e.g SELECT * FROM Users

ORDER BY State DESC;

 

e.g SELECT * FROM Users

ORDER BY State ASC;

 

or

 

SELECT * FROM Users

ORDER BY State;

String reverse using java script split method

Assume given string ‘str’ value is “welcome”
function stringRev(str) {
var splitString = str.split(“”);// Use the reverse() method to reverse the array
var arrayReverse = splitString.reverse(); // equals to [“e”, “m”, “o”, “c”, “l”, “e”, “w”]

// Use join() method to join the elements of the array into a string as below in comments
var joinArray = arrayReverse .join(“”); //  [“e”, “m”, “o”, “c”, “l”, “e”, “w”] to “emoclew”

//Return the reversed string
return joinArray; // “emoclew”
}

stringRev(‘welcome’);

Differences between SQL and PL/SQL

PL/SQL is procedural language where s SQL is data oriented language.
PL/SQL purpose is to create applications but SQL is data manipulator and reviewer
PL/SQL executions works at block of code level while SQL execution is per statement at a time.
PL/SQL servers for building, formatting and display application screens but SQL sources data for that screens.
PL/SQL is procedural based and instructs database on how to do but SQL is declarative level which helps database on what to do.
PL/SQL purpose it to code program blocks, procedures, triggers, functions, and packages but SQL is used to code queries, DCL, DML and DDL statements
SQL can be subset of PL/SQL but PL/SQL can not be subset of SQL
 

 Popular databases or filesystems that uses SQL – Please click here

Defect priority and severity

Severity indicates the seriousness of the defect.
Severity types are Critical, Major, Moderate, Minor, Cosmetic
 
Priority indicates how quickly the defect needs to be fixed.
Priority types are High, Medium, Low.
 

Low Severity and Low Priority: A cosmetic error in a page which is not important to users.

High Severity and High Priority: An error in the login feature which does not allow user to login to application or a server error in the web application.

Low Severity and High Priority : The spelling mistakes that happens on the cover page or heading or title of an application.

High Severity and Low Priority: A page access error which page is rarely used by users.

What is Apex?

Apex is a programming language for salesforce (only)

    • Object Oriented Program, in which the data types have to defined.
    • Allows developers for flow execution in force.com platforms.
    • Enables developers to add business logic to most system events including button clicks, related record updates and visualforce pages.

Datatypes in Apex

  • Primitives

Apex primitives include the following datatypes.

  1. Integer
  2. Boolean
  3. Decimal
  4. Double
  5. Date
  6. Date Time
  7. Time
  8. String
  9. Long
  10. ID- Any valid salesforce.com Id.
  • sObjects
    • Any  object that can be stored in force.com platform database.
    • sObject variable unlike primitive variable refers to row of data in salesforce. That is a complete record as a variable.

What is Salesforce

Salesforce.com is an American cloud computing company.
Salesforce offers Software as a Service (SaaS) platform which helps in Customer Relationship Management.
It has a multi-tenant architecture and subscriptions.

 The following are the application clouds in Salesforce CRM.
1. Sales Cloud
2. Service Cloud
3. Marketing Cloud
4. Data cloud
5. App Cloud
6. Analytics Cloud
7. Community Cloud
Salesforce also offers Platform as a Service (PaaS) using Force.com sites.
People involved in Salesforce Implementation
1. End User ( Customer)
2. Administrator
3. Developer
4. Consultant
The following are the list of Salesforce Certifications.
1. Certified Administrator
2. Certified Advanced Administrator
3. Certified Sales Cloud Consultant
4. Certified Service Cloud Consultant
5. Certified Force.com Platform App Builder
6. Certified Force.com Platform Developer I
7. Certified Force.com Platform Developer II
8. Certified Technical Architect

Quick summary of QTP

QTP Quick summary:

Automation Frameworks

  1. Record and Playback.(Records application flow using QTP and playback)
  2. Data driven. (Data controls the automation flow through a spreadsheet/datatable)
  3. Keyword driven. (Functions are mapped to Keywords)
  4. Hybrid approach (Combination of Keyword and data driven)
  5. Business process testing(BPT)
  6. Functional Decomposition

Types of QTP Licenses

  1. Seat
  2. Concurrent

How to record/playback

  1. Open QTP/UFT
  2. Click on File > New Test
  3. Click on the ‘Record’ button
  4. Perform actions on the application under test
  5. Click ‘Stop’ at the end of Recording session

Types of QTP/UFT Add-ins

  1. Activex Controls
  2. Web
  3. Visual Basic
  4. Java Add-in 8.2
  5. Terminal Emulator for mainframe
  6. .NET
  7. Oracle
  8. SAP Solutions
  9. PeopleSoft
  10. Siebel
  11. Web Services
  12. Etc

What is Record and Run Settings

  1. Record and Run Settings window will be triggered right after the recording started for a new Test or an existing test.
  2. user can see tabs based on the loaded Add-in
  3. user can provide Application under test input criteria (like url, application path etc)

What are the various Recording Modes

There are 3 recording modes available

  • Standard Recording: this is used for normal recording to capture user operations on the application.
  • Analog Recording: this will record the exact mouse and keyboard operations.
  • Low level Recording: this will record the mouse movements with respect to the coordinates on the AUT (application under test) Window.

What is Expert View

  • Shows the every user actions done on the  application in the form of codes.

Active Screen view

  • Every code generated after recording will show corresponding application screen on Active screen window. This will help tracking the code vs application objects.

Actions in QTP:

It’s the recorded set of codes which are logically meaningful to the application flow. E.g Customer creation flow.

Types of actions in QTP:

  • Non-reusable Action – action that can be called only in the test where it is stored, and can be used only once.
  • Reusable Action – action that can be called from any QTP/UFT test
  • External Action – reusable action stored with another QTP/UFT test. External actions are read-only.

Object Repository in QTP/UFT:

  • QTP stores the recorded object details in a specific location in the tool named the ‘Object Repository’
  • Browser – page – Objects are stored in a hierarchal manner.
  • Every object will have some listed set of methods as e.g button can perform Click using QTP codes.

Web server vs Application server vs Database server

Web server vs Application server vs Database server

Web server serves a web content (HTML and static content) over the HTTP protocol.

Application server is a container on which one can build and expose business logic and processes to client applications through various protocols like HTTP. Some cases it will have internal web server. Application server is heavy in terms of resource usage.

Database server refers to the back-end system of a database application using client/server architecture. The database server performs tasks such as data analysis, storage, data manipulation, archiving, and other non-user specific tasks

Apache vs NGINX 

Both Apache and NGINX are web servers and used to serve the page contents back to users. NGINX has more efficiency in terms response especially when it comes to larger set of static pages. NGINX caching makes the contents ready available to user’s browser without going back to server to process the requsts from scratch.

Please search following topics in the search option of the site

Selenium jenkins integration
Protractor vs Selenium

java springboot

package com.example.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Service
public class GitService {

private static final Logger logger = LoggerFactory.getLogger(GitService.class);

/**
 * Executes the workflow by invoking the shell script for Git clone/pull and Gradle tests.
 * 
 * @param gitUrl      The Git repository URL.
 * @param branch      The Git branch.
 * @param targetDir   The target directory to clone/pull the repository.
 * @return The output of the shell script execution.
 */
public String executeWorkflow(String gitUrl, String branch, String targetDir) {
    try {
        // Path to the shell script
        String scriptPath = "./git-workflow.sh";

        // Build the command to run the shell script
        List<String> command = new ArrayList<>();
        command.add("bash");  // Specify to use bash shell
        command.add(scriptPath);  // Path to the shell script
        command.add(gitUrl);  // Git URL
        command.add(branch);  // Git branch
        command.add(targetDir);  // Target directory

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.directory(new File("."));  // Set working directory (current directory)
        processBuilder.redirectErrorStream(true);  // Merge error and output streams

        // Start the process
        Process process = processBuilder.start();

        // Capture the output
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
                logger.info(line);
            }
        }

        // Wait for the process to complete
        int exitCode = process.waitFor();
        logger.info("Shell script exited with code: " + exitCode);

        if (exitCode == 0) {
            return "Workflow completed successfully.\n" + output.toString();
        } else {
            throw new RuntimeException("Shell script failed with exit code: " + exitCode);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to execute workflow: " + e.getMessage(), e);
    }
}

}

!/bin/bash

Input arguments

GIT_URL=$1
BRANCH=$2
TARGET_DIR=$3

Clone or pull the repository

if [ -d “$TARGET_DIR” ]; then
echo “Directory $TARGET_DIR already exists. Pulling latest changes from $BRANCH branch…”
cd “$TARGET_DIR”
git pull origin “$BRANCH”
else
echo “Cloning $GIT_URL into $TARGET_DIR…”
git clone -b “$BRANCH” “$GIT_URL” “$TARGET_DIR”
cd “$TARGET_DIR”
fi

Run Gradle tests

echo “Running ./gradlew clean test –info…”
./gradlew clean test –info

import java.io.BufferedReader;import java.io.File;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public class GitService { /** * Executes the shell script using Git Bash on Windows. * * @param scriptPath The full path to the shell script. * @return The output of the shell script execution. */ public String executeShellScript(String scriptPath) { try { // Specify the path to Git Bash or another Bash shell installed on Windows String bashPath = “C:\\Program Files\\Git\\bin\\bash.exe”; // Path to Git Bash // Build the command to execute the shell script List<String> command = new ArrayList<>(); command.add(bashPath); // Git Bash executable command.add(scriptPath); // Full path to the shell script ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(“.”)); // Set working directory (current directory) processBuilder.redirectErrorStream(true); // Merge error and output streams // Start the process Process process = processBuilder.start(); // Capture the output StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(“\n”); System.out.println(line); // Print the output to console } } // Wait for the process to complete int exitCode = process.waitFor(); System.out.println(“Shell script exited with code: ” + exitCode); if (exitCode == 0) { return “Script executed successfully.\n” + output.toString(); } else { throw new RuntimeException(“Shell script failed with exit code: ” + exitCode); } } catch (Exception e) { throw new RuntimeException(“Failed to execute shell script: ” + e.getMessage(), e); } } public static void main(String[] args) { GitService gitService = new GitService(); // Full path to the shell script String scriptPath = “C:\\path\\to\\your\\script\\abc.sh”; // Execute the shell script and print the output String result = gitService.executeShellScript(scriptPath); System.out.println(result); }}

asycn below

package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableAsync;@SpringBootApplication@EnableAsync // Enable async processingpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}

package com.example.demo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class GitService {

@Async  // Make this method asynchronous
public CompletableFuture<String> executeWorkflow(String repo, String branch, String frameworkType) {
    try {
        // Define the command for Git clone with the provided repo and branch
        List<String> command = new ArrayList<>();
        command.add("C:\\Program Files\\Git\\bin\\bash.exe");  // Path to Git Bash
        command.add("-c");
        command.add("git clone -b " + branch + " " + repo);

        // Start the Git clone process
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.directory(new File("."));  // Set working directory (current directory)
        processBuilder.redirectErrorStream(true);  // Merge error and output streams

        Process process = processBuilder.start();
        StringBuilder output = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        }

        // Wait for the process to complete
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new RuntimeException("Git clone failed with exit code: " + exitCode);
        }

        // Execute the framework-specific command (e.g., Gradle build)
        if ("gradle".equalsIgnoreCase(frameworkType)) {
            return CompletableFuture.completedFuture(executeFrameworkCommand("./gradlew clean test --info", output));
        } else {
            // Other framework commands can be added here as needed
            return CompletableFuture.completedFuture("Unsupported framework type: " + frameworkType);
        }

    } catch (Exception e) {
        throw new RuntimeException("Failed to execute workflow: " + e.getMessage(), e);
    }
}

private String executeFrameworkCommand(String command, StringBuilder output) throws Exception {
    // Execute the framework-specific command (e.g., Gradle clean test)
    ProcessBuilder frameworkBuilder = new ProcessBuilder("C:\\Program Files\\Git\\bin\\bash.exe", "-c", command);
    frameworkBuilder.directory(new File("your_project_subdirectory"));  // Change directory to the cloned repo
    frameworkBuilder.redirectErrorStream(true);

    Process frameworkProcess = frameworkBuilder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(frameworkProcess.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
    }

    int exitCode = frameworkProcess.waitFor();
    if (exitCode == 0) {
        return "Workflow executed successfully.\n" + output.toString();
    } else {
        throw new RuntimeException("Framework command failed with exit code: " + exitCode);
    }
}

}

package com.example.demo.controller;import com.example.demo.model.WorkflowRequest;import com.example.demo.service.GitService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;import java.util.concurrent.CompletableFuture;@RestController@RequestMapping(“/api”)public class WorkflowController { @Autowired private GitService gitService; @PostMapping(“/execute-workflow”) public CompletableFuture<ResponseEntity<String>> executeWorkflow(@RequestBody WorkflowRequest request) { return gitService.executeWorkflow(request.getRepo(), request.getBranch(), request.getFrameworkType()) .thenApply(output -> ResponseEntity.ok(output)) .exceptionally(ex -> ResponseEntity.status(500).body(“Error: ” + ex.getMessage())); }}

curl -X POST http://localhost:8080/api/execute-workflow \ -H “Content-Type: application/json” \ -d ‘{ “repo”: “https://github.com/crewAIInc/crewAI-examples.git”, “branch”: “master”, “frameworkType”: “gradle” }’

Gitservice for Linux machine

package com.example.demo.service;import org.springframework.stereotype.Service;import reactor.core.publisher.Mono;import java.io.BufferedReader;import java.io.File;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;@Servicepublic class GitService { public Mono<String> executeWorkflow(String repo, String branch, String frameworkType) { return Mono.fromCallable(() -> { String tarballUrl = repo + “/archive/” + branch + “.tar.gz”; String repoDirName = extractRepoNameFromUrl(repo) + “-” + branch; // The extracted directory usually has the format {repoName}-{branch} // Step 1: Download the repository tarball using wget List<String> wgetCommand = new ArrayList<>(); wgetCommand.add(“bash”); wgetCommand.add(“-c”); wgetCommand.add(“wget ” + tarballUrl); ProcessBuilder wgetProcessBuilder = new ProcessBuilder(wgetCommand); wgetProcessBuilder.directory(new File(“.”)); // Set working directory (current directory) wgetProcessBuilder.redirectErrorStream(true); Process wgetProcess = wgetProcessBuilder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(wgetProcess.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(“\n”); } } int wgetExitCode = wgetProcess.waitFor(); if (wgetExitCode != 0) { throw new RuntimeException(“wget failed with exit code: ” + wgetExitCode); } // Step 2: Extract the downloaded tarball List<String> tarCommand = new ArrayList<>(); tarCommand.add(“bash”); tarCommand.add(“-c”); tarCommand.add(“tar -xvf ” + branch + “.tar.gz”); ProcessBuilder tarProcessBuilder = new ProcessBuilder(tarCommand); tarProcessBuilder.directory(new File(“.”)); // Set working directory (current directory) tarProcessBuilder.redirectErrorStream(true); Process tarProcess = tarProcessBuilder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(tarProcess.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(“\n”); } } int tarExitCode = tarProcess.waitFor(); if (tarExitCode != 0) { throw new RuntimeException(“Tar extraction failed with exit code: ” + tarExitCode); } // Step 3: Execute framework-specific command (e.g., Gradle build) if (“gradle”.equalsIgnoreCase(frameworkType)) { return executeFrameworkCommand(“./gradlew clean test –info”, output, repoDirName); } else { return “Unsupported framework type: ” + frameworkType; } }); } private String executeFrameworkCommand(String command, StringBuilder output, String repoDirName) throws Exception { // Execute the framework-specific command (e.g., Gradle clean test) ProcessBuilder frameworkBuilder = new ProcessBuilder(“bash”, “-c”, command); frameworkBuilder.directory(new File(repoDirName)); // Change directory to the extracted repo frameworkBuilder.redirectErrorStream(true); Process frameworkProcess = frameworkBuilder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(frameworkProcess.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(“\n”); } } int exitCode = frameworkProcess.waitFor(); if (exitCode == 0) { return “Workflow executed successfully.\n” + output.toString(); } else { throw new RuntimeException(“Framework command failed with exit code: ” + exitCode); } } private String extractRepoNameFromUrl(String repoUrl) { // Extract the repository name from the URL return repoUrl.substring(repoUrl.lastIndexOf(“/”) + 1).replace(“.git”, “”); }}

Ragas and RAG Testing

Ragas – collab – https://colab.research.google.com/drive/1zXfffyjY2ryTBV7makO6ztYrnB2ntT88?usp=sharing

import json
from datasets import Dataset
import os
from ragas import evaluate
from ragas.metrics import faithfulness, answer_correctness
from langchain_ollama import OllamaLLM
from requests.exceptions import ConnectionError
from langchain_community.llms import Ollama

# Set environment variables (if needed)
os.environ["OPENAI_API_KEY"] = "NA"  # Replace "NA" with your API key if necessary

# Path to your JSON file
json_file_path = "eval_input.json"  # Update this with the path to your actual JSON file

# Function to load JSON data
def load_json_data(file_path):
    try:
        with open(file_path, "r") as f:
            data = json.load(f)
        return data
    except FileNotFoundError:
        print(f"Error: The file {file_path} was not found.")
        return None
    except json.JSONDecodeError:
        print(f"Error: Failed to decode the JSON file {file_path}.")
        return None

# Load the data from the JSON file
data_samples = load_json_data(json_file_path)

if data_samples:
    try:
        # Initialize the LLM (ensure your local Ollama instance is running)
        evaluator_llm = Ollama(model = "llama3")
#         evaluator_llm = OllamaLLM(
#             model="llama3.2",
#             base_url="http://localhost:11434"  # Ensure Ollama is running at this URL
#         )

        print('--------------------------------------')

        llm_test = evaluator_llm.invoke("can you tell 4 genai frameworks?")
        print(llm_test)
        print('--------------------------------------')

        # Convert the data into a Hugging Face `Dataset` format
        dataset = Dataset.from_dict({
            'question': data_samples['question'],
            'answer': data_samples['answer'],
            'contexts': data_samples['contexts'],
            'ground_truth': data_samples['ground_truth']
        })

        # Perform evaluation using RAGAS metrics
        score = evaluate(dataset, metrics=[faithfulness, answer_correctness])

        # Convert the score to a pandas DataFrame and print it
        score_df = score.to_pandas()
        print(score_df)

    except ConnectionError as e:
        print(f"Connection error: {e}")
        print("Ensure that the LLM server is running and accessible at http://localhost:11434.")
    except Exception as e:
        print(f"An error occurred: {e}")
else:
    print("No data to evaluate due to an issue with the JSON file.")
{
  "question": [
    "When was the first super bowl?",
    "Who won the most super bowls?"
  ],
  "answer": [
    "The first superbowl was held on Jan 15, 1967",
    "The most super bowls have been won by The New England Patriots"
  ],
  "contexts": [
    [
      "The First AFL–NFL World Championship Game was an American football game played on January 15, 1967, at the Los Angeles Memorial Coliseum in Los Angeles."
    ],
    [
      "The Green Bay Packers...Green Bay, Wisconsin.",
      "The Packers compete...Football Conference."
    ]
  ],
  "ground_truth": [
    "The first superbowl was held on January 15, 1967",
    "The New England Patriots have won the Super Bowl a record six times"
  ]
}

{
  "question": [
    "What are the global implications of the USA Supreme Court ruling on abortion?",
    "Which companies are the main contributors to GHG emissions and their role in global warming according to the Carbon Majors database?",
    "Which private companies in the Americas are the largest GHG emitters according to the Carbon Majors database?",
    "What action did Amnesty International urge its supporters to take in response to the killing of the Ogoni 9?",
    "What are the recommendations made by Amnesty International to the Special Rapporteur on Human Rights Defenders?",
    "Who are the target audience of the two books created by Amnesty International on child rights?",
    "Which right guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations?",
    "Who has the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims?",
    "When can individuals be found guilty under Article 207.3 of the Russian Criminal Code?",
    "When does the prosecution consider statements contrary to the official position as 'false' under Article 207.3?",
    "What factors have contributed to the decline of independent civil society organizations in Nicaragua?",
    "What conditions designate wetlands as Ramsar sites?",
    "Where was COP15 held in 2022?",
    "What is the purpose of the agreement known as 30x30?",
    "Who failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area at COP15?",
    "What are the consequences of criminalizing abortion for marginalized individuals?",
    "What responsibilities should social media companies have in relation to ensuring access to accurate sexual and reproductive health information?",
    "What role do social media companies play in protecting users' rights online, regardless of their language and political views?",
    "What labor abuses were documented by Amnesty International in Qatar and how do they relate to the kafala system?",
    "When did the government of Qatar start repealing restrictions on migrant workers?"
  ],
  "answer": [
    "The global implications of the USA Supreme Court ruling on abortion can be significant, as it sets a precedent for other countries and influences the global discourse on reproductive rights. Here are some potential implications:\n\n1. Influence on other countries: The Supreme Court's ruling can serve as a reference point for other countries grappling with their own abortion laws. It can provide legal arguments and reasoning that advocates for reproductive rights can use to challenge restrictive abortion laws in their respective jurisdictions.\n\n2. Strengthening of global reproductive rights movements: A favorable ruling by the Supreme Court can energize and empower reproductive rights movements worldwide. It can serve as a rallying point for activists and organizations advocating for women's rights, leading to increased mobilization and advocacy efforts globally.\n\n3. Counteracting anti-abortion movements: Conversely, a ruling that restricts abortion rights can embolden anti-abortion movements globally. It can provide legitimacy to their arguments and encourage similar restrictive measures in other countries, potentially leading to a rollback of existing reproductive rights.\n\n4. Impact on international aid and policies: The Supreme Court's ruling can influence international aid and policies related to reproductive health. It can shape the priorities and funding decisions of donor countries and organizations, potentially leading to increased support for reproductive rights initiatives or conversely, restrictions on funding for abortion-related services.\n\n5. Shaping international human rights standards: The ruling can contribute to the development of international human rights standards regarding reproductive rights. It can influence the interpretation and application of existing human rights treaties and conventions, potentially strengthening the recognition of reproductive rights as fundamental human rights globally.\n\n6. Global health implications: The Supreme Court's ruling can have implications for global health outcomes, particularly in countries with restrictive abortion laws. It can impact the availability and accessibility of safe and legal abortion services, potentially leading to an increase in unsafe abortions and related health complications.\n\nIt is important to note that the specific implications will depend on the nature of the Supreme Court ruling and the subsequent actions taken by governments, activists, and organizations both within and outside the United States.",
    "According to the Carbon Majors database, the main contributors to greenhouse gas (GHG) emissions and their role in global warming are primarily fossil fuel companies. These companies extract, produce, and sell fossil fuels, which when burned release carbon dioxide (CO2) and other GHGs into the atmosphere. The top contributors include:\n\n1. Saudi Arabian Oil Company (Saudi Aramco): As the world's largest oil producer, Saudi Aramco is responsible for a significant portion of global GHG emissions. It is estimated to have contributed around 59.26 gigatons of CO2 equivalent (GtCO2e) between 1965 and 2017.\n\n2. Chevron Corporation: Chevron is one of the largest oil and gas companies globally and has contributed approximately 43.35 GtCO2e between 1965 and 2017.\n\n3. ExxonMobil Corporation: ExxonMobil is another major oil and gas company and has contributed around 41.90 GtCO2e between 1965 and 2017.\n\n4. BP plc: BP is a multinational oil and gas company and has contributed approximately 34.02 GtCO2e between 1965 and 2017.\n\n5. Royal Dutch Shell plc: Shell is one of the largest oil and gas companies globally and has contributed around 31.95 GtCO2e between 1965 and 2017.\n\n6. TotalEnergies SE: TotalEnergies is a French multinational oil and gas company and has contributed approximately 31.91 GtCO2e between 1965 and 2017.\n\n7. ConocoPhillips Company: ConocoPhillips is an American multinational energy corporation and has contributed around 20.67 GtCO2e between 1965 and 2017.\n\n8. PetroChina Company Limited: PetroChina is the largest oil and gas producer in China and has contributed approximately 17.26 GtCO2e between 1965 and 2017.\n\n9. Peabody Energy Corporation: Peabody Energy is the largest private-sector coal company globally and has contributed around 15.39 GtCO2e between 1965 and 2017.\n\n10. Glencore plc: Glencore is a multinational commodity trading and mining company and has contributed approximately 15.11 GtCO2e between 1965 and 2017.\n\nThese companies, along with others in the fossil",
    "According to the Carbon Majors database, the largest private companies in the Americas that are the largest GHG emitters are:\n\n1. Chevron Corporation (United States)\n2. ExxonMobil Corporation (United States)\n3. ConocoPhillips Company (United States)\n4. BP plc (United Kingdom, but with significant operations in the Americas)\n5. Royal Dutch Shell plc (Netherlands, but with significant operations in the Americas)\n6. Peabody Energy Corporation (United States)\n7. Duke Energy Corporation (United States)\n8. TotalEnergies SE (France, but with significant operations in the Americas)\n9. BHP Group Limited (Australia, but with significant operations in the Americas)\n10. Rio Tinto Group (United Kingdom/Australia, but with significant operations in the Americas)\n\nPlease note that the rankings may change over time as new data becomes available.",
    "Amnesty International urged its supporters to write letters to the Nigerian government, calling for an independent investigation into the killings of the Ogoni 9 and for those responsible to be brought to justice. They also called for an end to the human rights abuses in the Niger Delta region and for the protection of the rights of the Ogoni people.",
    "Amnesty International made several recommendations to the Special Rapporteur on Human Rights Defenders. These recommendations include:\n\n1. Urging states to fully implement the UN Declaration on Human Rights Defenders and ensure that national laws and policies are in line with international human rights standards.\n\n2. Calling on states to create a safe and enabling environment for human rights defenders, including by adopting legislation that protects defenders from threats, attacks, and reprisals.\n\n3. Encouraging states to establish effective mechanisms for the protection of human rights defenders, such as national human rights institutions and specialized units within law enforcement agencies.\n\n4. Urging states to investigate and hold accountable those responsible for attacks and threats against human rights defenders, ensuring that they are brought to justice in fair trials.\n\n5. Calling on states to repeal or amend laws that are used to criminalize or restrict the work of human rights defenders, including laws on defamation, sedition, and counter-terrorism.\n\n6. Encouraging states to provide adequate resources and support to human rights defenders, including funding for their work, access to legal assistance, and psychosocial support.\n\n7. Urging states to consult and engage with human rights defenders in the development and implementation of laws, policies, and programs that affect their rights and work.\n\n8. Calling on states to ensure that human rights defenders are able to access and share information freely, including through the internet and other digital platforms.\n\n9. Encouraging states to protect the rights of specific groups of human rights defenders who face particular risks and challenges, such as women defenders, indigenous defenders, and defenders working on issues related to sexual orientation and gender identity.\n\n10. Urging states to cooperate with the Special Rapporteur and other UN mechanisms in the promotion and protection of human rights defenders, including by responding to communications and requests for visits.",
    "The target audience of the two books created by Amnesty International on child rights are likely children and young adults.",
    "The right that guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations, is the right to truth.",
    "Everyone has the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims. This right is recognized by various international human rights instruments, such as the Universal Declaration of Human Rights and the International Covenant on Civil and Political Rights.\n\nThe victims of human rights violations and their families have a particular right to know the truth about what happened to them. This includes knowing the identities of the perpetrators and the fate of the victims, such as whether they are alive or dead, and if dead, the circumstances of their death.\n\nFurthermore, society as a whole has a right to be informed about human rights violations. This is essential for holding perpetrators accountable, preventing future abuses, and ensuring justice and reparations for the victims. Access to information about human rights violations also allows for public scrutiny and debate, which are crucial for building a culture of human rights and promoting transparency and accountability.\n\nJournalists, human rights defenders, and civil society organizations play a vital role in investigating and reporting on human rights violations. They have the right to access information, conduct independent investigations, and disseminate their findings to the public. Governments have a responsibility to protect and facilitate these activities, ensuring that individuals and organizations can operate freely and without fear of reprisals.\n\nIn summary, the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims, belongs to everyone. It is a fundamental aspect of promoting human rights, accountability, and justice.",
    "Under Article 207.3 of the Russian Criminal Code, individuals can be found guilty if they participate in an organized group or commit repeated acts of smuggling of cultural heritage items.",
    "Under Article 207.3 of the Russian Criminal Code, statements contrary to the official position are considered 'false' by the prosecution when they are intentionally made with the aim of discrediting the state or its authorities, or spreading false information that could potentially harm the public interest or cause significant damage. The prosecution will consider such statements as false if they are deliberately made to mislead the public or undermine the credibility of the state.",
    "There are several factors that have contributed to the decline of independent civil society organizations in Nicaragua:\n\n1. Repressive government policies: The Nicaraguan government, under President Daniel Ortega, has implemented a series of repressive policies that have targeted civil society organizations. These policies include restrictive laws, such as the Foreign Agents Law, which requires organizations receiving foreign funding to register as \"foreign agents\" and submit detailed financial reports. This has created a climate of fear and uncertainty for many organizations, leading to self-censorship and a decline in their activities.\n\n2. Harassment and intimidation: Civil society organizations in Nicaragua have faced harassment and intimidation from government authorities, including surveillance, arbitrary arrests, and physical attacks. Human rights defenders and activists have been particularly targeted, with many facing threats to their personal safety and the safety of their families. This has made it difficult for organizations to operate freely and has deterred many individuals from getting involved in civil society work.\n\n3. Lack of funding: The repressive policies and climate of fear have also made it difficult for civil society organizations to secure funding. Many international donors have been reluctant to support organizations in Nicaragua due to concerns about the government's crackdown on civil society. This has led to a decline in resources available for organizations to carry out their work, including advocacy, research, and service provision.\n\n4. Legal restrictions: The Nicaraguan government has implemented a series of legal restrictions that have made it difficult for civil society organizations to operate. These include laws that limit freedom of association, freedom of expression, and the right to peaceful assembly. Organizations that are critical of the government or engage in activities deemed \"political\" have faced increased scrutiny and legal challenges, further limiting their ability to operate independently.\n\n5. Polarization and division: The political situation in Nicaragua has become increasingly polarized, with the government cracking down on dissent and opposition voices. This has created a climate of fear and mistrust, making it difficult for civil society organizations to collaborate and coordinate their efforts. The lack of unity and solidarity among civil society actors has weakened their collective impact and made it easier for the government to suppress their activities.\n\nOverall, the decline of independent civil society organizations in Nicaragua can be attributed to a combination of repressive government policies, harassment and intimidation, lack of funding, legal restrictions, and polarization. These factors have created a hostile environment for civil society, leading to a decline in their numbers and activities.",
    "Wetlands are designated as Ramsar sites based on the following conditions:\n\n1. The wetland must be of international importance, either ecologically, botanically, zoologically, or hydrologically.\n\n2. The wetland should support a significant number of rare, vulnerable, or endangered species of plants or animals.\n\n3. The wetland should be a habitat for migratory species.\n\n4. The wetland should have exceptional biodiversity or ecological processes.\n\n5. The wetland should provide important services to the local community, such as water purification, flood control, or groundwater recharge.\n\n6. The wetland should have cultural, scientific, educational, or recreational values.\n\n7. The wetland should be under threat from human activities or face potential degradation.\n\n8. The wetland should have effective management and conservation plans in place or the potential to develop them.\n\nThese conditions are assessed by the Ramsar Convention on Wetlands, an international treaty aimed at conserving and sustainably using wetlands worldwide.",
    "COP15 was held in Kunming, China in 2022.",
    "The purpose of the agreement known as 30x30 is to conserve and protect 30% of the planet's land and oceans by the year 2030. This agreement aims to address the global biodiversity crisis and the impacts of climate change by preserving and restoring ecosystems, promoting sustainable land and ocean management practices, and safeguarding the habitats of numerous plant and animal species. The goal is to ensure the long-term health and resilience of the planet's natural resources and to support the well-being of both human and non-human communities.",
    "At COP15, the United Nations Climate Change Conference held in 2009 in Copenhagen, Denmark, the failure to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area was primarily attributed to the governments of several countries. These countries included Canada, Australia, New Zealand, and the United States. These governments were criticized for their reluctance to acknowledge the rights and land claims of Indigenous Peoples, which hindered the inclusion of Indigenous lands as protected areas in the conference's agreements.",
    "Criminalizing abortion can have severe consequences for marginalized individuals, particularly those who are already facing various forms of discrimination and inequality. Some of the consequences include:\n\n1. Health risks: When abortion is criminalized, individuals may resort to unsafe and illegal methods to terminate their pregnancies, leading to serious health complications and even death. Marginalized individuals, who often have limited access to healthcare and resources, are more likely to be affected by these risks.\n\n2. Economic burden: Marginalized individuals, who are more likely to face financial constraints, may struggle to afford safe and legal abortions in countries where it is criminalized. This can lead to increased financial burdens, as they may have to travel long distances or seek expensive underground services.\n\n3. Limited reproductive choices: Criminalizing abortion restricts individuals' reproductive choices and autonomy. Marginalized individuals, who already face various barriers to accessing healthcare and education, may be further limited in their ability to make informed decisions about their reproductive health.\n\n4. Increased inequality: Criminalizing abortion disproportionately affects marginalized individuals, exacerbating existing inequalities. Women from low-income backgrounds, racial and ethnic minorities, LGBTQ+ individuals, and those living in rural areas often face additional barriers to accessing safe and legal abortion services, further widening the gap between privileged and marginalized groups.\n\n5. Criminalization of pregnancy: In some cases, criminalizing abortion can lead to the criminalization of pregnancy itself. This can result in the surveillance and punishment of pregnant individuals, particularly those from marginalized communities, who may be subjected to invasive monitoring, discrimination, and even imprisonment for actions perceived as harmful to the fetus.\n\n6. Mental health impact: The criminalization of abortion can have significant psychological consequences for marginalized individuals. The stigma and shame associated with seeking illegal abortions or being unable to access safe services can lead to increased stress, anxiety, and depression.\n\n7. Reproductive injustice: Criminalizing abortion perpetuates reproductive injustice by denying marginalized individuals the right to control their own bodies and make decisions about their reproductive health. It reinforces systemic inequalities and denies them the same reproductive rights and freedoms enjoyed by more privileged individuals.\n\nIt is important to note that these consequences are not limited to criminalizing abortion alone but are often intertwined with broader social, economic, and healthcare disparities faced by marginalized communities.",
    "Social media companies have a responsibility to ensure access to accurate sexual and reproductive health information. Here are some key responsibilities they should have:\n\n1. Promote accurate information: Social media platforms should actively promote and prioritize accurate sexual and reproductive health information over misinformation or harmful content. This can be done by using algorithms to identify and reduce the visibility of false or misleading information.\n\n2. Fact-checking and verification: Social media companies should invest in fact-checking mechanisms to verify the accuracy of sexual and reproductive health information shared on their platforms. They should work with experts and organizations specializing in sexual and reproductive health to ensure the information is reliable and evidence-based.\n\n3. Transparency and disclosure: Social media companies should be transparent about their content moderation policies and algorithms. They should disclose how they handle sexual and reproductive health information and what measures they take to ensure accuracy. This transparency will help users understand the reliability of the information they encounter.\n\n4. Collaborate with experts and organizations: Social media companies should collaborate with reputable experts, organizations, and health authorities to develop guidelines and standards for accurate sexual and reproductive health information. They should seek input from these stakeholders to ensure that their policies and practices align with the latest scientific evidence and best practices.\n\n5. User education and awareness: Social media companies should invest in user education and awareness campaigns to help users identify accurate sexual and reproductive health information. This can include providing tips on how to evaluate the credibility of sources, recognizing misinformation, and understanding the importance of evidence-based information.\n\n6. Reporting and addressing misinformation: Social media platforms should have clear and accessible mechanisms for users to report misinformation related to sexual and reproductive health. They should promptly investigate and take appropriate action against accounts or content that spread false or harmful information.\n\n7. Accessibility and inclusivity: Social media companies should ensure that accurate sexual and reproductive health information is accessible to all users, including those with disabilities or from marginalized communities. They should consider the needs of diverse populations and provide information in multiple languages and formats.\n\n8. Continuous improvement: Social media companies should regularly evaluate and improve their policies, algorithms, and practices related to sexual and reproductive health information. They should stay updated with the latest research and feedback from users and experts to adapt their approaches and address emerging challenges.\n\nBy fulfilling these responsibilities, social media companies can play a crucial role in promoting accurate sexual and reproductive health information and empowering users to make informed decisions about their health.",
    "Social media companies play a crucial role in protecting users' rights online, regardless of their language and political views. Here are some key aspects of their role:\n\n1. Content moderation: Social media companies have the responsibility to moderate and remove content that violates their community guidelines, including hate speech, harassment, and misinformation. This helps protect users from harmful and abusive content, ensuring a safer online environment.\n\n2. Privacy and data protection: Companies must safeguard users' personal information and ensure their privacy rights are respected. This involves implementing robust data protection measures, obtaining user consent for data collection and usage, and providing transparent privacy policies.\n\n3. Algorithmic transparency: Social media platforms use algorithms to curate and personalize content for users. Ensuring transparency in these algorithms is crucial to prevent bias, discrimination, and the manipulation of information. Companies should disclose how algorithms work and take steps to address any unintended consequences.\n\n4. Accessibility and inclusivity: Social media companies should strive to make their platforms accessible to users of all languages and abilities. This includes providing language options, captioning for videos, and features that accommodate users with disabilities, ensuring equal access to information and participation.\n\n5. Fighting disinformation: Companies should actively combat the spread of disinformation and fake news on their platforms. This involves implementing fact-checking mechanisms, partnering with credible sources, and promoting media literacy to help users distinguish between reliable and misleading information.\n\n6. Transparency and accountability: Social media companies should be transparent about their policies, practices, and decision-making processes. They should provide clear avenues for users to report issues, appeal content removals, and seek redress. Regular transparency reports can help build trust and hold companies accountable.\n\n7. Collaboration with external stakeholders: Companies should collaborate with governments, civil society organizations, and experts to develop policies and practices that protect users' rights. Engaging in multi-stakeholder dialogues helps ensure diverse perspectives are considered and fosters a collective effort to address online challenges.\n\nOverall, social media companies have a responsibility to create a safe, inclusive, and rights-respecting online environment for all users, regardless of their language and political views.",
    "Amnesty International has documented several labor abuses in Qatar, particularly in relation to the kafala system. The kafala system is a sponsorship-based employment system that ties migrant workers to their employers, giving employers significant control over their workers' lives and rights. Here are some of the labor abuses documented:\n\n1. Exploitative working conditions: Migrant workers in Qatar often face long working hours, with some working up to 12 hours a day, six or seven days a week. They are also subjected to dangerous and hazardous working conditions, especially in the construction sector.\n\n2. Withheld wages: Many workers have reported that their employers withhold their wages for months, sometimes even years. This practice leaves workers in a vulnerable position, unable to leave their jobs or seek alternative employment.\n\n3. Passport confiscation: Employers often confiscate the passports of migrant workers, depriving them of their freedom of movement and making it difficult for them to leave the country or change jobs. This practice is a clear violation of workers' rights and leaves them trapped in exploitative situations.\n\n4. Forced labor and human trafficking: Amnesty International has documented cases of forced labor and human trafficking in Qatar. Some workers are deceived about the nature of their work or are forced to work against their will, often in conditions akin to modern-day slavery.\n\n5. Inadequate living conditions: Migrant workers in Qatar often live in overcrowded and unsanitary accommodation provided by their employers. These living conditions are substandard and do not meet basic human rights standards.\n\nThese labor abuses are directly linked to the kafala system, which gives employers excessive power and control over migrant workers. The system ties workers to their employers, making it difficult for them to assert their rights or seek redress for abuses. The kafala system creates a power imbalance that enables employers to exploit workers, leading to the documented labor abuses in Qatar.",
    "The government of Qatar started repealing restrictions on migrant workers in 2017."
  ],
  "contexts": [
    [
      "- In 2022, the USA Supreme Court handed down a decision ruling that overturned 50 years of jurisprudence recognizing a constitutional right to abortion.\n- This decision has had a massive impact: one in three women and girls of reproductive age now live in states where abortion access is either totally or near-totally inaccessible.\n- The states with the most restrictive abortion laws have the weakest maternal health support, higher maternal death rates, and higher child poverty rates.\n- The USA Supreme Court ruling has also had impacts beyond national borders due to the geopolitical and cultural influence wielded by the USA globally and the aid it funds.\n- SRR organizations and activists across the world have expressed fear about the ruling laying the groundwork for anti-abortion legislative and policy attacks in other countries.\n- Advocates have also observed the ruling's impact on progressive law reform and the stalling of the adoption and enforcement of abortion guidelines in certain African countries.\n- The ruling has created a chilling effect in international policy spaces, emboldening anti-abortion state and non-state actors to undermine human rights protections.",
      "The USA Supreme Court ruling on abortion has sparked intense debates and discussions not only within the country but also around the world. Many countries look to the United States as a leader in legal and social issues, so the decision could potentially influence the policies and attitudes towards abortion in other nations.",
      "The ruling may also impact international organizations and non-governmental groups that work on reproductive rights and women's health issues. Depending on the outcome, there could be shifts in funding, advocacy efforts, and collaborations with American counterparts, leading to ripple effects in the global fight for reproductive justice."
    ],
    [
      "In recent years, there has been increasing pressure on these major contributors to reduce their greenhouse gas emissions and transition to more sustainable practices. Many of these companies have made commitments to reduce their carbon footprint and invest in renewable energy sources. However, the role of these companies in global warming remains a contentious issue, with ongoing debates about their responsibility and accountability for the environmental damage caused by their operations.",
      "The Carbon Majors database identifies a small group of companies responsible for the majority of global greenhouse gas emissions. These companies include major oil and gas producers, as well as coal mining companies, whose activities have significantly contributed to climate change. The data from the Carbon Majors database highlights the disproportionate impact of these companies on the environment and the urgent need for action to address their emissions.",
      "- Fossil fuel companies, whether state or private, play a key role in the emissions that drive global warming.\n- According to the Carbon Majors database, 100 existing fossil fuel companies (and eight that no longer exist) have produced almost a trillion tons of GHG emissions in 150 years.\n- These 100 companies are responsible for 71% of all GHG emissions since 1988.\n- In the Americas, the private companies responsible for the most emissions during this period, according to the database, are from the United States: ExxonMobil, Chevron, and Peabody.\n- The largest emitter amongst state-owned companies in the Americas is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A.\n- Despite the fact that people with fewer resources, in particular from countries in the global South, do not make significant contributions to climate change, it is these people who are most affected by it.\n- Approximately half of the global population lives in areas that are \"very vulnerable\" to climate change, and it is people with considerable development constraints who are most exposed.\n- This disproportionately affects the human rights of people with fewer resources and greater risk in the context of climate change in the global South.\n- Between 2010 and 2020, human mortality due to climate disasters was 15 times higher in vulnerable regions and populations."
    ],
    [
      "The issue of greenhouse gas emissions has become a major concern for environmentalists and policymakers alike, as the impact of climate change becomes more apparent. Private companies in the Americas play a significant role in contributing to these emissions, with some being identified as the largest emitters in the region according to the Carbon Majors database.",
      "Reducing greenhouse gas emissions from private companies is a complex challenge that requires cooperation between governments, businesses, and consumers. Many companies are now taking steps to reduce their carbon footprint through initiatives such as investing in renewable energy, improving energy efficiency, and offsetting emissions through carbon credits.",
      "The private companies responsible for the most emissions during this period, according to the database, are from the United States: ExxonMobil, Chevron and Peabody.\nThe largest emitter amongst state-owned companies in the Americas is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A."
    ],
    [
      "In the case of the Ogoni 9, Amnesty International called on its supporters to take action by signing petitions, writing letters to government officials, and participating in protests and demonstrations. The organization also urged its members to raise awareness about the plight of the Ogoni people and the need for justice and accountability in their case. By mobilizing public pressure and solidarity, Amnesty International hoped to bring attention to the human rights abuses committed against the Ogoni 9 and to push for meaningful change and accountability.",
      "Amnesty International called on its vast network of supporters to deluge Nigerian authorities first with appeals for the defenders\u2019 freedom, and later with letters of outrage.",
      "Amnesty International is a global human rights organization known for its advocacy work on behalf of individuals facing injustice and persecution. The organization has a long history of campaigning for the rights of prisoners of conscience, political dissidents, and marginalized communities around the world. Through its research, lobbying efforts, and grassroots activism, Amnesty International seeks to hold governments and other powerful entities accountable for human rights violations and abuses."
    ],
    [
      "In recent years, Amnesty International has focused on issues such as the increasing threats faced by human rights defenders, particularly in authoritarian regimes, and the need for stronger international mechanisms to support and protect their work. The organization's recommendations to the Special Rapporteur often include calls for greater accountability for perpetrators of violence and harassment against defenders, as well as measures to ensure their safety and freedom to carry out their important work.",
      "Amnesty International recommends that the Special Rapporteur on the Situation of Human Rights Defenders embeds a focus on child and young HRDs in the future work of the mandate. \nAmnesty International recommends raising awareness about the differences between \"child\" and \"youth\" HRDs and the different context, needs, barriers, and challenges they face as defenders. \nAmnesty International recommends incorporating age disaggregated data on the lived experiences of child and young HRDs in all future reports or interventions by the Special Rapporteur. \nAmnesty International recommends creating online and face-to-face safe spaces for child and young HRDs and their child and youth-led organizations to actively engage with the Special and other human rights mechanisms.",
      "Amnesty International is known for its advocacy work on behalf of human rights defenders around the world. The organization often provides detailed reports and recommendations to the Special Rapporteur on Human Rights Defenders, highlighting specific cases of abuse and calling for action to protect those at risk."
    ],
    [
      "In addition to children, parents, teachers, and caregivers are also key target audiences for Amnesty International's books on child rights. These adults play a crucial role in guiding and supporting children as they learn about their rights and responsibilities. By reading and discussing these books together, families and educators can help instill values of equality, respect, and compassion in the next generation.",
      "Amnesty International's books on child rights are designed to educate and empower young readers about their rights and the importance of standing up for justice. The colorful illustrations and engaging storytelling make these books accessible to children of various ages and backgrounds, sparking their curiosity and empathy for others.",
      "Amnesty International has therefore created two simple books on child rights and how to claim them for self and others: (1) \u2018Know Your Rights and Claim Them: A Guide for Youth\u2019, by Amnesty International, Angelina Jolie, Geraldine van Bueren (Andersen Press 2021); (2) \u2018These Rights Are Your Rights: An empowering guide for children everywhere\u2019, by Nicky Parker at Amnesty International (Andersen Press, 2024).\nThe objectives of the two books are to build children\u2019s and young people\u2019s understanding of their rights and give them the awareness and tools they need to take action."
    ],
    [
      "The right to truth is a fundamental human right that seeks to uncover the full extent of past human rights violations and ensure accountability for those responsible. This right includes access to official records, archives, and other sources of information that shed light on historical injustices and atrocities.",
      "In many countries, the pursuit of truth and justice for past human rights violations is a complex and often contentious process. Governments, institutions, and individuals may resist efforts to uncover the truth, leading to challenges in achieving transparency and accountability. The right to truth is essential for promoting reconciliation, healing, and preventing future abuses.",
      "26. The Act raises serious questions about its compatibility with the right to truth.\n27. At an individual level, victims and their families possess an inalienable and non-derogable right to know the truth regarding the circumstances and reasons behind human rights violations, including the identities of the perpetrators and, in cases of death or enforced disappearance, the fate of the victims.\nIn particular, the right to know the fate and whereabouts of \u2018disappeared\u2019 relatives has been confirmed in the jurisprudence of international and regional human rights bodies, as well as of national courts."
    ],
    [
      "In many cases, the identities of perpetrators of human rights violations are shielded from public knowledge, either due to political reasons or lack of evidence. This lack of transparency can hinder efforts to seek justice for victims and hold those responsible accountable for their actions. The right to know the fate of victims is equally important, as it allows families and communities to grieve, seek closure, and work towards healing and reconciliation.",
      "- The victims of gross human rights violations and their families, as well as members of society generally, have the right to know the whole truth about past human rights violations.\n- The right to truth is engaged by the violation of the rights to access to justice, remedy, and information.\n- Victims and their families possess an inalienable and non-derogable right to know the truth regarding the circumstances and reasons behind human rights violations, including the identities of the perpetrators and the fate of the victims.\n- The right to know the fate and whereabouts of 'disappeared' relatives has been confirmed in the jurisprudence of international and regional human rights bodies, as well as of national courts.",
      "The concept of universal human rights has evolved over centuries, with various international declarations and treaties outlining the fundamental rights that all individuals are entitled to. These rights are considered inherent to all human beings, regardless of nationality, ethnicity, or any other distinguishing factor. The idea that everyone should be fully informed about human rights violations stems from the belief that transparency and accountability are essential for upholding these rights and preventing future abuses."
    ],
    [
      "Article 207.3 of the Russian Criminal Code pertains to the illegal acquisition, transfer, sale, storage, transportation, or carrying of firearms, their main parts, ammunition, explosives, and explosive devices. This law aims to regulate the possession and use of dangerous weapons to maintain public safety and order.",
      "- As long as their statements are contrary to the official position of the Russian authorities, they can be regarded by the prosecution and courts as \"false\" and individuals are found guilty under Article 207.3.\n- Official information regarding Russia's full-scale invasion of Ukraine has been riddled with false and deliberately misleading messages and claims.\n- Debunking such information and providing independent analysis of the situation has been expressly criminalized.\n- Accordingly, Article 207.3 acts as a tool of wartime censorship.\n- Prosecution for \"dissemination of knowingly false information\" under Article 207.3 contributes to impunity for violations of the laws and customs of war.\n- The claim that Roman Ivanov's actions were \"in violation of constitutional order\" do not stand scrutiny either, as Article 207.3 of the Criminal Code is contrary to the provisions of the Russian Constitution itself.\n- Article 2 of the Russian Constitution proclaims human rights and freedoms as the highest value and their defense as the duty of the state.\n- Article 17 further declares that human rights and freedoms are guaranteed \"in accordance with the recognized principles and norms of international law and this Constitution.\"\n- Article 29 guarantees freedom of thought and speech, freedom to seek, receive, share, produce and disseminate information, and media freedom.\n- At the same time, it prohibits censorship.",
      "In addition to the legal implications, individuals found guilty under Article 207.3 may face severe penalties, including fines, imprisonment, or other restrictions on their rights and freedoms. The enforcement of this law is crucial in preventing criminal activities involving firearms and explosives in Russia."
    ],
    [
      "- As long as their statements are contrary to the official position of the Russian authorities, they can be regarded by the prosecution and courts as \u201cfalse\u201d and individuals are found guilty under Article 207.3.\n- Official information regarding Russia\u2019s full-scale invasion of Ukraine has been riddled with false and deliberately misleading messages and claims.\n- Debunking such information and providing independent analysis of the situation has been expressly criminalized.\n- Accordingly, Article 207.3 acts as a tool of wartime censorship.\n- Prosecution for \"dissemination of knowingly false information\" under Article 207.3 contributes to impunity for violations of the laws and customs of war.\n- The claim that Roman Ivanov\u2019s actions were \"in violation of constitutional order\" do not stand scrutiny either, as Article 207.3 of the Criminal Code is contrary to the provisions of the Russian Constitution itself.\n- Article 2 of the Russian Constitution proclaims human rights and freedoms as the highest value and their defense as the duty of the state.\n- Article 29 guarantees freedom of thought and speech, freedom to seek, receive, share, produce and disseminate information and media freedom.\n- At the same time, it prohibits censorship.",
      "In legal proceedings, the prosecution may consider statements contrary to the official position as 'false' under Article 207.3 when they are deemed to be intentionally misleading or deceptive. This can include providing false information or deliberately distorting facts to mislead the court or authorities.",
      "The determination of whether statements are considered 'false' under Article 207.3 is based on the intent behind the statements and the impact they have on the legal proceedings. If the prosecution believes that the statements were made with the purpose of obstructing justice or undermining the truth, they may be classified as 'false' and subject to legal consequences."
    ],
    [
      "The economic challenges facing Nicaragua have also played a role in the decline of independent civil society organizations. Limited funding opportunities, coupled with a shrinking space for civic engagement, have made it difficult for these organizations to sustain their operations and carry out their missions effectively.",
      "- \"arrests and harassment of human rights defenders, restrictive NGO laws and violent repression of protests have been decimating independent civil society organizations for years.\"\n- \"The closure of civil society organizations and our rural community centers, which for more than 40 years have worked in defense of SRR and human rights in general.\"\n- \"The expropriation of their belongings and premises.\"\n- \"The criminalization of social organizing and mobilization and of freedom of expression.\"\n- \"The implementation of repressive laws that breach the human rights of the population to suit the wishes of the regime.\"\n- \"The constant threats of arrest and detention of those who protest and the restrictions on social media.\"\n- \"The silence imposed through violence and repression.\"\n- \"As a result, the activities of our feminist community organization are severely limited right now.\"",
      "Nicaragua's political landscape has undergone significant changes in recent years, leading to increased government control and restrictions on independent civil society organizations. The government's crackdown on dissent and opposition has resulted in the closure of many NGOs and civil society groups, limiting their ability to operate freely and advocate for social change."
    ],
    [
      "Wetlands designated as Ramsar sites must meet specific criteria outlined by the Ramsar Convention, an international treaty aimed at conserving wetlands and their resources. These criteria include the presence of rare or unique ecosystems, the support of a diverse range of plant and animal species, and the provision of essential services such as water purification and flood control.",
      "The Ramsar Convention, signed in 1971 in Ramsar, Iran, has designated over 2,000 wetlands worldwide as Ramsar sites. These sites are recognized for their ecological importance and are protected under international law to ensure their conservation for future generations.",
      "- \"Ramsar sites are designated when they fulfil the criteria for identifying wetlands of international importance.\"\n- \"These criteria were established under the Convention on Wetlands, an intergovernmental agreement containing a framework for the conservation and wise use of wetlands and their resources.\""
    ],
    [
      "The city of Kunming, located in the Yunnan province of China, is known for its stunning natural landscapes and diverse ecosystems. It served as the perfect backdrop for COP15, allowing delegates to immerse themselves in the beauty of nature while discussing crucial environmental issues.",
      "- These include the agreement known as 30x30, adopted at the UN Conference on Biological Diversity (COP15) held in Montreal, Canada, in late 2022.\n- Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights.",
      "COP15, also known as the 15th meeting of the Conference of the Parties to the Convention on Biological Diversity, was held in Kunming, China in 2022. The conference aimed to address the global biodiversity crisis and set ambitious targets for conservation and sustainable development."
    ],
    [
      "The 30x30 agreement aims to protect 30% of the world's land and oceans by the year 2030. This ambitious goal is seen as crucial in preserving biodiversity and combating the effects of climate change. By setting aside these areas as protected zones, it is hoped that ecosystems can thrive and species can be safeguarded for future generations.",
      "The 30x30 agreement has garnered support from various governments, environmental organizations, and indigenous groups around the world. It represents a global effort to address the urgent need for conservation and sustainable land management practices. Through this agreement, countries are committing to prioritize the protection of natural habitats and the promotion of biodiversity.",
      "- These include the agreement known as 30x30, adopted at the UN Conference on Biological Diversity (COP15) held in Montreal, Canada, in late 2022, which commits Parties to designate 30% of the world's land and sea masses as protected areas for biodiversity conservation by 2030.\n- Protecting and restoring these ecosystems is one of the most efficient, equitable and cost-effective mechanisms to capture and store carbon without compromising human rights.\n- However, the focus of the agreement should not be limited to the amount of area it covers, but rather to how it is managed, who selects the areas, and what biodiversity exists in them.\n- Indigenous Peoples and local communities have a key role to play here.\n- Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights."
    ],
    [
      "The lack of explicit recognition of Indigenous Peoples' lands and territories as a distinct category of protected area at COP15 highlights the ongoing challenges in balancing conservation efforts with respect for Indigenous rights and sovereignty. This issue has sparked debates about the need for more inclusive and equitable decision-making processes in global conservation initiatives.",
      "The issue of recognizing Indigenous Peoples' lands and territories as a distinct category of protected area at COP15 has been a point of contention among various stakeholders. While some argue that Indigenous Peoples' traditional knowledge and practices are essential for effective conservation efforts, others believe that a one-size-fits-all approach is more practical and efficient in achieving conservation goals.",
      "Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights."
    ],
    [
      "- Abortion criminalization contributes to stigma around abortion and particularly on those who need, provide or assist with abortion services.\n- Criminalization, lack of information, disinformation, and stigma have severe and irreversible effects, particularly on marginalized individuals.\n- Girls and young women are kept in the dark about their rights and often forced to bring to term pregnancies resulting from sexual violence.\n- Marginalized individuals, including those living in poverty, historically discriminated against, Indigenous and Afro-descendent women, migrants, and refugees, are disproportionately affected by abortion criminalization.\n- Criminalization of abortion is the biggest contributing factor to the estimated 35 million unsafe abortions happening every year, increasing maternal mortality and morbidity.\n- Criminalizing abortion undermines access to health services and leads to increased rates of preventable maternal mortality and morbidity.\n- Abortion criminalization forces women, girls, and all pregnant individuals to attempt unsafe clandestine abortion methods, placing their life and health at risk.\n- Abortion laws in Nigeria are restrictive, making abortion unsafe and difficult to access safe abortion care.",
      "In countries where abortion is illegal or highly restricted, marginalized individuals, such as low-income women, young girls, and immigrants, are disproportionately affected. They may resort to unsafe and clandestine methods to terminate a pregnancy, putting their lives at risk. The criminalization of abortion can further perpetuate cycles of poverty, inequality, and discrimination, as marginalized individuals are denied the autonomy to make decisions about their own bodies and futures.",
      "The debate over abortion has been a contentious issue for decades, with strong opinions on both sides of the argument. The criminalization of abortion can have far-reaching consequences for marginalized individuals, particularly those who may not have access to safe and legal options for terminating a pregnancy. This can lead to increased health risks, financial burdens, and emotional distress for those who are already facing systemic barriers to healthcare and support services."
    ],
    [
      "Social media companies play a significant role in shaping public discourse and disseminating information on a wide range of topics, including sexual and reproductive health. As such, they have a responsibility to ensure that the information shared on their platforms is accurate, reliable, and evidence-based. This includes taking steps to combat misinformation and disinformation that can harm individuals' health and well-being.",
      "Social media companies involved in facilitating and moderating online content need to invest adequate resources in human oversight of artificial intelligence-driven content moderation systems to ensure all users can equally exercise their rights online, regardless of language and political views and ensure that they can access accurate sexual and reproductive health-related information, including on the right to abortion. They should also uphold their human rights responsibilities by engaging in human rights due diligence, including to address risks and abuses arising from their business model.",
      "In recent years, there has been growing concern about the spread of false or misleading information related to sexual and reproductive health on social media platforms. This has led to calls for greater accountability and transparency from these companies in terms of monitoring and regulating the content that is shared on their platforms. By taking proactive measures to promote accurate information and combat misinformation, social media companies can help to empower individuals to make informed decisions about their sexual and reproductive health."
    ],
    [
      "Companies, including social media companies, have a responsibility to respect all human rights wherever they operate in the world.\nSocial media companies involved in facilitating and moderating online content need to invest adequate resources in human oversight of artificial intelligence-driven content moderation systems to ensure all users can equally exercise their rights online, regardless of language and political views.\nThey should uphold their human rights responsibilities by engaging in human rights due diligence, including to address risks and abuses arising from their business model.\nThey should undertake proactive measures in educating users and raising awareness about security and privacy features on their platforms that will help WHRDs create a safer and less toxic online experience.",
      "Social media companies have faced increasing scrutiny over their handling of user data and privacy concerns. The Cambridge Analytica scandal, in which Facebook data was used to influence political campaigns, highlighted the need for greater transparency and accountability in the industry. As a result, companies like Facebook and Twitter have implemented stricter policies and measures to protect users' rights and prevent misuse of their platforms.",
      "The issue of online censorship and freedom of speech has also been a contentious topic for social media companies. Balancing the need to protect users from harmful content while also upholding principles of free expression is a delicate task. Companies must navigate complex legal and ethical considerations when deciding what content to allow or remove, taking into account the diverse perspectives and values of their global user base."
    ],
    [
      "The kafala system in Qatar, which ties a migrant worker's legal status to their employer, has been identified as a key factor contributing to the labor abuses documented by Amnesty International. This system gives employers significant control over their workers, making it difficult for them to leave abusive situations or seek justice for violations of their rights.",
      "Amnesty International's report on labor abuses in Qatar highlighted the widespread exploitation of migrant workers, including long working hours, low wages, and poor living conditions. These violations of human rights have raised concerns globally and put pressure on the Qatari government to reform its labor laws and practices.",
      "During the tournament, Amnesty International documented how one company providing guards to an international hotel chain in Doha was permitting workers only one day off each month, threatening salary cuts if they took more rest time, failing to provide pay slips and housing them in dirty and overcrowded accommodation with six people per room in bunkbeds.\nUntil 2020, Qatar\u2019s inherently abusive kafala sponsorship system imposed tight restrictions on migrant workers\u2019 freedom of movement, prohibiting them from leaving the country or changing jobs without the permission of their employer.\nBetween 2018 and 2020, the government took important steps towards tackling two central pillars of this system by repealing for most migrant workers the requirement to obtain from their employer an 'exit permit\u2019 to leave the country, and a \u2018no-objection certificate\u2019 (NOC) to change jobs.\nSuch reliance means abusive employers can \u2013 and still do \u2013 depend on an array of tools to control their workforce. This includes cancelling or refraining from renewing workers\u2019 residence permits, or falsely reporting employees as having \u201cabsconded\u201d from their job (when they could be trying to escape abuse) - all of which can lead to workers being arrested and deported.\nOther barriers to workers changing jobs freely have emerged over the last few years, limiting the impact of the reforms and maintaining the status quo. These include the unwritten \u2013 but often spoken \u2013 need for workers to secure \u201crelease papers\u201d, a resignation letter, or any equivalent of an NOC, from their current employers in order to successfully move jobs, and the malicious use by employers of the Labour Law\u2019s non-compete clause to effectively ban workers from changing jobs under the guise that they are going to work for direct competitors."
    ],
    [
      "Qatar's efforts to improve the rights and working conditions of migrant workers have been widely praised by international organizations and human rights advocates. The government's decision to gradually repeal restrictions and implement reforms has been seen as a positive step towards addressing long-standing issues in the country's labor system.",
      "Between 2018 and 2020, the government took important steps towards tackling two central pillars of this system by repealing for most migrant workers the requirement to obtain from their employer an 'exit permit\u2019 to leave the country, and a \u2018no -objection certificate\u2019 (NOC) to change jobs.\nOther barriers to workers changing jobs freely have emerged over the last few years, limiting the impact of the reforms and maintaining the status quo.\nThese include the unwritten \u2013 but often spoken \u2013 need for workers to secure \u201crelease papers\u201d, a resignation letter, or any equivalent of an NOC, from their current employers in order to successfully move jobs.",
      "The changes in Qatar's labor laws have also been linked to the country's preparations for hosting the FIFA World Cup in 2022. The government's commitment to ensuring fair treatment and protection for migrant workers has been a key focus in the lead-up to the tournament, with various initiatives and policies being introduced to uphold these principles."
    ]
  ],
  "ground_truth": [
    "The global implications of the USA Supreme Court ruling on abortion are significant. The ruling has led to limited or no access to abortion for one in three women and girls of reproductive age in states where abortion access is restricted. These states also have weaker maternal health support, higher maternal death rates, and higher child poverty rates. Additionally, the ruling has had an impact beyond national borders due to the USA's geopolitical and cultural influence globally. Organizations and activists worldwide are concerned that the ruling may inspire anti-abortion legislative and policy attacks in other countries. The ruling has also hindered progressive law reform and the implementation of abortion guidelines in certain African countries. Furthermore, the ruling has created a chilling effect in international policy spaces, empowering anti-abortion actors to undermine human rights protections.",
    "According to the Carbon Majors database, the main contributors to GHG emissions and their role in global warming are fossil fuel companies. These companies, both state-owned and private, have produced almost a trillion tons of GHG emissions in 150 years. The database shows that 100 existing fossil fuel companies, along with eight that no longer exist, are responsible for 71% of all GHG emissions since 1988. In the Americas, the private companies that have contributed the most emissions are ExxonMobil, Chevron, and Peabody, all from the United States. Among state-owned companies in the Americas, the largest emitter is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A. It is important to note that while people with fewer resources, particularly from countries in the global South, do not significantly contribute to climate change, they are the ones most affected by its impacts. Approximately half of the global population lives in areas that are \"very vulnerable\" to climate change, and it is people with limited development opportunities who face the greatest risks. This unequal impact disproportionately affects the human rights of those with fewer resources and greater vulnerability in the context of climate change in the global South. Additionally, between 2010 and 2020, human mortality due to climate disasters was 15 times higher in vulnerable regions and populations.",
    "The largest private companies in the Americas that are the largest GHG emitters according to the Carbon Majors database are ExxonMobil, Chevron, and Peabody.",
    "Amnesty International urged its supporters to send appeals for the defenders' freedom to Nigerian authorities and later to send letters of outrage.",
    "The recommendations made by Amnesty International to the Special Rapporteur on Human Rights Defenders include embedding a focus on child and young HRDs in future work, raising awareness about the differences and challenges they face, incorporating age disaggregated data in reports, and creating safe spaces for engagement.",
    "The target audience of the two books created by Amnesty International on child rights are children and young people.",
    "The right that guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations, is the right to know the truth.",
    "The victims of gross human rights violations and their families, as well as members of society generally, have the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims.",
    "Individuals can be found guilty under Article 207.3 of the Russian Criminal Code if their statements are contrary to the official position of the Russian authorities.",
    "The prosecution considers statements contrary to the official position as 'false' under Article 207.3 when they are in opposition to the official position of the Russian authorities.",
    "The factors that have contributed to the decline of independent civil society organizations in Nicaragua include arrests and harassment of human rights defenders, restrictive NGO laws, violent repression of protests, closure of civil society organizations and community centers, expropriation of belongings and premises, criminalization of social organizing and mobilization, restrictions on freedom of expression, implementation of repressive laws, constant threats of arrest and detention, restrictions on social media, and the imposition of silence through violence and repression.",
    "The conditions that designate wetlands as Ramsar sites are when they fulfill the criteria for identifying wetlands of international importance, as established under the Convention on Wetlands.",
    "COP15 was held in Montreal, Canada in 2022.",
    "The purpose of the agreement known as 30x30 is to designate 30% of the world's land and sea masses as protected areas for biodiversity conservation by 2030.",
    "The States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area at COP15.",
    "The consequences of criminalizing abortion for marginalized individuals include increased stigma, lack of information, and disinformation. This can have severe and irreversible effects on these individuals. Girls and young women may be forced to carry pregnancies resulting from sexual violence due to a lack of knowledge about their rights. Marginalized individuals, such as those living in poverty, historically discriminated against, Indigenous and Afro-descendent women, migrants, and refugees, are disproportionately affected by abortion criminalization. The criminalization of abortion is a major factor contributing to the high number of unsafe abortions, which leads to increased maternal mortality and morbidity. Access to health services is undermined, resulting in preventable maternal deaths and complications. Marginalized individuals are forced to resort to unsafe clandestine abortion methods, putting their lives and health at risk. In Nigeria, restrictive abortion laws make it difficult to access safe abortion care.",
    "Social media companies should have the responsibility to invest in human oversight of their content moderation systems to ensure equal access to accurate sexual and reproductive health information. They should also engage in human rights due diligence to address risks and abuses related to their business model.",
    "Social media companies play a role in protecting users' rights online, regardless of their language and political views, by investing in human oversight of content moderation systems, engaging in human rights due diligence, and educating users about security and privacy features.",
    "Amnesty International documented labor abuses in Qatar, including workers being permitted only one day off each month, threats of salary cuts for taking more rest time, failure to provide pay slips, and overcrowded and dirty living conditions. These labor abuses relate to the kafala system because the kafala system imposes tight restrictions on migrant workers' freedom of movement and ability to change jobs without their employer's permission. This system allows abusive employers to control their workforce by canceling residence permits, falsely reporting employees as absconding, and using non-compete clauses to prevent workers from changing jobs.",
    "The government of Qatar started repealing restrictions on migrant workers between 2018 and 2020."
  ]
}

Simple example for POC

import json
from ragas import EvaluationDataset, SingleTurnSample, evaluate
from ragas.metrics import LLMContextRecall, FactualCorrectness, Faithfulness
from ragas.llms import LangchainLLMWrapper
from langchain.chat_models import ChatOpenAI
import pandas as pd

Path to your JSON file

json_file_path = “your_json_file.json”

Open the JSON file and load the data

with open(json_file_path, “r”) as f:
data = json.load(f)

Extract questions, answers, and contexts from the JSON data

questions = data[“question”]
answers = data[“answer”]
contexts = data.get(“contexts”, []) # Handle optional contexts

Create samples for evaluation dataset

samples = []
for i in range(len(questions)):
sample = SingleTurnSample(
user_input=questions[i],
reference=answers[i],
response=None, # We don’t have a model-generated response for now
retrieved_contexts=contexts[i] if i < len(contexts) else []
)
samples.append(sample)

Create evaluation dataset

eval_dataset = EvaluationDataset(samples=samples)

Define your LLM using Langchain’s OpenAI wrapper for GPT-4

evaluator_llm = LangchainLLMWrapper(ChatOpenAI(model=”gpt-4″))

Define metrics to evaluate

metrics = [LLMContextRecall(), FactualCorrectness(), Faithfulness()]

Evaluate the LLM on the dataset

results = evaluate(dataset=eval_dataset, metrics=metrics, llm=evaluator_llm)

Display results in pandas DataFrame (if pandas is installed)

if pd is not None:
df = results.to_pandas()
print(df.head())

———————————————–

Retrieval component using FAISS

  1. import faiss
  2. import numpy as np# Sample documents (replace with your corpus)
  3. documents = [ “The Eiffel Tower is in Paris.”, “The Great Wall of China is visible from space.”, “Python is a programming language.”]# Convert documents into vector embeddings (for simplicity, use random vectors here)document_embeddings = np.random.random((len(documents), 512)).astype(‘float32’)# Set up FAISS index for retrievalindex = faiss.IndexFlatL2(512)index.add(document_embeddings)# Function to retrieve documentsdef retrieve_documents(query_embedding, top_k=2): _, retrieved_indices = index.search(query_embedding, top_k) return [documents[idx] for idx in retrieved_indices[0]]
  4. Generate component
  5. import openai
  6. # Set up your OpenAI API key
  7. openai.api_key = ‘your-openai-api-key’# Function to generate responses using OpenAI’s GPT modeldef generate_response(prompt): response = openai.Completion.create( engine=”text-davinci-003″, prompt=prompt, max_tokens=150 ) return response[‘choices’][0][‘text’]
  8. 3. RAG pipeline setup
  9. def rag_pipeline(query): # Convert query into a vector embedding (for simplicity, use random vectors) query_embedding = np.random.random((1, 512)).astype(‘float32’) # Retrieve relevant documents retrieved_docs = retrieve_documents(query_embedding) # Combine retrieved docs into a prompt for the generative model prompt = “Based on the following information:\n” + “\n”.join(retrieved_docs) + “\nAnswer the question: ” + query # Generate response using OpenAI response = generate_response(prompt) return response
  10. 4. Integrate Ragas testing framework
  11. import ragas# Sample queries and expected responsestest_data = [ { “query”: “Where is the Eiffel Tower?”, “expected”: “The Eiffel Tower is in Paris.” }, { “query”: “What is Python?”, “expected”: “Python is a programming language.” }]# Running tests with RAGASfor test_case in test_data: query = test_case[‘query’] expected_response = test_case[‘expected’] # Get model’s response from the RAG pipeline generated_response = rag_pipeline(query) # Use RAGAS evaluation metrics to assess the response relevance = ragas.evaluate_relevance(generated_response, expected_response) coherence = ragas.evaluate_coherence(generated_response) # Print the evaluation results print(f”Query: {query}”) print(f”Generated Response: {generated_response}”) print(f”Expected Response: {expected_response}”) print(f”Relevance Score: {relevance}”) print(f”Coherence Score: {coherence}”) print(“———“)
  12. 5. Ragas test results
  13. Query: Where is the Eiffel Tower?Generated Response: The Eiffel Tower is located in Paris, France.Expected Response: The Eiffel Tower is in Paris.Relevance Score: 0.95Coherence Score: 0.90———Query: What is Python?Generated Response: Python is a programming language used for many purposes, including web development, automation, and data analysis.Expected Response: Python is a programming language.Relevance Score: 0.93Coherence Score: 0.92———

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();
    }
}

}

Java excel reader

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelUpdater {

    public static void main(String[] args) {

        String excelFilePath = “path/to/your/excel-file.xlsx”; // Change to your Excel file path

        try (FileInputStream fis = new FileInputStream(excelFilePath);

             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheet(“Sheet1”);

            // Loop through all rows in column A

            for (int i = 0; i < 100; i++) {

                Row row = sheet.getRow(i);

                if (row != null) {

                    Cell cellA = row.getCell(0); // Column A

                    Cell cellB = row.getCell(1); // Column B

                    if (cellA != null && cellB != null) {

                        // Update Column A to match Column B

                        cellA.setCellValue(cellB.getStringCellValue());

                    }

                }

            }

            // Write the changes back to the file

            try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {

                workbook.write(fos);

            }

            System.out.println(“Excel file updated successfully!”);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

SpringBoot examples

Git access logic

package com.web.client.demo.controller;

import com.web.client.demo.model.WorkflowRequest;
import com.web.client.demo.service.GitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**

  • Controller to handle Git and Gradle operations.
    */
    @RestController
    @RequestMapping(“/api/get”)
    public class GitController { private final GitService gitService; @Autowired
    public GitController(GitService gitService) {
    this.gitService = gitService;
    } /**
    • Endpoint to trigger the git clone/pull and gradle clean test workflow.
      *
    • @param request The request containing Git repository URL and branch.
    • @return The combined output of Git and Gradle commands.
      */
      @PostMapping(“/execute-workflow”)
      public ResponseEntity executeWorkflow(@RequestBody WorkflowRequest request) {
      try {
      String gitUrl = request.getGitUrl();
      String branch = request.getBranch(); // Define target directory (e.g., repositories will be cloned into a 'repos' folder in the current directory) String targetDir = "repos/" + extractRepoName(gitUrl); // Define project sub-directory (e.g., 'quality/services') String projectSubDir = "quality/services"; String output = gitService.executeWorkflow(gitUrl, branch, targetDir, projectSubDir); return ResponseEntity.ok(output); } catch (RuntimeException e) {
      return ResponseEntity.status(500).body(“Error: ” + e.getMessage());
      }
      }
    /**
    • Extracts the repository name from the Git URL.
      *
    • @param gitUrl The Git repository URL.
    • @return The repository name.
      */
      private String extractRepoName(String gitUrl) {
      if (gitUrl == null || gitUrl.isEmpty()) {
      throw new IllegalArgumentException(“Git URL cannot be null or empty.”);
      }
      // Remove trailing .git if present
      gitUrl = gitUrl.endsWith(“.git”) ? gitUrl.substring(0, gitUrl.length() – 4) : gitUrl;
      // Extract repository name
      return gitUrl.substring(gitUrl.lastIndexOf(‘/’) + 1);
      }
      }

package com.web.client.demo.model;

import lombok.Data;

@Data
public class WorkflowRequest {
private String gitUrl;
private String branch;
}

package com.web.client.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class GitService {

private static final Logger logger = LoggerFactory.getLogger(GitService.class);

/**
 * Executes a shell command in a specific directory.
 *
 * @param command    The command to execute.
 * @param workingDir The directory in which to execute the command.
 * @return The output of the command.
 * @throws IOException          If an I/O error occurs.
 * @throws InterruptedException If the process is interrupted.
 */
private String executeCommand(String[] command, File workingDir) throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(workingDir);
    processBuilder.redirectErrorStream(true); // Merge error and output streams

    logger.info("Executing command: {}", String.join(" ", command));
    Process process = processBuilder.start();

    // Read the output
    StringBuilder output = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
            logger.info(line);
        }
    }

    // Wait for the process to complete
    int exitCode = process.waitFor();
    logger.info("Command exited with code: {}", exitCode);

    if (exitCode != 0) {
        throw new RuntimeException("Command " + String.join(" ", command) + " failed with exit code " + exitCode);
    }

    return output.toString();
}

/**
 * Clones the Git repository if it doesn't exist, otherwise performs a git pull.
 *
 * @param gitUrl     The URL of the Git repository.
 * @param branch     The branch to clone or pull.
 * @param targetDir  The directory where the repository should be cloned.
 * @return The output of the git clone or git pull command.
 */
public String cloneOrPullRepo(String gitUrl, String branch, String targetDir) {
    File repoDir = new File(targetDir);

    try {
        if (repoDir.exists()) {
            logger.info("Repository already exists. Performing git pull.");
            String[] pullCommand = {"git", "pull"};
            return executeCommand(pullCommand, repoDir);
        } else {
            logger.info("Cloning repository.");
            String[] cloneCommand = {"git", "clone", "-b", branch, gitUrl, targetDir};
            return executeCommand(cloneCommand, repoDir.getParentFile());
        }
    } catch (IOException | InterruptedException e) {
        logger.error("Error during git operation", e);
        throw new RuntimeException("Git operation failed: " + e.getMessage(), e);
    }
}

/**
 * Executes the Gradle command in the specified directory.
 *
 * @param projectDir The directory where the Gradle command should be executed.
 * @return The output of the Gradle command.
 */
public String runGradleCleanTest(String projectDir) {
    File gradleDir = new File(projectDir);

    try {
        logger.info("Running Gradle clean test.");
        String[] gradleCommand = {"./gradlew", "clean", "test", "--info"};
        return executeCommand(gradleCommand, gradleDir);
    } catch (IOException | InterruptedException e) {
        logger.error("Error during Gradle operation", e);
        throw new RuntimeException("Gradle operation failed: " + e.getMessage(), e);
    }
}

/**
 * Executes the full workflow: clone/pull Git repository and run Gradle tests.
 *
 * @param gitUrl      The URL of the Git repository.
 * @param branch      The branch to clone or pull.
 * @param targetDir   The directory where the repository should be cloned.
 * @param projectSubDir The sub-directory within the repository to run Gradle commands.
 * @return The combined output of Git and Gradle commands.
 */
public String executeWorkflow(String gitUrl, String branch, String targetDir, String projectSubDir) {
    StringBuilder combinedOutput = new StringBuilder();

    // Step 1: Clone or Pull Git Repository
    combinedOutput.append("=== Git Operation ===\n");
    String gitOutput = cloneOrPullRepo(gitUrl, branch, targetDir);
    combinedOutput.append(gitOutput).append("\n");

    // Step 2: Run Gradle Clean Test
    combinedOutput.append("=== Gradle Operation ===\n");
    String gradleOutput = runGradleCleanTest(targetDir + File.separator + projectSubDir);
    combinedOutput.append(gradleOutput).append("\n");

    return combinedOutput.toString();
}

}

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()

What is Cucumber dependency injection in Selenium Projects?

You would notice Cucumber Selenium project has step definitions and hooks classes. Cucumber options glueing these step definitions and hooks to generate class instances using dependency injections before each Scenario

What is dependency injection?
Dependency injection is a design pattern where an object or function can receive other object or function.
In java you would notice constructor injection and setter injection. Spring projects are example using dependency

How to setup kubernetes on windows WSL

How do I setup Kubernetes and run kubectl commands from windows machine

WSL(Windows subsystems linux) can be leveraged when you want to run kubectl commands from windows machine. Steps as below,

  1. Enable WSL with Kalilinux
  2. Install Windows Docker
  3. Create docker hub account and link account to Windows docker
  4. In Windows docker, go to settings
  5. Then enable Kubernetes
  6. Setup Persistent volume claim (pvc) by creating a yaml configuration for this.
  7. Run kubectl apply to yaml file
  8. When creating pods, or does kubectl deployment, make sure volume mounting done based on pvc
  9. Verify pod status by accessing commandline to docker containet directories

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

What is Java collection framework

Collection framework in java is set of interfaces and classes that forms a collection of data Objects

Set, List, and Queus are interfaces helps to build collection. Map is really not a collection as it is key/value pairs of data.

Java collections help us to create group of objects and it iterates in data container, helping developer to do data operations like add, modify, remove etc.

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”