Quantcast
Channel: Edureka
Viewing all 1753 articles
Browse latest View live

What are Comments in Python and how to use them?

$
0
0

Have you ever asked any programmer to explain the code he wrote a year ago? Or have you ever tried reading your own previously written code? It would become very time consuming and tiring if you had to reanalyze every block of code from scratch! The best thing to do is, add a comment.  Comments are not something just to increase the lines of your code but it is the best way to make your code meaningful. Here is a complete guide to help you understand all about Comments in Python.

Before moving ahead, let’s just have a quick walk through all the topics that have been covered in this article –

What are Comments?

A comment, in general, is an expression of one’s ideas. In programming, comments are programmer-coherent statements, that describe what a block of code means. They get very useful when you are writing large codes. It’s practically inhuman to remember the names of every variable when you have a hundred-page program or so. Therefore, making use of comments will make it very easy for you, or someone else to read as well as modify the code.

Comments are very important, but you will need to know how to make use of them which is exactly what will be discussed in the following topic. 

How to make use of Comments?

Comments can be included anywhere which means inline as well. The best practice is to write relevant comments as and how you proceed with your code.  

 Here are some key points that will help you while commenting your code:

  • Comments need to be short and relevant
  • They are to be specific to the block of code they are included with
  • Make sure to use decent language, as using foul language is unethical
  • Don’t comment self-explanatory lines

Now that you know the importance of comments, let’s move ahead and see how to write Comments in Python.

How to write Comments in Python?

Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes), which are described further in this article.

Example:

#Comments in Python start like this
print("Comments in Python start with a #")


Output: Comments in Python start with a #

As you can see in the above output, the print statement is executed whereas the comment statement is not present in the output.

 If you have more than one comment line, all of them need to be prefixed by a #.

Example:

#Comments in Python
#start with this character
print("Comments in Python")

Output: Comments in Python

The above output shows that all lines prefixed with a # character are not returned in the output.

Moving forward let’s see how comments are interpreted and why they never appear in the output.

How does Python interpret comments?

When the interpreter encounters a # symbol anywhere, (except inside a string because a # within a string just means #), it omits everything that is present after it until the end of that line. The # tag actually tells the interpreter to stop reading anything present after it.

Types of Comments

Comments in Python Types

Comments can either be

  • Single-line or
  • Multi-line

Single-line Comments:

They can appear either in an individual line or inline with some other code.

Example:
#multiplying two variables          (this line starts with a #, hence will be ignored till line ends)
a=1
b=2
c=a*b
print(c)     # printing result      (inline comment, whatever is present after # will be ignored)
Output: 2

Multi-line Comments:

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. If you don’t do so, you will encounter an error.

Example:

#adding 2 variables
#pinting the result in a new variable
a=2
b=3
c=a+b
print(c)

Output: 5

The above output shows that the first two program lines being prefixed with a # character have been omitted and the rest of the program is executed returning its respective output.

You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.

If you want to remove # from multiple lines you can do the same thing and use the backspace key just once and all the selected # characters will be removed.

However, these multi-line comments look very unpleasant when you’re commenting documentation. The following topic will introduce you to a solution to this.

Docstring Comments:

Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.

They are used particularly when you need to affiliate some documentation related to a class or a function, etc.

Example:

"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)

Output:  2.0

As you can see, the output does not contain the docstring, therefore, it has been omitted as it appears before the code has started.

But if you execute just a docstring without the code below, as shown above, the output will be the string itself.

Example:

"""
Using docstring as a comment.
This code divides 2 numbers
"""

Output: ‘\nUsing docstring as a comment.\nThis code divides 2 numbers\n’

In the above output, the docstring has been printed since it is not followed by any code.

Now, in case it would be present after the code was written, the docstring will still be printed after the result.

Example:

x=8
y=4
z=x/y
print(z)
"""
Using docstring as a comment.
This code divides 2 numbers
"""

 

Output: 

2.0
'\nUsing docstring as a comment.\nThis code divides 2 numbers\n'

As you can see, the docstring has been printed after the output. So, therefore, as mentioned above, docstring behaves differently at different places depending on where it appears in the code. This brings us to the end of this article. I hope you have enjoyed learning about Comments in Python. Make sure you practice as much as possible and revert your experience.  

Got a question for us? Please mention it in the comments section of this “Comments in Python” blog and we will get back to you as soon as possible.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access.  

The post What are Comments in Python and how to use them? appeared first on Edureka.


Azure Boards: How To Get Started With Agile Planning on Azure?

$
0
0

In my previous article we discussed Azure DevOps and its components. This article would elaborate on one of those components known as Azure Boards. In the process we would explore how it helps to plan, track and also discuss work across different teams.

First, let us start by taking a look at the pointers to be discussed in this Azure Boards article:

  1. What is Azure Boards
  2. Azure Boards Features
  3. Demo: Getting Started with Azure Boards

So let us start by understanding what the term actually means.

What is Azure Boards?

Well, you can think of it as an interface that lets you you track tasks, features, and even bugs that may be associated with your project. Here you are aided by three work item types:

  • Epics
  • Issues
  • Tasks

Here is the depiction in the form of an image(Image Source: Microsoft.com):

Work Item Types - Azure Boards - Edureka

Also as the work gets completed the status gets updated stage by stage from:

  • To Do 
  • Doing 
  • Done

Here is the image below depicting the same (Image Source: Microsoft.com):

Workflow - Azure Boards - Edureka

Each time we create or add an issue, task or an epic, it means we are creating a work item. Every work item we create would represent an object. This object is stored in the work item data store. Every item here will have an identifier, assigned to it. These IDs are unique to a particular project.

If you wish to track significant features or requirements you add epics. Issues on the other hand are used to track user stories, bugs, or other smaller items of work. Likewise tasks are meant for tracking little amounts of work. The tracker can be used for both hourly and daily tracking.

Now let us take a look at some of the features of Azure Boards.

Features Of Azure Boards

Kanban Implementation

It is very easy to implement and use Kanban with Azure Boards. It eases up two important tasks, those are:

  • Update the status of issues
  • Prioritize Your Backlog of Issues

This means assigning work becomes a lot more easier and you can share information better and prioritize your work with drag and drop features provided.

Collaborate using Azure Boards

  • The Discussion section lets you collaborate better with the people in your project
  • You can create dashboards and  track status and trends of the accomplished work. Get instant alerts for the issues created, changed or resolved
  • You can set notifications to get alerted when an issue is created or changed

Flexibility to work in sprints and to implement Scrum

  • It becomes easier to plan sprints with proper assignment
  • You can use effort estimates to predict work
  • It is possible to assign issues or tasks in bulk

Integrate with GitHub

It is easy to connect to GitHub and in turn it means:

  • You can perform pull, push and commit requests with ease
  • You can link to GitHub commits and pull requests with ease

Let us now move further and see how can we use Azure Boards to carry out some of the features we discussed above.

Demo: Getting Started with Azure Boards

Step1: Start by opening this link in your browser ‘https://aex.dev.azure.com/signup/boards’. You would be re-directed to this page. Click on Continue.

Login - Azure Boards - Edureka

Step2: Next you would be asked to enter the organisation name and the location where you are operating from. Enter those and click on continue.

Step3: Next step is to create a project. Enter the details below and create a project.

Create-Project - Azure Boards - Edureka

Step4: You would be re-directed to following interface, You have four sections. The first one gives you access to all the major tabs of Azure Boards. Second one lets you add items. Third one is for issues and fourth one lets you manage project and project members.

Interface - Azure Boards - Edureka

Step5: Let us create an issue, to do that click on issues drop down on top left corner of your screen and select issue.

IssueCreation - Azure Boards - Edureka

Step6: Click on Add Item and enter the name of the issue. Once you hit the enter button, the issue tab would appear as below.

Adding and issue - Azure Boards - Edureka

Step7: We can change the state to Doing and your item would shift under the column named Doing.

switching to next state - Azure Boards - Edureka

Step8: You can add tasks to the issue. This bit covers what needs to be done. I have added three tasks and I have crossed one suggesting the task was complete.

Adding Tasks - Azure Boards - Edureka

So guys this was about adding a simple issue to your Azure boards. There is a lot that can be done with Azure boards. You are free to explore Azure Boards. As far as this article is concerned. I would be resting it here. In case if you like Cloud Computing and DevOps. You may want to check out this AWS Certified DevOps Engineer Training by Edureka which is catered to meet all the AWS and DevOps needs the learners may have.

In case of queries put those in the comment section and we revert at the earliest.

The post Azure Boards: How To Get Started With Agile Planning on Azure? appeared first on Edureka.

Vol. XII – Edureka Career Watch – 27th Apr. 2019

$
0
0

“Don’t be afraid to give up the good to go for the great,”

– John D. Rockefeller

The year 2019 has been one of the greatest in terms of job openings and career prospects. Many of us are already aware of this fact. But, even still, we do not really have the time or patience to hunt down the right opportunities or look at what technologies are changing the IT landscape, except for the obvious ones, of course. So, as per usual, Edureka Career Watch is bringing you your fortnightly pill that might help you make the next big decision in your career.

So, without further ado, let’s look at what the job market has had in store for us this past couple of weeks.

AI Researchers In-Demand by the Industry & Universities

A recent report by Nature points towards the fact that AI has become a force to be reckoned with. According to the article, AI researchers are finding an abundance of opportunities not just in the IT industry, but also in universities. To top it all off, these opportunities come with hefty pays and many other perks. The article states that while AI researchers are an absolute necessity in universities because of the cutting-edge work that needs to be monitored and automated, businesses in finance, manufacturing, and every other domain require AI engineers for jobs like risk analysis, robotics, and a lot more.

AI is one of the building blocks of the 21st century and it will keep changing the industry landscape for years to come.

via Nature

Become an AI expert today to get into one of the hottest job roles of this era.

Nutanix Launches WomEncore, a Returnship Program for Women

One of the major players in enterprise cloud computing, Nutanix, has recently launched a returnship program for women in India whose careers have been interrupted because of personal and family issues. Dubbed WomEncore (women encore), this new initiative hopes to re-skill women who would like to continue their career after taking a break from their jobs. This is not the first time Nutanix has launched such a program. The company is known for its long-standing and successful internship program for its product support and engineering teams.

via CIO

OnePlus Lists Several Job Vacancies Across its Global Bases

OnePlus, a name synonymous with premium smartphones has recently listed several job openings at most of its bases around the world. The smartphone giant is looking to fill over a hundred positions in different departments. While there are openings in locations like China, the UK, the US, Singapore et cetera, most of the job vacancies are specific to the company’s Bengaluru and Hyderabad bases. Also, these job postings range in experience requirement, as well. So, there are roles for everyone from entry-level to board-level professionals.

Tech giants like OnePlus are looking to increase their headcount because of the inevitable changes in the technology landscape.

via OnePlus

Up-skill today to never miss out on opportunities like these.

Wells Fargo is Hiring, Lists Several New Job Openings

Finance giant, Wells Fargo, has recently listed several job openings across different domains including business development, marketing, and obviously IT. The company is looking for software and systems architects, web developers, and QA analysts. These vacancies span across the company’s US bases at Minneapolis, Minnesota, Chandler, Arizona, San Francisco, California, Charlotte, and North Carolina.

via Wells Fargo

Amazon is Looking to Fill Several Software Development Roles

Technology giant, Amazon is looking to fill several software development roles across its Indian bases. The company has recently listed a handful of job openings, all in the software development domain for its Bengaluru and Hyderabad bases. These vacancies also range in experience requirement, so you can try out for them if you are an entry-level, a mid-level or even a senior professional.

Software development is an evergreen career landscape that will evidently never be out of opportunities.

via Stack Overflow

Learn Software Development today to ensure you are ready to opportunities like this.

We have some more good news for you! Edureka Career Watch is now also available as a video. Follow us on Instagram, LinkedIn, Facebook, and Twitter to never miss out on the latest news.

Make full use of Edureka’s expertise in the education and career counseling space. Speak with our course advisors today to get a clearer picture of your career path and more. Call us at:  IND: +91-960-605-8406 / US: 1-833-855-5775 (toll-free).

These were the major news stories related to job openings and career trends in the market this week. If you have any questions, suggestions or there are any specific topics you’d like us to cover, feel free to hit us up in the comments section below. Edureka Career Watch will be back next week with the top stories that you need to know. So, make sure you are subscribed to our blog through the subscription button below and never miss these important updates.

The post Vol. XII – Edureka Career Watch – 27th Apr. 2019 appeared first on Edureka.

Know How to Perform Stress Testing using JMeter on Websites

$
0
0

Most systems are developed under the assumption of normal operating conditions. It is important to ensure that it doesn’t breakdown under heavy loads. Software Testing makes sure that the system would not crash under crunch situations. This Stress Testing using JMeter article will guide you on how to perform stress testing in the following sequence:

Introduction to Performance Testing

Software testing provides the solution to all our problems about machines behaving the way we want them to. The different types of software testing help the tester determine the right choice of testing for the applications. 

 

Performance Testing is a type of software testing which ensures that the application is performing well under workload. It is further divided into six different types such as:

This article focuses on Stress Testing and we will have a look at how you can perform stress testing using JMeter.

Stress Testing Using JMeter | Edureka

What is Stress Testing?

Stress Testing is a type of Software Testing that verifies the stability & reliability of the system. This test mainly determines the system on its robustness and error handling under extremely heavy load conditions.

stress testing - stress testing using jmeter - edureka

 

Stress Testing ensures that the system would not crash under crunch situations. It tests beyond the normal operating point and evaluates how the system works under those extreme conditions. It also checks whether the system demonstrates effective error management.

 

Why do We Need Stress Testing?

It is important to perform Stress Testing on a website whenever there is a spike or a sudden surge in traffic. If you fail to accommodate this sudden traffic, it may result in loss of revenue and repute. Stress Testing is also required for the following reasons:

  • To check whether the system works under abnormal conditions.
  • Display appropriate error message when the system is under stress.
  • System failure under extreme conditions could result in enormous revenue loss.
  • Prepare the website for extreme conditions by executing Stress Testing.

Steps to Perform Stress Testing

There are 5 steps that you need to follow while performing stress testing on any website:

Stress Testing Steps - Stress Testing using JMeter - edureka

 

1. Plan the Stress Test – In this step, you gather the system data, analyze the system and define the stress test goals.
2. Create Automation Scripts – Here, you need to create the Stress testing automation scripts and generate the test data for the stress scenarios.
3. Script Execution – In the third step, you run the Stress testing automation scripts and store the stress results.
4. Results Analysis – After storing the results, now you need to analyze the Stress Test results and identify bottlenecks.
5. Tweaking and Optimization – In the final step,  you fine-tune the system, change configurations, and optimize the code to meet the desired benchmark.

Now you know about the different steps involved in the process of stress testing. So, let’s move ahead and have a look at the different types of stress testing and the tools required.

Stress Testing Types & Tools

The different types of Stress Testing include:

  • Distributed Stress Testing – In distributed client-server systems, you can perform testing across all clients from the server. The role of stress server is to distribute a set of stress tests to all stress clients and track on the status of the client.
  • Application Stress Testing – This testing is used for finding defects related to data locking and blocking, network issues and performance bottlenecks in an application.

 

Stress Testing Types - Stress testing using JMeter - edureka

 

  • Transactional Stress Testing – You need this testing to perform stress testing on a number of transactions between two or more applications. It is used for fine-tuning and optimizing the system.
  • Systematic Stress Testing – This testing is integrated and can be tested across multiple systems running on the same server. You can also find defects where one application data blocks another application.
  • Exploratory Stress Testing – This is used to test the system with unusual parameters or conditions that are unlikely to occur in a real scenario. You can find the defects in any critical situation.

These were some of the different types of stress testing. Now to perform these tests, you require certain tools. So, let’s have a look at some of the important tools used for stress testing.

Tools used for Stress Testing

Testing tools ensure that your applications are performing well in peak traffic and under extreme stress conditions. Below are some of the most commonly used stress/web testing tools:

 

 

  • Apache JMeter – Jmeter is an Open Source testing tool. It is a pure Java application for stress and Performance Testing.
  • LoadRunner – LoadRunner from HP is a widely-used Testing tool. Stress test results provided by  Loadrunner are considered as a benchmark.
  • NeoLoad – This tool is used to simulate thousands of users in order to evaluate the application performance under stress and analyze the response times.

You might get confused because there are a number of tools available for stress testing. But JMeter is one of the most preferred tools for performing stress testing on websites. So, let’s have a look at the steps required in the process of Stress Testing using JMeter.

 

Stress Testing Using JMeter

I have already discussed about Apache JMeter in detail and also the steps involved in the installation of JMeter in my previous articles. So, let’s get started with the steps involved in performing stress testing.

Step 1 – First, you have to create your own Test Plan in JMeter.

JMeter GUI - stress testing using JMeter - edureka

 

Step 2 – Insert a Thread Group and add an HTTP request with the server name of your website on which you want to perform stress testing.

HTTP Request - Stress testing using JMeter - edureka

 

Step 3 – Next, you need to add a listener inside the thread group and view the test results. It will show the status of the test that has taken place.

View Results - Stress testing using JMeter - edureka

 

Step 4 – Now you need to add a response assertion inside your thread group. It is one of the most important element because it helps you to assert the response of request in your software load test plan.

We will assert for response code 200 using response assertion. Response code 200 represents the success of your HTTP request. If you change the value from 200 to any other number, the status of the test will change to unsuccessful.

Response assertion - stress testing using jmeter - edureka

 

Now you can add a number of users or threads and increase the loop count. So this will increase the stress on your server. But You can continue performing the test and view results in order to check the status of your website under a certain amount of stress.

Now that you have understood what is stress testing, check out the Performance Testing Using JMeter Course by Edureka which is designed to introduce you to the complete software testing life-cycle. You will be learning different levels of testing, test environment setup, test case design technique, test data creation, test execution, bug reporting, CI/CD pipeline in DevOps, and other essential concepts of software testing. Got a question for us? Please mention it in the comments section of “Stress Testing using JMeter” and we will get back to you.

The post Know How to Perform Stress Testing using JMeter on Websites appeared first on Edureka.

What Is Unit Testing? Everything That You Need To Know About Unit Testing

$
0
0

The prime objective of any software project is to get a high-quality output while reducing the cost and the time required for completing the project. To achieve that companies subject software product to mainly four levels of testing. Unit testing is the first level of testing in Software Testing. Throughout this article, we will explore what unit test is in detail. If you are new to software testing, be sure to also read the Beginners’ Guide for Software Testing.

Let’s take a look at topics covered in this article:

Levels of Software Testing

Software Testing is a phase within the software development cycle in which business-critical software is verified for correctness, quality, and performance.

There are four fundamental levels within software testing, each examining the software functionality from a unique vantage point within the development process. The four levels of software testing are as shown in the image below.

Levels of Software Testing - What is Unit Testing? - Edureka

This article explains unit testing, the first level of software testing in detail.

What is Unit Testing?

Unit testing is a way of testing the smallest piece of code referred to as a unit that can be logically isolated in a system. It is mainly focused on the functional correctness of standalone modules.

A unit can be almost anything you want it to be – a specific piece of functionality, a program, or a particular method within the application. Smaller the unit, better it is. Smaller tests usually give you a much more granular view of your production, the code is performing. Also, your tests can run faster if they are small. So, it is also micro-level of software testing.

How Do You Perform Unit Testing?

The goal of unit testing to separate each part of the program and test that the individual parts are working correctly and as intended. While performing unit tests, application code functions are executed in a test environment with sample input. The output obtained is then compared with the expected output for that input. If they match the test passes. If not it is a failure. Unit tests are great for confirming the correctness of the code. Let’s take a look at a sample algorithm that illustrates the concept. 

Unit Testing Algorithm - What is Unit Testing? - Edureka

As you can see, performing the unit test is quite simple. You write part of the code and subject it to test. If the test passes then you add it to your test suite and test the next part of the code. Else, you make the necessary changes and retest it again. Repeat the process until all the units of software are tested. This type of basic testing offers a lot of advantages like finding software bugs early, simplifying integration, providing a source of documentation, and many others.

What are the Benefits of Unit Testing?

Conducting regression tests, benefits companies in a number of ways such as:

Makes Coding Agile

Unit testing speeds up the coding process. When you add new features to your application, sometimes you might have to modify the design and code of your software product. However, changing already tested code costs too much money and effort. But with unit tests, you can just test the newly added piece of code instead of testing the entire program. Also, unit tests improve the quality of your code.

Helps Find Software Bugs Early

As unit tests are carried out by developers who test individual code before integration, issues can be found very early in the software testing process. They can be resolved then and there without impacting the other pieces of the code. The advantage of detecting errors early is that you can minimize development risks, and avoid spending too much money and time.

Provides Documentation

In testing, code documentation is often neglected since it requires a lot of time. But unit testing makes documentation a little easier by encouraging better coding practices and also leaving behind pieces of code that describe what your product is doing.

Debugging is Made Easier

Unit testing simplifies the debugging process. When a test fails, only the latest changes made in the code need to be debugged. At higher levels of testing changes made over the span of several days or weeks or months need to be scanned.

Reduces Testing Costs

Since the bugs are found early, the cost of bug fixes is reduced up to some extent. It would cost much more if a bug is found during the later stages of development. You will have to modify the entire code of your project. That sounds really tiring and waste of money. So performing unit testing saves precious time and money as well.

There you go! I hope you are convinced as to why unit testing is important. Moving further, let’s check out a simple demo on how to write unit tests.

Demo: Writing a Sample Unit Test

Unit testing demands that a good test should be:

  • Easy to write
  • Readable
  • Reliable
  • Faster & Efficient

Requirements for the demo:

  • Java Development Kit(JDK)
  • An IDE(In this demo Eclipse is used)
  • Unit testing framework(In this demo TestNG is used)

Let’s get started with the demo. So, in this demo, I have two files:

  • A Math class with a function to test
  • A Test class with methods to perform testing

Take a look at the below code to understand the test case. It’s a Math class with two methods: add, multiply. 


public final class Math {

public static int add(int first, int second) 

{
  return first + second;
}

public static int multiply(int multiplicand, int multiplier) 

{
  return multiplicand * multiplier;
}

}

Next up we have a Test class with methods to test the functionality of the add() function and multiply() function.


import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class MathTests {

@Test
public void add_TwoPlusTwo_ReturnsFour() {
final int expected = -4;

final int actual = Math.add(-2,-3);

assertEquals(actual, expected);
}
@Test
public void multiple_twonumbers_retursvalue() {
final int expected = -4;

final int actual = Math.multiply(2,2);
assertEquals(actual, expected);

}

}

Unit Test: Checking functionality of add function

Comment the multiply() function in Math class and multiple_twonumbers_retursvalue() function in Test class. Then assign value for the expected variable and call the multiply() function with sample input(consider both positive & negative cases). When you run the test, the expected value is compared with the actual value. If the test is returning the intended results, it means that add() function is working perfectly. I have attached a screenshot of test results when the expected value is -5 and the parameters passed to add() function are -2 and -3.

Simple right? We have tested a unit or part of the entire program. You can do the same with multiply() function. The purpose of this demo was to make you understand what a unit means in unit testing. So, the main objective of here is to verify the internal design and internal logic, internal paths of the software project in small chunks. The unit testing framework that I used in this demo is TestNG. There are various other unit testing frameworks for various programming languages.

Best Unit Testing Frameworks

Some of the popular unit testing frameworks are:

  • JUnit: It is an open-source framework for a test-driven development environment, specifically designed for Java programming language.
  • NUnit: It is one of the most popular unit-testing frameworks for C#.
  • TestNG: Designed for Java programming language, it resembles JUnit and NUnit but offers some new functionalities which make it more powerful and easier to use.
  • HtmlUnit: It is one of the most popular frameworks for JavaScript. It is used for testing web applications that are used within frameworks like JUnit and TestNG.
  • Unitest: Inspired by the JUnit framework, this framework supports test automation and acts independently of the tests from the reporting environment. It is one of the most popular unit-testing frameworks for Python.

Apart from these, there are a lot of other frameworks. With this, we have reached the end of the blog. Hope the things that you have learned here today will help you as you head out on your software testing journey.

If you found this article relevant, check out the live-online Selenium Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this article and we will get back to you.

The post What Is Unit Testing? Everything That You Need To Know About Unit Testing appeared first on Edureka.

Smoke Testing and Sanity Testing: How are they different?

$
0
0

Every business runs on software and all the software needs to be tested before it is released to users. Software testing is vital to release efficient, effective and reliable software at a rapid pace. There are different types of software testing and each of these types has a different purpose and provides a unique value to the software development process. In this article, we will be discussing the two most frequently misunderstood types: smoke testing and sanity testing.

Let’s take a look at topics covered in this article:

Types of Software Testing

Software Testing is a crucial phase of the software development cycle. There are many different types of software testing. Each of these testing types has its own purpose. The type of software testing that you choose depends on your testing objective, the complexity, and functionality of your software, and your testing team. The image below lists out some of the most common types of software testing used today.

TestingTypes - Smoke Testing and Sanity Testing - EdurekaThis article will help you figure out what smoke testing and sanity testing are and how different they are from each other. Let’s get started.

Smoke Testing

What is Smoke Testing?

Smoke Testing is a type of software testing which is usually performed on initial software builds to make sure that the critical functionalities of the program are working absolutely fine.

Not sure what software build is? A software build is a process by which source code is converted to a stand-alone form that can be run on any system. It is often referred to as a code build. Coming back to smoke testing, it is executed before any functional or any regression tests are executed in detail on the software build. The main objective here is to reject a badly broken application so that the QA team does not waste time installing and testing the software application. Instead of performing exhaustive testing, we make sure that critical functionalities are working fine.

How to Conduct Smoke Testing?

Smoke tests can be performed manually or they can be automated. To execute smoke tests, you don’t need to write new test cases, instead, you can just pick the necessary test cases that are already defined by programmers. The primary focus here is to test the core application workflow. So, just pick those test cases that define the main functionalities of your software. Let’s try to figure this out with a real-time example.

Smoke Testing - Smoke Testing and Sanity Testing - Edureka

Let’s say, you are working on an e-commerce site. You have a few initial builds that are ready to be released for testing. First thing you need to do is to check if the core functionalities are working or not. So, you try to access the site and add an item to your cart to place an order. Well, that’s the major workflow of any e-commerce site, right? If this primary workflow works, you can say that the build that you have subjected to testing has passed the smoke test. You can then move on to next rounds of testing.

Now that you are clear with what smoke testing is, let’s get to the next topic of this article, that is sanity testing.

Sanity Testing

What is Sanity Testing?

Smoke Testing is a type of software testing which is conducted after receiving a software build, with minor changes in the code, or functionality. The aim is to make sure that the bugs have been fixed and to confirm that there are no further issues introduced due to the new changes.

Unlike smoke testing, the objective goal of sanity test is not to verify the core functionalities, instead, it is to verify the correctness and rationality of the software. It is usually done near the end of a test cycle, to ascertain if bugs have been fixed and if minor changes to the code are well tolerated. Also, to determine whether the most recent fixes have affected any component functionality. Sanity tests are often unscripted and can be performed manually, or with the help of automated tools.

How to Conduct Sanity Testing?

Similar to smoke testing, you don’t need to write new test cases unless a new feature is introduced. The main objective here is, to ensure that false results or bugs are not present in component processes. Also, to check whether the build is sane enough to move to further stages of software testing cycle

Sanity Testing - Smoke Testing and Sanity Testing - Edureka

Let’s consider the same example that we used for smoke testing. So, you are working on an e-commerce site. A new feature related to user registration is released. Your main goal is to check if the new feature is working correctly or not. Once you are sure that it’s working as it is supposed to, then you move on to the next level of testing. If the sanity test fails, it is not reasonable to attempt more rigorous testing. In the sanity tests, you exercise the smallest subset of application functions needed to determine whether the application logic is functional and correct.

You might have noticed that there is some overlap between smoke testing and sanity testing, especially when it comes to the fact that neither is really designed to be a thorough process. However, there are also obvious and important differences between these two testing types. Let’s check them out.

Smoke Testing vs Sanity Testing

Smoke testing and sanity testing describe very different practices. But people still get them confused, since the distinction is somewhat subtle. The table below lists the key differences between smoke testing and sanity testing.

Features Smoke Testing Sanity Testing
System Builds Tests are executed on initial builds of software product Tests are done over builds that have passed smoke tests & rounds of regression tests 
Motive of Testing To measure the stability of the newly created build to face off more rigorous testing To evaluate rationality & originality of the functionalities of software builds
Subset of? Is a subset of regression testing Is a subset of acceptance testing
Documentation Involves documentation and scripting work Doesn’t emphasize any sort of documentation
Test Coverage Shallow & wide approach to include all the major functionalities without going too deep Narrow & deep approach involving detailed testing of functionalities and features
Performed By? Executed by developers or testers Executed by testers

So, that’s it, guys! With this, we have reached the end of this article. Hopefully, by now, you have the basic knowledge of smoke testing and sanity testing. These are important testing types which ensure the detection of bugs and defects in early stages of the development cycle and I hope you will be using them well.

If you found this article relevant, check out the live-online Selenium Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this article and we will get back to you.

The post Smoke Testing and Sanity Testing: How are they different? appeared first on Edureka.

Learn how to Perform an Effective Project Stakeholder Management

$
0
0

Most of the projects fail because of poor stakeholder management as stakeholders are one of the key factors which play a huge role in deciding the success or failure of a project. In this article on Project Stakeholder Management, I will be giving you a complete insight into who exactly are these stakeholders and why a separate Knowledge Area has been dedicated for their management along with various process involved in it.

Below are the topics that I would be discussing in this article:

If you wish to master the concepts of project management and become a certified project manager, you can check out our instructor-led PMP Certification Training where these topics are covered in depth.

What is Project Stakeholder Management?

Project Stakeholder Management is one of the ten Knowledge Areas of the project management framework that exclusively deals with the resources involved in a project. According to PMBOK® Guide – Sixth Edition,

Project Stakeholder Management includes the processes required to identify the people, groups, or organizations that could impact or be impacted by the project, to analyze stakeholder expectations and their impact on the project, and to develop appropriate management strategies for effectively engaging stakeholders in project decisions and execution.

Project stakeholder management is the process where a project manager needs to form, monitor and maintain productive relationships with the investors involved in the project. This is mostly done by influencing the expectations of the stakeholders regarding the result gained from their initial investment in the project appropriately. It also helps a business towards its defined goals by preserving the existing investor’s satisfaction and furthermore, recruiting new investors as per requirement but in an ethical way.

Before explaining project stakeholder management in further detail, you must have a clear understanding of who a stakeholder is.

In any business, a stakeholder is normally an investor in a company or a project and plays a vital role in companies business decisions. A stakeholder need not be an equity holder if the company but can be a regular employee as well. To put it in simpler terms, stakeholders are of three types:

  1. Internal Stakeholders: These are the people who own or work in the organization such as business partners, board members, and employees.
  2. External Stakeholders: These are the people who are affected by the performance and the outcomes of a business such as local city government, community residents, nonprofits business sponsors, the trade media, etc.
  3. Connected Stakeholders: This group includes people like shareholders, vendors, suppliers, retailers, contractors, customers, wholesalers, sales reps, distributors, etc.

To conclude this, you can say that a stakeholder is a person or a group of people who have an interest in your project and will be influenced by its deliverables/ output. Thus for a project manager, it becomes very important to understand the values and issues that stakeholders have in order to resolve. Addressing stakeholders issues are very necessary for avoiding any possible conflicts and ensuring that everyone remains satisfied until the completion of the project.

I hope this clears who is a stakeholder and what role he plays in an organization. Moving ahead, let’s now see with proper stakeholder management how a project can be benefitted.

Need for Project Stakeholder Management

  1. Stakeholder Identification: With better identification and engagement of valuable stakeholders in your project, the implementation of the project will be more aligned to the project managers benefit.
  2. Relationship Building: Stakeholder management helps in early relationship building with the stakeholders which leads them to engage earlier in the project. It is really helpful in building rapport with the public.
  3. Fewer Surprises and better communication: Since everything is well discussed and communicated with the stakeholders, it reduces the chances of getting caught off guard and in turn reduces the number of iterations or modifications.
  4. A better understanding of needs and concerns: With Stakeholder management, you get to communicate with each of the stakeholder involved in your project which helps in getting a clear cut view of their idea about the project and related concerns.
  5. Better time and money investment: Stakeholder management keeps you in the loop with the stakeholders which results in continuous input and regular feedback from them. This ensures that the tasks that you are working on hold the highest value to the project.
  6. Happier Stakeholders: Since you are keeping your stakeholders in a proper loop and with regular involvement, they will feel happy and satisfied.
  7. Improved Reputation: Being a project manager it is very important to hold good rapport in the market. With good stakeholder management skills, you can relate well with people in their projects which in turn will help you in adding stars to your reputation as well.

Now that you are aware of various benefits and need for stakeholder management in a project, let’s now dive deeper to get a better insight on how actually it works internally.

Project Stakeholder Management Processes

Project Stakeholder Management knowledge area consists of four processes. They are:

  1. Identify Stakeholders
  2. Plan Stakeholder Engagement
  3. Manage Stakeholder Management
  4. Monitor Stakeholder Engagement

Identify Stakeholders

The initial process of project stakeholder management is Identify Stakeholders. In this process, the project stakeholders are regularly identified, analyzed and various information related to them such as their interests, involvement, interdependencies, influence, and potential impact on project success are documented. It is performed at periodic intervals throughout the project lifecycle which helps the project team in identifying appropriate focus required for the engagement of each stakeholder involved in the project.

Below I have listed down the various inputs, techniques, and outputs involved in this process of project stakeholder management:

Inputs Tools & Techniques Outputs
  1. Project Charter
  2. Business Documents
    • Business Case
    • Benefits Management Plan
  3. Project Management Plan
    • Communications Management Plan
    • Stakeholder Engagement Plan
  4. Project Documents
    • Change log
    • Issue Log
    • Requirements Documentation
  5. Agreements
  6. Enterprise Environmental Factors
  7. Organizational Process Assets
  1. Expert Judgement
  2. Data Gathering
    • Data gathering Questionnaires & Surveys
    • Brainstorming
  3. Data Analysis
    • Stakeholder Analysis
    • Document Analysis
  4. Data Representation
    • Stakeholder mapping/representation
  5. Meetings
  1. Stakeholder Register
  2. Change Requests
  3. Project Management Plan Updates
    • Requirements Management Plan
    • Communications Management Plan
    • Risk Management plan
    • Stakeholder Engagement Plan
  4. Project documents updates
    • Assumption Log
    • Issue Log
    • Risk Register

Plan Stakeholder Engagement

The second process of project stakeholder management is Plan Stakeholder Engagement. In this process, various approaches are curated in order to involve the stakeholders on the basis of their needs, interests, expectations, and latent impact on the project. It is performed at periodic intervals throughout the project lifecycle and helps in developing a realistic plan which can effectively interact with the stakeholders.

In the below table, I have listed down various inputs, tools, and techniques and outputs involved in this process:

Inputs Tools & Techniques Outputs
  1. Project Charter
  2. Project Management Plan
    • Resource Management Plan
    • Communication Management Plan
    • Risk Management Plan
  3. Project Documents
    • Assumption Log
    • Change Log
    • Issue Log
    • Project Schedule
    • Risk Register
    • Stakeholder Register
  4. Agreements
  5. Enterprise Environmental Factors
  6. Organizational Process Assets
  1. Expert Judgement
  2. Data Gathering
    • Benchmarking
  3. Data Analysis
    • Assumption and Constraint Analysis
    • Root Cause Analysis
  4. Decision Making
    • Prioritizing/Ranking
  5. Data Representation
    • Mind Mapping
    • Stakeholder Engagement Assessment Matrix
  6. Meetings
  1. Stakeholder Engagement Plan

Manage Stakeholder Management 

Next process of this knowledge area is Manage Stakeholder Engagement. In this process, various steps are taken for better communication and maintain working with stakeholders so that by the end of the project all their needs and expectations are met. Along with this their concerns and issues are addressed and appropriate stakeholder involvement is fostered as well. It is performed throughout the project lifecycle and helps a project manager in increasing support and minimizing resistance from the stakeholders.

I have listed down the various inputs, tools & techniques and outputs involved in this process:

Inputs Tools & Techniques Outputs
  1. Project Management Plan
  2. Project Documents
    • Change Log
    • Issue Log
    • Lessons Learned Register
    • Stakeholder Register
  3. Enterprise Environmental Factors
  4. Organizational Process Assets
  1. Expert Judgement
  2. Communication Skills
    • Feedback
  3. Interpersonal & Team Skills
    • Ground Rules
    • Meetings
    1. Change Requests
    2. Project Management Plan Updates
      • Communication Management Plan
      • Stakeholder Engagement Plan
    3. Project Documents Updates
      • Change Log
      • Issue Log
      • Lessons Learned Register
      • Stakeholder Register

    Monitor Stakeholder Engagement

    Monitor Stakeholder Engagement is the final process of project stakeholder management Knowledge Area. As the name suggests, in this process relationships of project stakeholders are monitored and various strategies are tailored in order to engage the stakeholders using engagement plans and strategies. This process is performed throughout the project lifecycle and helps in maintaining as well as increasing the efficiency and effectiveness of the implied stakeholder engagement activities. This process is very crucial to perform while the project evolves and its development environment varies.

    Various inputs, tools and techniques, and outputs involved in this process have been listed below:

    Inputs Tools & Techniques Outputs
    1. Project Management Plan
    2. Project Documents
      • Issue Log
      • Lessons Learned Register
      • Project Communications
      • Risk Register
      • Stakeholder Register
    3. Work Performance Data
    4. Enterprise Environmental Factors
    5. Organizational Process Assets
    1. Data Analysis
      • Alternative Analysis
      • Root cause Analysis
      • Stakeholder Analysis
    2. Decision Making
      • Multicriteria Decision Analysis
      • Voting
    3. Data Representation
      • Stakeholder Engagement Assessment Matrix
    4. Communication Skills
      • Feedback
      • Presentations
    5. Interpersonal & Team Skills
      • Active Listening
      • Cultural Awareness
      • Leadership
      • Networking
      • Political Awareness
    6. Meetings
    1. Work Performance Information
    2. Change Requests
    3. Project Management Plan Updates
    4. Project Documents Updates
      • Issue Log
      • Lessons Learned Register
      • Risk Register
      • Stakeholder Register

    This brings us to the end of this Project Stakeholder Management article. Hope it helped in adding value to your knowledge. If you wish to learn more about project management or project management certifications you can check my other articles as well.

    If you found this “Project Stakeholder Management” article relevant, check out the PMP® Certification Exam Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

    Got a question for us? Please mention it in the comments section of this Project Stakeholder Management article and we will get back to you.

    The post Learn how to Perform an Effective Project Stakeholder Management appeared first on Edureka.

    What are ChromeDriver and GeckoDriver in Selenium?

    $
    0
    0

    Software testing, in recent days, has reached the peaks of popularity and the growth of Automation testing using Selenium has added more wings to this transformation. As you all be might be aware that Selenium is the best tool for testing a website. But what is the very basic thing that you need for website testing? Well, Selenium provides few drivers that help you in creating a browser instance and perform testing. In this article, I will give you a brief insight into two of the important drivers which are ChromeDriver and GeckoDriver in Selenium.

    Below is the list of topics that I will be covering in this article:

    ChromeDriver

    GeckoDriver

    You may also go through this recording of ChromeDriver in Selenium by experts where you can understand the topics in a detailed manner with examples.

    What is ChromeDriver?

    WebDriver is an open source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and many more. ChromeDriver is a standalone server which implements WebDriver’s wire protocol for Chromium. In order to instantiate the object of ChromeDriver, you can simply create the object with the help of below command.

    Webdriver driver = New ChromeDriver();

    Now, let’s move further in this ChromeDriver and GeckoDriver in Selenium article and understand why you need a ChromeDriver in Selenium.

    Why do you need ChromeDriver?

    The main purpose of the ChromeDriver is to launch Google Chrome. Without that, it is not possible to execute Selenium test scripts in Google Chrome as well as automate any web application. This is the main reason why you need ChromeDriver to run test cases on Google Chrome browser. 

    Now that you know what is ChromeDriver and why do you need it, let’s move ahead and understand how to set up ChromeDriver in the system.

    Setting Up ChromeDriver

    Step 1: Navigate to the Selenium official website. Under third-party drivers, you will find all the drivers. Just click on Google ChromeDriver and choose the latest version and download it. Below image depicts the same.

    Chrome Driver download - ChromeDriver and GeckoDriver in Selenium - Edureka

    Step 2: Based on your operating system, you can choose the preferred ChromeDriver that suits your operating system as shown in the below image. 

    Chrome Driver - ChromeDriver and GeckoDriver in Selenium - Edureka

    Step 3: Once the zip file is downloaded, you can unzip it in order to retrieve chromedriver.exe. executable file. Below image depicts the executable ChromeDriver application.

    Chromedriver executable file - Chrome Driver and GeckoDriver in Selenium - Edureka

    Step 4: After configuring ChromeDriver, you need to copy the path where you have saved a ChromeDriver to set the system properties of the driver.

    Step 5: Now let’s move further and understand the Selenium script and see how ChromeDriver is useful in launching Google Chrome browser and executing the test cases.

    package Edureka;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.chrome.ChromeDriver;
    public class Chrome {
    public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "C:\\Selenium-java edureka\\chromedriver_win32\\chromedriver.exe"); // Setting system properties of ChromeDriver
    WebDriver driver = new ChromeDriver(); //Creating an object of ChromeDriver
    driver.manage().window().maximize();
    driver.manage().deleteAllCookies();
    driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get("https://www.google.com/");
    driver.findElement(By.name("q")).sendKeys("Edureka"); //name locator for text box
    WebElement searchIcon = driver.findElement(By.name("btnK"));//name locator for google search
    searchIcon.click();
    
    

    In the above code, I have used System.set.property() to set the properties of the ChromeDriver and then created an object of ChromeDriver. This will help us to instantiate the Google Chrome browser and execute the test cases. So, I will start Google Chrome and navigate to google.com. Here, I will try to locate the search box using the name locator. On inspecting the web element you can see that it has an input tag and attributes like class and id. Next, I will copy the name of name locator and paste it in my Selenium script as shown in the above code. On executing the code, it will give you an automated search of Selenium. Basically, this is how it works. But the role of ChromeDriver basically is to launch Google Chrome browser.

    This was all about ChromeDriver. I hope this helped you in gaining a few insights about ChromeDriver. Now let’s move further and learn the fundamentals of another driver that is widely used in the market, i.e. GeckoDriver.

    What is GeckoDriver?

    GeckoDriver is a web browser engine which is used in many applications developed by Mozilla Foundation and the Mozilla Corporation. GeckoDriver is the link between your tests in Selenium and the Firefox browser. GeckoDriver is a proxy for using W3C WebDriver-compatible clients to interact with Gecko-based browsers. In order to instantiate the object of GeckoDriver, you can simply create the object with the help of the below command.

    Webdriver driver = New FirefoxDriver();

    You may also go through this recording of GeckoDriver in Selenium by experts where you can understand the topics in a detailed manner with examples.

    Why do you need GeckoDriver?

    For Mozilla Firefox till version 47, we never needed GeckoDriver. But the Mozilla Firefox after version 47, comes with Marionette, which is an automation driver for Mozilla’s.

    It can remotely control either the UI or the internal JavaScript of a Gecko platform, such as Firefox. So, you require GeckoDriver for FireFox. If you do not use it, you won’t be able to instantiate the object of GeckoDriver and launch Firefox. That is the reason why you need a GeckoDriver.

    Now that you know what is GeckoDriver and why do you need it, let’s dive deeper in this ChromeDriver and GeckoDriver in Selenium article and learn how to set up GeckoDriver in the system.

    Setting Up GeckoDriver

    Step 1: Navigate to the Selenium official website. Under third-party drivers, you will find all the drivers. Just click on Mozilla  GeckoDriver and choose the latest version and download it. Below image depicts the same.

    GeckoDriver Download - ChromeDriver and GeckoDriver in Selenium - Edureka

    Step 2: Next, you will be redirected to GitHub where you will find options for GeckoDriver releases as depicted in the below image.

    GeckoDriver Releases - ChromeDriver and GeckoDriver in Selenium - Edureka

    Step 3: Based on your operating system, you can choose the preferred ChromeDriver that suits your operating system as shown in the below image.

    GeckoDriver DownloadVersion - ChromeDriver and GeckoDriver in Selenium - Edureka

    Step 4: Once the zip file is downloaded, you can unzip it in order to retrieve geckodriver.exe executable file.

    Step 5: After configuring GeckoDriver, you need to copy the path where you have saved GeckoDriver to set the system properties of it.

    Step 6: Now let’s move further and understand the Selenium script and see how GeckoDriver is useful in launching the Mozilla Firefox browser and executing the test cases.

    package Edureka;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class Example {
    public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\geckodriver-v0.23.0-win64\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().deleteAllCookies();
    driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
    String baseUrl = "https://www.edureka.co/";
    String expectedTitle = "Instructor-Led Online Training with 24X7 Lifetime Support | Edureka";
    String actualTitle = "";
    // launch firfox and direct it to the Base URL
    driver.get(baseUrl);
    // get the actual value of the title
    actualTitle = driver.getTitle();
    
    /*compare the actual title of the page with the expected one and print
     the result as "Passed" or "Failed"*/
    
    if (actualTitle.contentEquals(expectedTitle)){
    System.out.println("Test Passed!");
    } else {
    System.out.println("Test Failed");
    }
    }
    }
    

    In the above code, I have used System.set.property() to set the properties of the GeckoDriver and then created an object of GeckoDriver. That will help us to instantiate the Mozilla Firefox browser and execute the test cases. So, I will launch the Mozilla Firefox and navigate to edureka.co website. Here, I will check whether the actual title matches with the expected title of the webpage or not manually. On executing the code, GeckoDriver will launch Mozilla Firefox browser and navigate to edureka.co website. In the backend, Selenium will implicitly verify if the actual title matches with the expected title or not. If it matches, then it will print Test Passed. Else, it will print Test Failed. This is how it works.

    This was all about GeckoDriver. With this, we come to an end of this article on ChromeDriver and GeckoDriver in Selenium. I hope you understood the concepts and it added value to your knowledge.

    If you wish to learn Selenium and build a career in the testing domain, then check out our interactive, live-online Selenium Certification Training here, that comes with 24*7 support to guide you throughout your learning period.

    Got a question for us? Please mention it in the comments section of ChromeDriver and GeckoDriver in Selenium article and we will get back to you.

    The post What are ChromeDriver and GeckoDriver in Selenium? appeared first on Edureka.


    Know How to Perform Cross Browser Testing Using Selenium

    $
    0
    0

    With the increasing demand for automation testing, Selenium is one such tool which perfectly fits for Cross Browser Testing of a website. It is very necessary to check the compatibility and performance of the websites on different browsers and operating systems. So, this article on Cross Browser testing using Selenium will help you understand these concepts in depth.

    Below are the topics covered in this article:

    What is Cross Browser Testing?

    Cross-browser testing is nothing but testing the application in multiple browsers like IE, Chrome, Firefox so that we can test our application effectively. Cross-browser compatibility is the ability of a website or web application to function across different browsers and operating systems. 

    Cross broswer testing using selenium - edurekaFor Example– Say you have 20 test cases to execute manually.  You can complete this task in a day or two. But, if the same test cases have to be executed in five browsers, then probably you will take a week to complete it. However, if you automate these 20 test cases and run them, then it will not take more than an hour or two depending on the test case complexity. So that’s where cross-browser testing comes into the picture.

    Now, let’s move further and see why do you need Cross Browser Testing in Selenium.

    Why do you need Cross Browser Testing?

    Every website is comprised of three major technologies i.e. HTML5, CSS3, and JavaScript. However, there are n number of technologies in the backend like PythonRuby, etc can be used. But, in the front end and in the rendering, only these three technologies are used.

    Also, each browser uses a completely different rendering engine to compute these three technologies. For example, Chrome uses Blink, Firefox uses Gecko and IE uses edge HTML and Chakra,  because of which the same website would be rendered completely differently by all these different browsers. And that’s exactly why you need cross-browser testing. That means the website should work perfectly fine, in all the different browser versions and in different operating systems. So to ensure that it works fine, cross-browser testing is required.

    Along with that, I have listed a few reasons that depict the need for Cross Browser Testing.

    • Browser compatibility with different OS.
    • Image orientation.
    • Each browser has a different orientation of Javascript which can cause issue sometimes.
    • Font size mismatch or not rendered properly.
    • Compatibility with the new web framework.

    Now let’s move further and understand how to perform Cross Browser Testing.

    How to Perform Cross Browser Testing?

    Cross-browser testing is basically running the same set of test cases multiple times on different browsers. This type of repeated task is best suited for automation. Thus, it’s more cost and time effective to perform this testing by using tools. Now let’s see how it is performed using selenium web driver.

    Step1: If we are using Selenium WebDriver, we can automate test cases using Internet Explorer, FireFox, Chrome, Safari browsers.

    Step 2: To execute test cases with different browsers in the same machine at the same time we can integrate TestNG framework with Selenium WebDriver.

    Step3: Finally, you can write the test cases and execute the code.

    Now, let’s see how to perform cross-browser testing of Edureka website on three different browsers

    Demo using Selenium WebDriver

    package co.edureka.pages;
    
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.edge.EdgeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Parameters;
    import org.testng.annotations.Test;
    
    public class CrossBrowserScript {
    
    WebDriver driver;
    
    /**
    * This function will execute before each Test tag in testng.xml
    * @param browser
    * @throws Exception
    */
    @BeforeTest
    @Parameters("browser")
    public void setup(String browser) throws Exception{
    //Check if parameter passed from TestNG is 'firefox'
    if(browser.equalsIgnoreCase("firefox")){
    //create firefox instance
    System.setProperty("webdriver.gecko.driver", "C:\\geckodriver-v0.23.0-win64\\geckodriver.exe");
    driver = new FirefoxDriver();
    }
    
    //Check if parameter passed as 'chrome'
    else if(browser.equalsIgnoreCase("chrome")){
    //set path to chromedriver.exe
    System.setProperty("webdriver.chrome.driver", "C:\\Selenium-java-edureka\\New folder\\chromedriver.exe");
    driver = new ChromeDriver();
    
    }
    else if(browser.equalsIgnoreCase("Edge")){
    //set path to Edge.exe
    System.setProperty("webdriver.edge.driver","C:\\Selenium-java-edureka\\MicrosoftWebDriver.exe");;span style="font-family: verdana, geneva, sans-serif; font-size: 14px;">//create Edge instance</span>
    driver = new EdgeDriver();
    }
    else{
    //If no browser passed throw exception
    throw new Exception("Browser is not correct");
    }
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }
    
    @Test
    public void testParameterWithXML() throws InterruptedException{
    driver.get("https://www.edureka.co/");
    WebElement Login = driver.findElement(By.linkText("Log In"));
    //Hit login button
    Login.click();
    Thread.sleep(4000);
    WebElement userName = driver.findElement(By.id("si_popup_email"));
    //Fill user name
    userName.sendKeys("your email id");
    Thread.sleep(4000);
    //Find password'WebElement password = driver.findElement(By.id("si_popup_passwd"));
    //Fill password
    password.sendKeys("your password");
    Thread.sleep(6000);
    
    WebElement Next = driver.findElement(By.xpath("//button[@class='clik_btn_log btn-block']"));
    //Hit search button
    Next.click();
    Thread.sleep(4000);
    WebElement search = driver.findElement(By.cssSelector("#search-inp"));
    //Fill search box
    search.sendKeys("Selenium");
    Thread.sleep(4000);
    //Hit search button
    
    WebElement searchbtn = driver.findElement(By.xpath("//span[@class='typeahead__button']"));
    searchbtn.click();
    }
    }

     

    In the above code, I am performing actions on Edureka website like logging in to the website and searching for Selenium course. but, I want to check the cross-browser compatibility on three different browsers i.e Google Chrome, Mozilla Firefox, and Microsoft Edge. That’s why I have set the system properties of all the 3 browsers in my code. After that using locators I am performing actions on the website. So this is all about my class file. Now in order to execute the program, you need a TestNG XML file which contains the dependencies of the above class file. Below code depicts the TestNG file.

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    <suite name="TestSuite" thread-count="2" parallel="tests" >
    <test name="ChromeTest">
    <parameter name="browser" value="Chrome"/>
    <classes>
    <class name="co.edureka.pages.CrossBrowserScript">
    </class>
    </classes>
    </test>
    <test name="FirefoxTest">
    <parameter name="browser" value="Firefox" />
    <classes>
    <class name="co.edureka.pages.CrossBrowserScript">
    </class>
    </classes>
    </test>
    <test name="EdgeTest">
    <parameter name="browser" value="Edge" />
    <classes>
    <class name="co.edureka.pages.CrossBrowserScript">
    </class>
    </classes>
    </test>
    </suite>
    
    

    In the above XML file, I am specifying different classes for the drives so that it will help us in instantiating the browsers to execute the test cases on the website. That’s how it works.

    With this, we come to an end of this article on Cross Browser Testing using Selenium Webdriver. I hope you understood the concepts and it added value to your knowledge.

    If you wish to learn Selenium and build a career in the testing domain, then check out our interactive, live-online Selenium Certification Training here, that comes with 24*7 support to guide you throughout your learning period.

    Got a question for us? Please mention it in the comments section of Cross Browser Testing using Selenium article and we will get back to you.

    The post Know How to Perform Cross Browser Testing Using Selenium appeared first on Edureka.

    Operators In Python – All You Need To Know

    $
    0
    0

    Python language is one of the most popular programming languages. While learning python is seemingly easy, there are certain core concepts that must be mastered before moving on with various applications of python. Operators in python is one of the core fundamental concept in python. This blog will help you understand the different types of operators in python. Following are the topics covered in this blog:

    What Is An Operator?

    Operators in python are used for operations between two values or variables. The output varies according to the type of operator used in the operation. We can call operators as special symbols or constructs to manipulate the values of the operands. Suppose if you want to perform addition of two variables or values, you can use the addition operator for this operation. The values in the operands can be  variable or any data type that we have in python.

    operators in python-edureka

    Depending upon the type of operations there are 7 types of operators in python programming language.

    Types of Operators

    1. Arithmetic operators
    2. Assignment operators 
    3. Comparison operators
    4. Logical operators
    5. Membership operators
    6. Identity operators
    7. Bitwise operators

    Arithmetic operators

    Arithmetic operators are used to perform arithmetic calculations in python. Below are the arithmetic operators with names and their symbols. These are the symbols that we use while doing an arithmetic operation in python.

    x = 10
    y = 15
    #addition
    x + y
    #subtraction
    x - y
    #multiplication
    x * y
    #division
    x / y
    #floor division
    x // y
    #modulus
    x % y
    #exponentiation
    x ** y
    
    

    Assignment operators

    Assignment operators are used to assign values to the variables or any other object in python. Following are the assignment operators that we have in python.

    assignment operators-operators in python-edureka

    
    x = 10
    x += 5
    #it is same as x = x + 5
    x -= 5
    x *= 5
    x /= 5
    #similarly we can write all assignment operators like this.
    
    

    Comparison operators

    Comparison operators are used to compare two values. Following are the comparison operators that we have in python.

    comparison operators-operators in python-edureka

    
    x = 5
    y = 3
    
    #equal
    x == 5
    
    #not equal
    x != 5
    
    #greater than
    x &gt; y
    
    #less than
    x &lt; y #greater than or equal to x &gt;= y
    
    #less than or equal to
    x &lt;= y
    
    

    Logical operators

    Logical operators are used to compare two conditional statements. Following are the logical operators that we have in python.

    logical operators-operators in python-edureka

    
    #logical and
    5 &gt; 3 and 5 &gt; 4
    #it will return true, since both statements are true.
    5 &gt; 3 or 5 &lt; 2
    #it will return true, since one of the statements is true.
    not(5 &lt; 2 and 5 &gt; 3)
    #it will return true, even when logical and will return false.
    
    

    Identity operators

    Identity operators compare two objects. Following are the identity operators that we have in python.

    identity operators-operators in python-edureka

    
    a = [10,20,30]
    b = [10,20,30]
    x = b
    z = a
    # is operator
    x is a
    #this will return false
    x is z
    #this will return true.
    a is b
    #this will return false, even though both have the same items in the list.
    a is not b
    #this will return true, since both are not same objects.
    
    

    Membership operators

    Membership operators are used to check if a sequence is present in an object. Following are the membership operators that we have in python.

    membership operators-operators in python-edureka

    
    a = [10,20,30,'edureka']
    #in operator
    'edureka' in a
    #this will return true, since the item is present in the object.
    'python' in a
    #this will return false, since it is not present in a.
    10 not in a
    #this will return false, because it is there.
    50 not in a
    #this will return true, since there is no 50 in a.
    
    

    Bitwise operators

    Bitwise operators compare the binary values. Following are the bitwise operators that we have in python.

    bitwise -operators in python-edureka

    
    #bitwise AND
    10 &amp; 12
    #this will return 8
    #bitwise OR
    10 | 12
    #this will return 14
    #bitwise XOR
    10 ^ 12
    #this will return 6
    #bitwise NOT
    ~ (10 &amp; 12)
    #this will return -9
    #left shift
    10 &lt;&lt; 2 #this will return 40 #right shift 10 &gt;&gt; 2
    #this will return 2
    
    

    To understand how we got the result using the bitwise operators lets take a look at the binary equivalent of 10 and 12.

    10 in binary is 1010 and 12 in binary is 1100. When doing an AND operation between 1010 and 1100, the bit will be 1 if both the bits are 1. Therefore, the resultant binary equivalent will be 1000 which is 8 when we convert it to decimal.

    Bitwise OR operator will set each bit to 1 if one of the bits is 1, bitwise XOR will set each bit to 1 if only one of the bits is 1 and bitwise not will invert all bits.

    When doing a left shift or a right shift, the bits will shift left 2 places in our example. Therefore 1010 will become 101000 which is 40. Similarly, when doing right shift 1010 will become 10, which is 2.

    In this blog, we have discussed different types of operators in python. This topic is a fundamental concept for learning python programming language. It is a core python concept that is necessary while moving to various other domains in python. If you are looking for a structured learning approach towards python programming, you can enroll for Edureka’s Python Certification Program to kick-start your learning.

    If you have any queries, mention them in the comments section. We will get back to you. 

    The post Operators In Python – All You Need To Know appeared first on Edureka.

    20 Linux Commands You’ll Actually Use In Your Life

    $
    0
    0

    Linux users and administrators can’t really live by the GUI alone. By only learning how to work with your tool, can you get the most out of Linux. Hence, we’ve brought together a list of useful Linux commands into this convenient guide, which will be of help no matter which Linux Curriculum you choose to learn from. 

    So, I’ve categorized these commands into the following segments;

    Linux Commands: Basic Commands 

    Linux provides a CLI (Command Line Interface) to communicate with the OS. Here are the most basic of the Linux Commands.

    1. pwd

    This command Displays the current working directory of the terminal.

    syntax:

    $ pwd

    pwd - linux commands - edureka2. echo

    This command writes its arguments to standard output.

    syntax:

    $ echo "<text>"

    echo - linux commands - edureka3. su

    This command is used to switch to root-user so that superuser permissions can be used to execute commands.

    syntax:

    $ su

    su - linux commands - edureka4. su <username>

    This command is used to switch to a different user whose name is passed as the argument.

    syntax:

    $ su <username>

    su user - linux commands - edureka5. sudo

    This command executes only that command with root/ superuser privileges.

    syntax:

    $ sudo <command>

    Command Explanation
    sudo useradd <username>

    Adding a new user

    sudo passwd <username> Setting a password for the new user
    sudo userdel <username>  Deleting the user
    sudo groupadd <groupname> Adding a new group
    sudo groupdel <groupname>  Deleting the  group
    sudo usermod -g <groupname> <username> Adding a user to a primary group

    6. clear

    This command is used to clear the terminal screen. Contents will not actually be deleted in this case, only scrolled down. You can also clear the screen by pressing Ctrl+L on the keyboard.

    syntax:

    $ clear

    Linux Commands: Working with Files

    7. cp 

    This command copies files and directories. A copy of the file/directory copied, still remains in the working directory.

    syntax:

    $ cp <flag> {filename} /pathname/

    cp - linux commands - edureka

    Command Explanation
    cp -i Enters interactive mode; CLI asks before overwriting files
    cp -n Does not overwrite the file
    cp -u Updates the destination file only when the source file is different from the destination file
    cp -R Recursive copy for copying directories; Copies even hidden files
    cp -v Verbose; Prints informative messages

    8. mv

    This command moves files and directories from one directory to another. The file/directory once moved, is deleted from the working directory. 

    syntax:

    $ mv <flag> {filename} /pathname/

    mv - linux commands - edureka

    Command Explanation
    mv -i Enters interactive mode; CLI asks before overwriting files
    mv -u Updates the destination file only when the source file is different from the destination file
    mv -v Verbose; Prints source and destination files

    9. rm

    This command removes files from a directory. By default, the rm command does not remove directories. Once removed, the contents of a file cannot be recovered.

    syntax:

    $ rm <flag> {filename} 

    rm - linux commands - edureka

    Command Explanation
    rm –r Removes even non-empty directories.
    rm –rp Removes non-empty directories including parent and subdirectories.

    10. grep

    This command is used to search for a particular string/ word in a text file. This is similar to “Ctrl+F”, but executed via a CLI.

    syntax:

    $ grep <flag or element_to_search> {filename}

    grep - linux commands - edureka

    Command Explanation
    grep -i Returns the results for case insensitive strings
    grep -n Returns the matching strings along with their line number
    grep -v Returns the result of lines not matching the search string
    grep -c Returns the number of lines in which the results matched the search string

    Linux Commands | Edureka

    11. cat

    This command can read, modify or concatenate text files. It also displays file contents.

    syntax:

    $ cat <flag> {filename}

    cat - linux commands - edureka

    Command Explanation
    cat -b This is used to add line numbers to non-blank lines
    cat -n This is used to add line numbers to all lines
    cat -s This is used to squeeze blank lines into one line
    cat –E Show $ at the end of line

    Linux Commands: Working with Directories

    12. ls

    This command lists all the contents in the current working directory.

    syntax:

    $ ls <flag>
    ls - linux commands - edureka

    Command Explanation
    ls <path name> By specifying the path after ls, the content in that path will be displayed
    ls –l Using ‘l’ flag, lists all the contents along with its owner settings, permissions & time stamp (long format)
    ls –a Using ‘a’ flag, lists all the hidden contents in the specified directory
    ls –author Using ‘–author’ flag, lists the contents in the specified directory along with its owner
    ls –S Using ‘a’ flag, sorts and lists all the contents in the specified directory by size
    ls *.html Using ‘*’ flag, lists only the contents in the directory of a particular format
    ls –lS > file.txt Using ‘>’ flag, copies the result of ls command into a text file

    13. cd

    This command is used to change the current working directory of the user.

    syntax:

    $ cd /pathname/

    cd - linux commands - edureka

    Command Explanation
    cd ~ This command also changes the directory to home directory
    cd / Changes the directory to root directory
    cd .. Changes the directory to its parent directory
    cd ‘xx yy’ We specify the folder name in inverted commas because there is a space in the folder name

    14. sort 

    This command sorts the results of a search either alphabetically or numerically. Files, file contents and directories can be sorted using this command.

    syntax:

    $ sort <flag> {filename}

    sort - linux commands - edureka

    Command Explanation
    sort -r the flag returns the results in reverse order;
    sort -f the flag does case insensitive sorting
    sort -n the flag returns the results as per numerical order

    15. mkdir

    This command is used to create a new directory.

    syntax:

    $ mkdir <flag> {directoryname} /pathname/

    mkdir - linux commands - edureka

    Command Explanation
    mkdir -p Creates both a new parent directory and a sub-directory
    mkdir –p  <filename1>/{f1,f2,f3} This is used to create multiple subdirectories inside the new parent directory

    16. rmdir

    This command is used to remove a specified directory. Although by default, it can only remove an empty directory, there are flags which can be deployed to delete the non-empty directories as well.

    syntax:

    $ rmdir <flag> {directoryname} 

    rmdir - linux commands - edureka

    Command Explanation
    rmdir –p Removes both the parent and child directory
    rmdir –pv Removes all the parent and subdirectories along with the verbose.

    Linux Commands: Working with User Permissions

    17. chmod

    This command is used to change the access permissions of files and directories. Consider the example below.

    chmod script - linux commands - edureka

    On trying to run the newly created file named chmodtest.sh, an error is thrown. After modifying the permissions of the file using the said Linux command, it turns executable.

    syntax:

    $ chmod <permissions of user,group,others> {filename}

    chmod - linux commands - edurekaThe permissions associated with each digit is as follows.

    Number read write  execute
    0
    1 yes
    2 yes
    3 yes yes
    4 yes
    5 yes yes
    6 yes yes
    7 yes yes yes

     

    Linux Commands: Installing Packages

    Stable versions of most software’s will already be available in Linux repositories. Here are the Linux Commands to install them.

    18. install packages

    For an RHEL based system;

    syntax:

    $ sudo yum install package-name

    For a Debian based system;

    syntax:

    $ sudo apt-get install package-name

    For a Fedora based system;

    syntax:

    $ sudo dnf install package-name

    Linux Commands: Working with Zipped Files

    When you download a package from the internet, the downloaded file comes in compressed form. Here are a few commands to decompress and compress files in Linux.

    19. tar

    The following command is used to zip files of .tar format.

    syntax:

    $ tar –cvf tar-filename source-folder-name

    The following command is used to unzip files of .tar format.

    syntax:

    $ tar –xvf tar-file-name

    Linux Commands: Working with Secure Shell For Remote Machine Access

    20. ssh

    This command refers to a cryptographic network protocol for operating network services securely over an unsecured network. Typical use-cases include remote command-line execution, but any network service can be secured with SSH.

    The following command, on running at the slave node, will give remote access to the master.

    syntax:

    $ ssh <master's ip>

    The following command, on running at the master, will give remote access to the slave node.

    syntax:

    $ ssh <slave's ip>

    So, there you have it. All the Linux commands you’re sure to use in your day-to-day IT-life.

    Want to know more about the Commands in Linux? You could log on to www.edureka.co/linux-admin. Edureka’s Linux Administration Certification training is curated to shape your career as a Linux professional & help you to run applications, perform desired functions on your system and networks, create a network configuration, and maintain security administration.

    The post 20 Linux Commands You’ll Actually Use In Your Life appeared first on Edureka.

    TensorFlow Image Classification : Build your own Classifier

    $
    0
    0

    Image Classification a task which even a baby can do in seconds, but for a machine, it has been a tough task until the recent advancements in Artificial Intelligence and Deep Learning. Self-driving cars can detect objects and take required action in real-time and most of this is possible because of TensorFlow Image Classification. In this article, I’ll guide you through the following topics:

     

    What is TensorFlow?

    TensorFlow is Google’s Open Source Machine Learning Framework for dataflow programming across a range of tasks. Nodes in the graph represent mathematical operations, while the graph edges represent the multi-dimensional data arrays communicated between them.

    TensorFlow-Image-Recognition
    Tensors are just multidimensional arrays, an extension of 2-dimensional tables to data with a higher dimension. There are many features of Tensorflow which makes it appropriate for Deep Learning and it’s core open source library helps you develop and train ML models.

     

    What is Image Classification?

    The intent of Image Classification is to categorize all pixels in a digital image into one of several land cover classes or themes.  This categorized data may then be used to produce thematic maps of the land cover present in an image.

    Tensorflow-image-classification

    Now Depending on the interaction between the analyst and the computer during classification, there are two types of classification:

    • Supervised &
    • Unsupervised

    So, without wasting any time let’s jump into TensorFlow Image Classification. I have 2 examples: easy and difficult. Let’s proceed with the easy one.

     

    TensorFlow Image Classification: Fashion MNIST

    Fashion_MNIST_sample

    Importing Fashion MNIST

    Here we are going to use Fashion MNIST Dataset, which contains 70,000 grayscale images in 10 categories. We will use 60000 for training and the rest 10000 for testing purposes. You can access the Fashion MNIST directly from TensorFlow, just import and load the data.

    • Let’s import the libraries first
    from __future__ import absolute_import, division, print_function
    # TensorFlow and tf.keras
    
    import tensorflow as tf
    from tensorflow import keras
    
    # Helper libraries
    
    import numpy as np
    import matplotlib.pyplot as plt
    

     

    • Let’s load the data
    fashion_mnist = keras.datasets.fashion_mnist
    
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
    

     

    • Next, we are going to map the images into classes
    class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    

     

    • Exploring the data
    train_images.shape
    #Each Label is between 0-9
    train_labels
    test_images.shape

     

    • Now, it’s time to pre-process the data.
    plt.figure()
    plt.imshow(train_images[0])
    plt.colorbar()
    plt.grid(False)
    plt.show()
    #If you inspect the first image in the training set, you will see that the pixel values fall in the range of 0 to 255.

     

    boot-tensorflow-image-classification

     

    • We have to scale the images from 0-1 to feed it into the Neural Network
    train_images = train_images / 255.0
    
    test_images = test_images / 255.0

     

    • Let’s display some images.
    plt.figure(figsize=(10,10))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(train_images[i], cmap=plt.cm.binary)
        plt.xlabel(class_names[train_labels[i]])
    plt.show()
     

     

    25-images

     

    • Setup the layers
    model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28, 28)),
        keras.layers.Dense(128, activation=tf.nn.relu),
        keras.layers.Dense(10, activation=tf.nn.softmax)
    ])

     

     

    • Compile the Model
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

     

     

    • Model Training
    model.fit(train_images, train_labels, epochs=10)

     

     

    epochs-tensorflow-image-classification

     

    • Evaluating Accuracy
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    
    print('Test accuracy:', test_acc)

     

    test-accuracy

    • Making Predictions
    predictions = model.predict(test_images)
    
    predictions[0]

     

    array

     

    • A prediction is an array of 10 numbers. These describe the “confidence” of the model that the image corresponds to each of the 10 different articles of clothing. We can see which label has the highest confidence value.
    np.argmax(predictions[0])
    #Model is most confident that it's an ankle boot. Let's see if it's correct

    Output: 9

     

    test_labels[0]

    Output: 9

     

    • Now, it’s time to look at the full set of 10 channels
    def plot_image(i, predictions_array, true_label, img):
      predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
      plt.grid(False)
      plt.xticks([])
      plt.yticks([])
    
      plt.imshow(img, cmap=plt.cm.binary)
    
      predicted_label = np.argmax(predictions_array)
      if predicted_label == true_label:
        color = 'green'
      else:
        color = 'red'
    
      plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                    100*np.max(predictions_array),
                                    class_names[true_label]),
                                    color=color)
    
    def plot_value_array(i, predictions_array, true_label):
      predictions_array, true_label = predictions_array[i], true_label[i]
      plt.grid(False)
      plt.xticks([])
      plt.yticks([])
      thisplot = plt.bar(range(10), predictions_array, color="#777777")
      plt.ylim([0, 1])
      predicted_label = np.argmax(predictions_array)
    
      thisplot[predicted_label].set_color('red')
      thisplot[true_label].set_color('green')

     

    • Let’s look at the 0th and 10th image first
    i = 0
    plt.figure(figsize=(6,3))
    plt.subplot(1,2,1)
    plot_image(i, predictions, test_labels, test_images)
    plt.subplot(1,2,2)
    plot_value_array(i, predictions,  test_labels)
    plt.show()

    ankle-tensorflow-image-classificatiion

     

    i = 10
    plt.figure(figsize=(6,3))
    plt.subplot(1,2,1)
    plot_image(i, predictions, test_labels, test_images)
    plt.subplot(1,2,2)
    plot_value_array(i, predictions,  test_labels)
    plt.show()

    coat

     

    • Now, let’s plot several images and their predictions. Correct ones are green, while the incorrect ones are red.
    num_rows = 5
    num_cols = 3
    num_images = num_rows*num_cols
    plt.figure(figsize=(2*2*num_cols, 2*num_rows))
    for i in range(num_images):
      plt.subplot(num_rows, 2*num_cols, 2*i+1)
      plot_image(i, predictions, test_labels, test_images)
      plt.subplot(num_rows, 2*num_cols, 2*i+2)
      plot_value_array(i, predictions, test_labels)
    plt.show()

     

    op-tensorflow-image-classification

     

    • Finally, we will use the trained model to make a prediction about a single image.

    []

    # Grab an image from the test dataset
    img = test_images[0]
    
    print(img.shape)
    
    # Add the image to a batch where it's the only member.
    img = (np.expand_dims(img,0))
    
    print(img.shape)
    predictions_single = model.predict(img) 
    print(predictions_single)

     

    pred-array

     

    plot_value_array(0, predictions_single, test_labels)
    plt.xticks(range(10), class_names, rotation=45)
    plt.show()

     

    prediction-single-image

    • As you can see the prediction for our only image in batch.
    prediction_result = np.argmax(predictions_single[0])

    Output: 9

     

    CIFAR-10: CNN

    cifar-10

    The CIFAR-10 dataset consists of airplanes, dogs, cats, and other objects. You’ll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. This use-case will surely clear your doubts about TensorFlow Image Classification.

    • Downloading the Data
    from urllib.request import urlretrieve
    from os.path import isfile, isdir
    from tqdm import tqdm 
    import tarfile
    
    cifar10_dataset_folder_path = 'cifar-10-batches-py'
    
    class DownloadProgress(tqdm):
        last_block = 0
    
        def hook(self, block_num=1, block_size=1, total_size=None):
            self.total = total_size
            self.update((block_num - self.last_block) * block_size)
            self.last_block = block_num
    
    """ 
        check if the data (zip) file is already downloaded
        if not, download it from "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" and save as cifar-10-python.tar.gz
    """
    if not isfile('cifar-10-python.tar.gz'):
        with DownloadProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:
            urlretrieve(
                'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
                'cifar-10-python.tar.gz',
                pbar.hook)
    
    if not isdir(cifar10_dataset_folder_path):
        with tarfile.open('cifar-10-python.tar.gz') as tar:
            tar.extractall()
            tar.close()

     

    • Importing Necessary Libraries
    import pickle
    import numpy as np
    import matplotlib.pyplot as plt

     

    • Understanding the Data

    The original batch of Data is 10000×3072 tensor expressed in a numpy array, where 10000 is the number of sample data. The image is colored and of size 32×32. Feeding can be done either in a format of (width x height x num_channel) or (num_channel x width x height). Let’s define the labels.

    def load_label_names():
        return ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

     

    • Reshaping the Data

    We are going to reshape the data in two stages

    Firstly, divide the row vector (3072) into 3 pieces. Each piece corresponds to each channel. This results in (3 x 1024) dimension of a tensor. Then Divide the resulting tensor from the previous step with 32.  32 here means the width of an image. This results in (3x32x32).

    Secondly, we have to transpose the data from (num_channel, width, height) to (width, height, num_channel).  For that, we are going to use the transpose function.

    Reshape and Transpose

     

    def load_cfar10_batch(cifar10_dataset_folder_path, batch_id):
        with open(cifar10_dataset_folder_path + '/data_batch_' + str(batch_id), mode='rb') as file:
            # note the encoding type is 'latin1'
            batch = pickle.load(file, encoding='latin1')
            
        features = batch['data'].reshape((len(batch['data']), 3, 32, 32)).transpose(0, 2, 3, 1)
        labels = batch['labels']
            
        return features, label

     

    • Exploring the Data
    def display_stats(cifar10_dataset_folder_path, batch_id, sample_id):
        features, labels = load_cfar10_batch(cifar10_dataset_folder_path, batch_id)
        
        if not (0 <= sample_id < len(features)):
            print('{} samples in batch {}.  {} is out of range.'.format(len(features), batch_id, sample_id))
            return None
    
        print('\nStats of batch #{}:'.format(batch_id))
        print('# of Samples: {}\n'.format(len(features)))
        
        label_names = load_label_names()
        label_counts = dict(zip(*np.unique(labels, return_counts=True)))
        for key, value in label_counts.items():
            print('Label Counts of [{}]({}) : {}'.format(key, label_names[key].upper(), value))
        
        sample_image = features[sample_id]
        sample_label = labels[sample_id]
        
        print('\nExample of Image {}:'.format(sample_id))
        print('Image - Min Value: {} Max Value: {}'.format(sample_image.min(), sample_image.max()))
        print('Image - Shape: {}'.format(sample_image.shape))
        print('Label - Label Id: {} Name: {}'.format(sample_label, label_names[sample_label]))
        
        plt.imshow(sample_image)

     

    %matplotlib inline
    %config InlineBackend.figure_format = 'retina'
    
    import numpy as np
    
    # Explore the dataset
    batch_id = 3
    sample_id = 7000
    display_stats(cifar10_dataset_folder_path, batch_id, sample_id)

     

    batch-op-tensorflow-image-classification

     

    • Implementing Preprocessing Functions

    We are going to Normalize the data via Min-Max Normalization. This simply makes all x values to range between 0 and 1.
    y = (x-min) / (max-min)

    def normalize(x):
        """
            argument
                - x: input image data in numpy array [32, 32, 3]
            return
                - normalized x 
        """
        min_val = np.min(x)
        max_val = np.max(x)
        x = (x-min_val) / (max_val-min_val)
        return x

     

    • One-Hot Encode
    def one_hot_encode(x):
        """
            argument
                - x: a list of labels
            return
                - one hot encoding matrix (number of labels, number of class)
        """
        encoded = np.zeros((len(x), 10))
        
        for idx, val in enumerate(x):
            encoded[idx][val] = 1
        
        return encoded

     

    • Preprocess and Save the Data
    def _preprocess_and_save(normalize, one_hot_encode, features, labels, filename):
        features = normalize(features)
        labels = one_hot_encode(labels)
    
        pickle.dump((features, labels), open(filename, 'wb'))
    
    
    def preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode):
        n_batches = 5
        valid_features = []
        valid_labels = []
    
        for batch_i in range(1, n_batches + 1):
            features, labels = load_cfar10_batch(cifar10_dataset_folder_path, batch_i)
            
            # find index to be the point as validation data in the whole dataset of the batch (10%)
            index_of_validation = int(len(features) * 0.1)
    
            # preprocess the 90% of the whole dataset of the batch
            # - normalize the features
            # - one_hot_encode the lables
            # - save in a new file named, "preprocess_batch_" + batch_number
            # - each file for each batch
            _preprocess_and_save(normalize, one_hot_encode,
                                 features[:-index_of_validation], labels[:-index_of_validation], 
                                 'preprocess_batch_' + str(batch_i) + '.p')
    
            # unlike the training dataset, validation dataset will be added through all batch dataset
            # - take 10% of the whold dataset of the batch
            # - add them into a list of
            #   - valid_features
            #   - valid_labels
            valid_features.extend(features[-index_of_validation:])
            valid_labels.extend(labels[-index_of_validation:])
    
        # preprocess the all stacked validation dataset
        _preprocess_and_save(normalize, one_hot_encode,
                             np.array(valid_features), np.array(valid_labels),
                             'preprocess_validation.p')
    
        # load the test dataset
        with open(cifar10_dataset_folder_path + '/test_batch', mode='rb') as file:
            batch = pickle.load(file, encoding='latin1')
    
        # preprocess the testing data
        test_features = batch['data'].reshape((len(batch['data']), 3, 32, 32)).transpose(0, 2, 3, 1)
        test_labels = batch['labels']
    
        # Preprocess and Save all testing data
        _preprocess_and_save(normalize, one_hot_encode,
                             np.array(test_features), np.array(test_labels),
                             'preprocess_training.p')

     

    preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)

     

    • Checkpoint
    import pickle
    
    valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))

     

    • Building the Network

    The entire model consists of 14 layers in total.

    CNN-TensorFlow-Image-Recognition

    import tensorflow as tf
    
    def conv_net(x, keep_prob):
        conv1_filter = tf.Variable(tf.truncated_normal(shape=[3, 3, 3, 64], mean=0, stddev=0.08))
        conv2_filter = tf.Variable(tf.truncated_normal(shape=[3, 3, 64, 128], mean=0, stddev=0.08))
        conv3_filter = tf.Variable(tf.truncated_normal(shape=[5, 5, 128, 256], mean=0, stddev=0.08))
        conv4_filter = tf.Variable(tf.truncated_normal(shape=[5, 5, 256, 512], mean=0, stddev=0.08))
    
        # 1, 2
        conv1 = tf.nn.conv2d(x, conv1_filter, strides=[1,1,1,1], padding='SAME')
        conv1 = tf.nn.relu(conv1)
        conv1_pool = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
        conv1_bn = tf.layers.batch_normalization(conv1_pool)
    
        # 3, 4
        conv2 = tf.nn.conv2d(conv1_bn, conv2_filter, strides=[1,1,1,1], padding='SAME')
        conv2 = tf.nn.relu(conv2)
        conv2_pool = tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')    
        conv2_bn = tf.layers.batch_normalization(conv2_pool)
      
        # 5, 6
        conv3 = tf.nn.conv2d(conv2_bn, conv3_filter, strides=[1,1,1,1], padding='SAME')
        conv3 = tf.nn.relu(conv3)
        conv3_pool = tf.nn.max_pool(conv3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')  
        conv3_bn = tf.layers.batch_normalization(conv3_pool)
        
        # 7, 8
        conv4 = tf.nn.conv2d(conv3_bn, conv4_filter, strides=[1,1,1,1], padding='SAME')
        conv4 = tf.nn.relu(conv4)
        conv4_pool = tf.nn.max_pool(conv4, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
        conv4_bn = tf.layers.batch_normalization(conv4_pool)
        
        # 9
        flat = tf.contrib.layers.flatten(conv4_bn)  
    
        # 10
        full1 = tf.contrib.layers.fully_connected(inputs=flat, num_outputs=128, activation_fn=tf.nn.relu)
        full1 = tf.nn.dropout(full1, keep_prob)
        full1 = tf.layers.batch_normalization(full1)
        
        # 11
        full2 = tf.contrib.layers.fully_connected(inputs=full1, num_outputs=256, activation_fn=tf.nn.relu)
        full2 = tf.nn.dropout(full2, keep_prob)
        full2 = tf.layers.batch_normalization(full2)
        
        # 12
        full3 = tf.contrib.layers.fully_connected(inputs=full2, num_outputs=512, activation_fn=tf.nn.relu)
        full3 = tf.nn.dropout(full3, keep_prob)
        full3 = tf.layers.batch_normalization(full3)    
        
        # 13
        full4 = tf.contrib.layers.fully_connected(inputs=full3, num_outputs=1024, activation_fn=tf.nn.relu)
        full4 = tf.nn.dropout(full4, keep_prob)
        full4 = tf.layers.batch_normalization(full4)        
        
        # 14
        out = tf.contrib.layers.fully_connected(inputs=full3, num_outputs=10, activation_fn=None)
        return out

     

    • Hyperparameters
    epochs = 10
    batch_size = 128
    keep_probability = 0.7
    learning_rate = 0.001

     

    logits = conv_net(x, keep_prob)
    model = tf.identity(logits, name='logits') # Name logits Tensor, so that can be loaded from disk after training
    
    # Loss and Optimizer
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
    
    # Accuracy
    correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')

     

    • Train the Neural Network
    #Single Optimization
    def
    train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): session.run(optimizer, feed_dict={ x: feature_batch, y: label_batch, keep_prob: keep_probability })

     

    #Showing Stats
    def print_stats(session, feature_batch, label_batch, cost, accuracy):
        loss = sess.run(cost, 
                        feed_dict={
                            x: feature_batch,
                            y: label_batch,
                            keep_prob: 1.
                        })
        valid_acc = sess.run(accuracy, 
                             feed_dict={
                                 x: valid_features,
                                 y: valid_labels,
                                 keep_prob: 1.
                             })
        
        print('Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(loss, valid_acc))

     

     

    • Fully Training and Saving the Model
    def batch_features_labels(features, labels, batch_size):
        """
        Split features and labels into batches
        """
        for start in range(0, len(features), batch_size):
            end = min(start + batch_size, len(features))
            yield features[start:end], labels[start:end]
    
    def load_preprocess_training_batch(batch_id, batch_size):
        """
        Load the Preprocessed Training data and return them in batches of <batch_size> or less
        """
        filename = 'preprocess_batch_' + str(batch_id) + '.p'
        features, labels = pickle.load(open(filename, mode='rb'))
    
        # Return the training data in batches of size <batch_size> or less
        return batch_features_labels(features, labels, batch_size)

     

     

     

    #Saving Model and Path
    save_model_path
    = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path)

    train-epochs-1

    train-epochs-2

    Now, the important part of Tensorflow Image Classification is done. Now, it’s time to test the model.

     

    • Testing the Model
    import pickle
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.preprocessing import LabelBinarizer
    
    def batch_features_labels(features, labels, batch_size):
        """
        Split features and labels into batches
        """
        for start in range(0, len(features), batch_size):
            end = min(start + batch_size, len(features))
            yield features[start:end], labels[start:end]
    
    def display_image_predictions(features, labels, predictions, top_n_predictions):
        n_classes = 10
        label_names = load_label_names()
        label_binarizer = LabelBinarizer()
        label_binarizer.fit(range(n_classes))
        label_ids = label_binarizer.inverse_transform(np.array(labels))
    
        fig, axies = plt.subplots(nrows=top_n_predictions, ncols=2, figsize=(20, 10))
        fig.tight_layout()
        fig.suptitle('Softmax Predictions', fontsize=20, y=1.1)
    
        n_predictions = 3
        margin = 0.05
        ind = np.arange(n_predictions)
        width = (1. - 2. * margin) / n_predictions
       
        for image_i, (feature, label_id, pred_indicies, pred_values) in enumerate(zip(features, label_ids, predictions.indices, predictions.values)):
            if (image_i < top_n_predictions):
                pred_names = [label_names[pred_i] for pred_i in pred_indicies]
                correct_name = label_names[label_id]
                
                axies[image_i][0].imshow((feature*255).astype(np.int32, copy=False))
                axies[image_i][0].set_title(correct_name)
                axies[image_i][0].set_axis_off()
    
                axies[image_i][1].barh(ind + margin, pred_values[:3], width)
                axies[image_i][1].set_yticks(ind + margin)
                axies[image_i][1].set_yticklabels(pred_names[::-1])
                axies[image_i][1].set_xticks([0, 0.5, 1.0])

     

    %matplotlib inline
    %config InlineBackend.figure_format = 'retina'
    
    import tensorflow as tf
    import pickle
    import random
    
    save_model_path = './image_classification'
    batch_size = 64
    n_samples = 10
    top_n_predictions = 5
    
    def test_model():
        test_features, test_labels = pickle.load(open('preprocess_training.p', mode='rb'))
        loaded_graph = tf.Graph()
    
        with tf.Session(graph=loaded_graph) as sess:
            # Load model
            loader = tf.train.import_meta_graph(save_model_path + '.meta')
            loader.restore(sess, save_model_path)
    
            # Get Tensors from loaded model
            loaded_x = loaded_graph.get_tensor_by_name('input_x:0')
            loaded_y = loaded_graph.get_tensor_by_name('output_y:0')
            loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
            loaded_logits = loaded_graph.get_tensor_by_name('logits:0')
            loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')
            
            # Get accuracy in batches for memory limitations
            test_batch_acc_total = 0
            test_batch_count = 0
            
            for train_feature_batch, train_label_batch in batch_features_labels(test_features, test_labels, batch_size):
                test_batch_acc_total += sess.run(
                    loaded_acc,
                    feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})
                test_batch_count += 1
    
            print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count))
    
            # Print Random Samples
            random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))
            random_test_predictions = sess.run(
                tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),
                feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})
            display_image_predictions(random_test_features, random_test_labels, random_test_predictions, top_n_predictions)
    
    
    test_model()

     

    Output: Testing Accuracy: 0.5882762738853503

    predictions-TensorFlow-Image-Classification

     

    Now, if you train your neural network for more epochs or change the activation function, you might get a different result that might have better accuracy.

    So, with this, we come to an end of this TensorFlow Image Classification article. I’m sure you can now use the same to classify any sort of images and you’re not a beginner to image classification.

    Edureka’s Deep Learning in TensorFlow with Python Certification Training is curated by industry professionals as per the industry requirements & demands. You will master the concepts such as SoftMax function, Autoencoder Neural Networks, Restricted Boltzmann Machine (RBM), Keras & TFLearn. The course has been specially curated by industry experts with real-time case studies.

    The post TensorFlow Image Classification : Build your own Classifier appeared first on Edureka.

    Automation Anywhere Examples – Top Examples That You Can Practice

    $
    0
    0

    What is Automation? How to automate tasks using RPA Tools? What are the Automation Anywhere Examples?

    I believe you might have wondered the answers to these questions. Well, with UiPath, Blue Prism or Automation Anywhere, you can easily automate multiple tasks with few action commands. In this article on Automation Anywhere Examples, I am going to discuss the top automation examples that will help you automate tedious tasks. This will help you upskill your career as an RPA Certified Professional and standout in today’s market.

    The following topics will be covered in this article:

    So let’s get started!

    What is Automation Anywhere?

    Automation Anywhere is an RPA tool which aims to provide its users with scalable, secure and resilient services. It offers better performance as it has the ability to integrate into multiple platforms and also scale simultaneously. You can also summarize this tool as a summation of Robotic Process Automation, Cognitive Analytics, and Workforce Analytics. Refer to the image below.

    Automation Anywhere - Automation Anywhere Examples - EdurekaApart from this, Automation Anywhere has recently launched a Community Edition / Free Trial version which is free for lifetime and offers an Enterprise Edition which you can use with a 30 Day Free Trial.

    Now, next in this article on Automation Anywhere Examples, let us look into the features of Automation Anywhere.

    Automation Anywhere Features

    The features of Automation Anywhere are as you can refer from the below image:

    Automation Anywhere Features - Automation Anywhere Examples - Edureka

    Now, that you know what is Automation Anywhere, let us next look into the various automation examples.

    Examples of Automation Anywhere

    For your better understanding, I have divided the examples to be shown in the following two sections:

    Basic Automation Anywhere Commands

    This section of the article on Automation Anywhere Examples will consist of the basic commands and different kinds of automation which will help you learn the tool better.

    So, let us get started.

    Windows Actions

    The Windows Actions are used to automate tasks such as opening/closing/minimizing/maximizing a window and even getting the Active Window Title.

    Problem Statement:

    To automate the action of getting the title of an active window.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag the Get Active Window Title command into your workspace.

    Step 2: Assign a variable. Here, I will assign the Clipboard system variable. Click on Save.

    Step 3: Drag a Message Box and mention the Clipboard variable to display the output. Click on Save. Refer to the below image.

    Automation Anywhere Windows Action - Automation Anywhere Examples - EdurekaStep 4: Save and Execute the task.

    When you execute the task, you will see that the active window title will be displayed. Here the output is Run Time Window as you can see below.

    Automation Anywhere Windows Action Output - Automation Anywhere Examples - EdurekaNow, this was just one command guys, you can use the other commands to open/close/resize a window by dragging your mouse over the window.

    Mouse Clicks

    The Mouse Clicks are used to automate the tasks which are related to clicking at a specific position on the application or a window

    Problem Statement:

    To automate the action of closing a notepad window.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag the Insert Mouse Click command into your workspace.

    Step 2: Select the window on which you want to click. Here I want to click on the Notepad window.

    Step 3: Now click on Capture and hover your mouse over the area where you want to click. Here I want to click on the Close symbol.

    Step 4: Now, click on Save. Refer to the below image.

    Automation Anywhere Mouse Clicks- Automation Anywhere Examples - EdurekaStep 5: Save and Execute the task.

    When you execute the task, you will see that the notepad window is closed automatically.

    String Operations

    The String operations like in any other programming knowledge are used to perform various operations such as comparing two strings, replacing a string, finding a length of the string, reversing a string, splitting a string and so on.

    Problem Statement:

    To automate the task of replacing a few characters from a string.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and assign the source strings, find and replace values to three different variables.

    Step 2: Now, drag the Replace command from the String Operation section.

    Step 3: In the source string section mention the initial string or the variable assigned to store the initial string.

    Step 4: In the find and the replace section mention the find and the replace strings or the variables assigned to it.

    Step 5: Assign the output variable. Here I have assigned the output to Clipboard variable. Now, click on Save. Refer to the below image.

    Automation Anywhere String Operation - Automation Anywhere Examples - Edureka

    NOTE: Here our source string is edureka. Find value will be ‘reka’ and we have to replace it with ‘tech’.

    Step 6: Drag a Message Box and mention the Clipboard variable to display the output. Click on Save.

    Step 7: Save and Execute your task.

    When you execute the task, you will see that the string is replaced as below.

    Automation Anywhere String Operation Output - Automation Anywhere Examples - EdurekaNow, this was just one command guys, you can use the other commands to compare/ find the length/ find a sub-string/ trim and do many other operations on the strings.

    Files & Folders

    The files and folders command deals with the various actions which you can perform with the files or folders like copying/deleting/renaming/moving/zipping/ printing and so on.

    Problem Statement:

    To automate the task of copying the files from a source folder to the destination folder.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and go to the Files/Folders activity. Now, choose the Copy Files action and drag it to your workspace.

    Step 2: Over here choose the option Folder since we wish to move a folder from a source path to the destination path.

    Step 3: Then mention the source path in the Source File section and the Destination path in the Destination path section. Refer below.

    Automation Anywhere Files and Folders - Automation Anywhere Examples - EdurekaStep 4: Save and Execute your task.

    Once you execute the task you will see that files present in a folder in the source path will be moved to the destination path.

    Web Recorders

    The web recorders are used in Automation Anywhere to extract text from the web, find broken links, navigate URL, manage web controls, download file and so on.

    Problem Statement:

    To automate the task of extracting a table from a webpage.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag the Extract Table command.

    Step 2: Now, mention the URL and click on Launch. This will open your website.

    Step 3: Next, click on Capture Table and hover your mouse over the table you wish to extract. Refer below.

    Automation Anywhere Web Recorder - Automation Anywhere Examples - EdurekaStep 4: Next, extract the table data to a CSV file by mentioning the path of the CSV file

    Step 5: You can also click on view extracted table by clicking on the View Extracted Table option. Then, click on Save. Refer below.

    Automation Anywhere Web Recorder Option - Automation Anywhere Examples - EdurekaStep 7: Save and Execute your task.

    When you execute your task, you will observe that the table is extracted and stored into a CSV file as below.

    Automation Anywhere Web Recorders Output - Automation Anywhere Examples - Edureka

    Optical Character Recognition(OCR)

    The optical character recognition aka OCR is used to capture an area, window or capture an image by path or URL.

    Problem Statement:

    To automate the task of extracting a text from a window and displaying the output.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag the Capture Area command from the OCR section.

    Step 2: Now, select the window from where you wish to extract text and choose the OCR Engine. By default, TESSERACT is chosen.

    Step 3: Next, click on Capture Area and drag your mouse over the area from which you wish to extract data. Refer below.

    Automation Anywhere OCR - Automation Anywhere Examples - Edureka

    Step 4: You can also view the Captured Text by clicking on View Captured Text. Then click on Save. Refer below.

    Automation Anywhere OCR Options - Automation Anywhere Examples - EdurekaStep 5: Assign the output to a variable. Here, I am assigning the variable to the Clipboard variable.

    Step 6: Now,  drag and drop a Message Box and mention the output variable to display the output.

    Step 7: Save and Execute the task.

    When you execute the task, you will see that the text is being extracted from the Notepad and is displayed on the Message Box as below.

    Automation Anywhere OCR Output - Automation Anywhere Examples - Edureka

    KeyStrokes

    Keystrokes are used to automate the tasks of writing text into an application. With the help of keystrokes, you can make sure you enter the text in any manner that you wish.

    Problem Statement:

    To automate the task of writing text into a notepad file.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag and drop the Insert Keystrokes command.

    Step 2: Type in your text that you want to display on a notepad using the keystrokes. In the below snapshot I have used ENTER, CAPS LOCK keystroke.

    Automation Anywhere Insert Keystrokes - Automation Anywhere Examples - EdurekaStep 3: Save and Execute the task.

    Once you execute the task you will see the text is automatically mentioned below.

    Automation Anywhere Insert Keystrokes Output - Automation Anywhere Examples - Edureka

    Rest Web Services

    The Rest Web Services are used to automate the task of fetching data from JSON APIs’ and storing it.

    Problem Statement:

    To automate the task of extracting the data from a JSON file and displaying the output in a Message Box.

    Solution:

    Step 1: Open the Automation Anywhere Workbench and drag and drop the REST Web Service command.

    Step 2: Now mention the URL of the JSON API and choose the method as GET.

    Step 3: Now, go to the Response section save the response to a variable.

    Step 4: Drag a Message Box and mention the variable. Refer below.

    Automation Anywhere Rest Web Services - Automation Anywhere Examples - EdurekaStep 5: Save and Execute the task.

    Once you execute the task, you will see the data being extracted from the JSON file and is being displayed on the Message Box. Refer below.

    Automation Anywhere Rest Web Services Output - Automation Anywhere Examples - Edureka

    Now, with this, we come to an end of this section of this article on Automation Anywhere Examples. Next, in this article, I will show you some complex automation like Excel and PDF.

    Complex Examples

    In this section of the article on Automation Anywhere Examples, I will discuss the Excel and PDF automation.

    So, let us get started guys!

    Excel Automation

    Excel Automation is used to tasks related to Excel such as opening/closing a spreadsheet, activating cells, going to a specific cell and so on.

    Problem Statement

    To automate the task of extracting the data from an Excel File according to some condition and storing the extracted data in another File.

    Solution

    Step 1: Open the Automation Anywhere Workbench.

    Before I move forward with the steps, let me show the file from which we are going to extract data and the output file.

    Sample Excel File - Automation Anywhere Examples - Edureka

    Step 2: Now, your next step is to open both the spreadsheets. To do that, drag the Open Spreadsheets command from the Excel section.

    Step 3: Mention the path of the first spreadsheet( from where you have to extract data), check in the box of Contains Header and click on Save. Refer below.

    Automation Anywhere Open Output Spreadsheet - Automation Anywhere Examples - EdurekaStep 4: Repeat the above two steps for the second spreadsheet and change the session name to Default1 so that it doesn’t clash with the session name of the first spreadsheet. Refer below.

    Automation Anywhere Open Spreadsheet - Automation Anywhere Examples - Edureka

    Step 5: Now, drag the Get Cell command and choose the  Get All Cells option. Then, mention the session name to be Default(which is the session name for the first spreadsheet). Then click on Save. Refer below.

    Automation Anywhere Get All Cells - Automation Anywhere Examples - Edureka

    Step 6: Drag the Get All Cells action in between the actions of opening both the spreadsheets. This step will help you get the data from all the cells in the first spreadsheet.

    Your task pane should look like the below image:

    Automation Anywhere Taskpane - Automation Anywhere Examples - Edureka

    Step 7: Now, you have to start a loop. To do that, drag the Each Row in an Excel Dataset command from the loop section. Mention the session name as Default. Then, click on Save. Refer below.

    Automation Anywhere Loop - Automation Anywhere Examples - Edureka

    Step 8: Now, you have to mention the condition based on which you wish to extract data. To do that follow the below steps.

    Step 8.1: Drag and drop the variable command from the If section.

    Step 8.2: Now click on the Edit option and set the condition using the following steps:

    Step 8.2.1: Mention the variable as Excel Column by pressing on CTRL + F2 and then click on Insert. After that mention the value 12 since we want to set a condition on the 12th column of the dataset. Press on OK.

    NOTE: Here the 12th column in the dataset is the Sales column. The condition is to extract data of all those rows whose sales < 10000.

    Step 8.2.2: Now, select the operator. Here I will select the Less Than(<) operator.

    Step 8.2.3: In the value section mention the value 10000 and click on Save. Refer below.

    Automation Anywhere If Clause - Automation Anywhere Examples - Edureka

    Step 9: Next, you have to iterate the loop of filling data for the number of columns present in the dataset. Since 16 columns are present in the dataset, you have to iterate the loop for 16 times. To do that, drag the Times command from the Loop section and mention 16 in the Times section. Then click on Save. Refer below.

    Automation Anywhere Times Loop - Automation Anywhere Examples - Edureka

    Step 10: Now, you have to fill the data into specific cells. To do that you have to set the cell as follows:

    Step 10.1: Drag the Set Cell command from the Excel command and in the Cell Value section mention the variable ExcelColumn and click on Insert. Then mention the Counter variable by pressing on CTRL + F2.  Finally, click on Save.

    Automation Anywhere Times Set Cell Value - Automation Anywhere Examples - Edureka

    Step 11: Next, you have to go to one cell towards the right of the active cell, to store the next extracted data. So, to do that, drag the Go To Cell command from the Excel section and choose One Cell Right. Refer below.

    Automation Anywhere Times One Cell To Right - Automation Anywhere Examples - EdurekaStep 12: Once the data is stored for a specific row, you have to go to the next row to store the next set of data. To do that, you have to go the beginning of a row and one cell below from the active cell.

    Step 12.1: So, to do that, drag the Go To Cell command from the Excel section and choose Beginning of the row. Refer below.

    Automation Anywhere Times Beginning of Row - Automation Anywhere Examples - EdurekaStep 12.2: Again drag the Go To Cell command from the Excel section and choose One Cell Below. Refer below.Automation Anywhere Times One Cell Below - Automation Anywhere Examples - Edureka

    Your final task list should look like below:

    Excel Automation Final Task List - Automation Anywhere Examples - Edureka

    Step 13: Now, click on the Save button, to save your task and execute the task by clicking on the Run button.

    You would see the below output.

    Excel Automation Output - Automation Anywhere Examples - Edureka

    PDF Automation

    The PDF Automation or the PDF Integration command is used in Automation Anywhere to automate tasks on PDFs’ such as merge two documents, extract text, split documents, convert PDF to image, and encrypt/decrypt a document.

    Problem Statement

    To automate the task of extracting the data from multiple PDF documents and storing the data into a CSV file.

    Solution

    Step 1: Open the Automation Anywhere Workbench.

    Step 2: Now choose the PDF from which you want to extract data and also take note of all the fields that you want to extract data. The below snapshots shows the document from which I want to extract data. Here I want to extract RecieptNo, TransactionID, StudentEnrolmentNo, StudentName, Grade, FeeModeofPayment, TotalAmount, DateofPayment.

    Sample PDF - Automation Anywhere Examples - Edureka

    Step 3: Now, go to the Variable Manager on the right-hand side of your Workbench and add the variables for all the fields you want to extract data. Here you have to create 8 variables. Let me show you how to create a single variable. 

    Step 3.1: Click on the Add option. In the dialog box that opens up, mention the name of the variable in the Name field and click on Save. Refer below.

    Automation Anywhere Add Variables - Automation Anywhere Examples - EdurekaStep 3.2: Repeat the above steps to create the other 7 variables.

    Step 4: Now click on the Excel command from the left panel and double click on the Open-Spreadsheet subcommand. This opens a dialog box.

    Step 4.1: Now go to the ellipses button and mention the path of the Excel file where you want to store the extracted data. Then, click on Save. This step will design the task to open an Excel file. Refer below.

    Automation Anywhere Open Spreadsheet - Automation Anywhere Examples - Edureka

    Step 5: Now, you have to make sure that the extracted data is getting filled automatically starting from the A2 Cell. To create an action for this Double-click on the Go-to-cell subcommand and enter A2 in the specific cell section. After that click on Save. Refer below.

    Automation Anywhere Go To Cell - Automation Anywhere Examples - Edureka

    This step will design a task to place your cursor at the A2 cell in the spreadsheet which is open.

    Step 6: Now, you have to start extracting data from the PDF File. To do so follow the below steps.

    Step 6.1: Click on the PDF-Integration command and double-click on the Extract Form Fieldssubcommand.

    Step 6.2: Now click on the ellipses button and choose the PDF file from which you want to extract data.

    Step 6.3: After this, from the Inserted Fields section, choose the Add option and drag the mouse over the required field.

    Step 6.4: Now, right-click the selected field, and choose the Add Field. Refer below.

    Automation Anywhere PDF Integration Command- Automation Anywhere Examples - Edureka

    Step 6.5: In the extracted text window, choose the suitable variable name and enter the field name. Then click Ok. This will store the extracted data for the specified variable and the field name. Refer below.

    Automation Anywhere Extract Text- Automation Anywhere Examples - Edureka

    Step 6.6: Similarly repeat the steps for the other 7 fields/variables.

    Step 6.7: Finally click on Save.

    Step 7: Now, you have to store the extracted data into respective cells in the Excel File. To do this follow the below steps:

    Step 7.1: Click on the Excel command and double-click on the Set Cell subcommand.

    Step 7.2: In the dialog box that opens up, go to the Cell value sectionpress on F2 and choose the variable name that you would like to choose. Then click on Insert. Here I will choose RecieptNo. Refer below.

    Automation Anywhere Extract Text From PDF- Automation Anywhere Examples - Edureka

    This action will make you store the data in the A2 cell.

    Step 7.3: Now, the next extracted data should be stored in the next cell that is B2(which is in the same row, but different column). To do that, double-click on the Go to cell subcommand and choose the option of One cell to right. After that click on Save.

    Automation Anywhere Go To Cell To Right - Automation Anywhere Examples - Edureka

    Step 7.4: Now, to insert the value to the B2 cell, again double click on the Set Cell subcommand and press on F2. Choose the variable name and click on Insert.

    Step 7.5: Now, insert the next value to the C2 cell. To do that repeat the above steps.

    Now, you have extracted the data for a single PDF, if you wish to extract data from various other PDFs. You have to store the data in the next row right?

    Step 8: To do so, Double click on the Go to Cell subcommand and choose One cell below.

    Automation Anywhere One Cell Below- Automation Anywhere Examples - Edureka

    Step 9: To go to the beginning cell i.e the first cell in the row, choose the Go to cell subcommand and choose Beginning of the row. Refer below.

    Automation Anywhere Beginning of Row - Automation Anywhere Examples - Edureka

    Step 10: Now, all the above actions were to extract data from a single PDF File. To extract data from multiple PDF Files, follow the below steps.

    Step 10.1: Click on the section action in the task pane and then Double click the Loop command from the left panel.

    Step 10.2: Over here choose Double click on the Each File in a Folder command and from the Browse option mention the path of the folder which contains all the PDF Files. Then click on Save.

    Automation Anywhere Start Loop - Automation Anywhere Examples - Edureka

    Step 10.3: Move the End Loop command to the last line of the action list.

    Step 10.4: Double click the PDF Integration command and insert the required variable ($FileName$) in the PDF Name section.

    Multiple PDFs - Automation Anywhere Examples - Edureka

    This is how your final task list should look like.Final Task List - Automation Anywhere Examples - Edureka

    Step 11: Now, click on the Save button, to save your task and execute the task by clicking on the Run button.

    You would see the below output.

    Output - Automation Anywhere Examples - EdurekaSo, folks! With this, we come to an end of this article on Automation Anywhere Examples. If you wish to give a jump start, to your career as an RPA Developer, then starting learning RPA and it’s various Tools.

    We at Edureka!, offer Robotic Process Automation Training using UiPath. Edureka! is a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. This training will help you gain deep knowledge in Robotic Process Automation and hands-on experience in UiPath.

    Got a question for us? Please mention it in the comments section of this Automation Anywhere Examples and we will get back to you

    The post Automation Anywhere Examples – Top Examples That You Can Practice appeared first on Edureka.

    What is Agile Testing? Know about Methods, Advantages and Principles

    $
    0
    0

    The complexity of the software development process is increasing continuously. The software testing approaches need to evolve to keep up with the development approaches. So, What is Agile Testing? In this article I will provide in-depth knowledge about the agile methodology in the following sequence:

    What is Agile Testing?

    Agile Testing is a type of software testing that follows the principle of agile software development. It is an iterative development methodology and the requirements evolve through collaboration between the customer and self-organizing teams.

    Agile testing - what is agile testing - edureka

    An agile team works as a single team towards a common objective of achieving Quality. Agile Testing has shorter time frames that are known as iterations.

    What is Agile Testing? | Edureka

    Principles of Agile Testing

    The different principles involved in Agile Testing include:

    • Testing is continuous: Agile team performs testing continuously because it is the only way to ensure continuous progress of the product.
    • Continuous feedback: Agile testing provides feedback on an ongoing basis so that your product can meet the business needs.
    • Tests performed by the whole team: In the software development life cycle, only the test team is responsible for testing. But in agile testing, the developers and the business analysts also test the application.

     

    principles - what is agile testing - edureka

     

    • Decrease time of feedback response: The business team is involved in each iteration in agile testing. So continuous feedback reduces the time of feedback response.
    • Simplified & clean code: The defects raised by the agile team are fixed in the same iteration. This helps in keeping the code clean and simplified.
    • Less documentation: Agile teams use a reusable checklist and the team focuses on the test instead of the incidental details.
    • Test Driven: In agile methods, you need to perform testing at the time of implementation. But in the traditional process, the testing is performed after implementation.

    Advantages of Agile Testing

    The benefits of Agile Testing approach include:

    • It saves time and money
    • Agile testing reduces documentation
    • It is flexible and highly adaptable to changes
    • It provides a way for receiving regular feedback from the end user
    • Better determination of issues through daily meetings

    Agile Testing Methods

    There are three main agile testing methods such as:

    Behavior Driven Development(BDD) – It improves communication amongst project stakeholders so that all members correctly understand each feature before the development process starts. There is continuous example-based communication between developers, testers, and business analysts.

     

    Acceptance Test Driven Development(ATDD) – It focuses on involving team members with different perspectives such as the customer, developer, and tester. The meetings are held to formulate acceptance tests incorporating perspectives of the customer, development, and testing.

     

    Exploratory Testing – It emphasizes working software over comprehensive documentation. The individuals and interactions are more important than the process and tools. Customer collaboration holds greater value than contract negotiation.

     

    Life Cycle of Agile Testing

    There are 5 different phases in the Agile Testing life cycle such as:

    lifecycle - what is agile testing - edureka

     

    1. Impact Assessment – In the first phase you have to gather inputs from stakeholders and users. Now this will be taken as feedback for the next deployment cycle.
    2. Agile Testing Planning – Here, the stakeholders come together to plan the schedule of the testing process, meeting frequency, and deliverables.
    3. Release Readiness – At this stage, you have to review the features that have been developed and check if they are ready to go live or not.
    4. Daily Scrums – This phase includes the everyday morning meetings to check on the status of testing and set the goals for the day.
    5. Test Agility Review – The final phase involves the weekly meetings with the stakeholders to review and assess the progress against milestones.

    Agile Test Plan & Quadrants

    The test plan is written and updated for every release for agile testing.  It includes:

    • The scope of the testing
    • Consolidating new functionalities to be tested
    • Types of testing/Levels of testing
    • Performance & load testing
    • Consideration of infrastructure
    • Risks Plan
    • Planning of resources
    • Deliverables & Milestones

    Quadrants

    The agile testing quadrants separate the whole process in four Quadrants. So this helps you in understanding the process of agile testing.

    quadrants - what is agile testing - edureka

     

    • Agile Quadrant I – This quadrant focuses on the internal code quality. It consists of test cases which are technology driven and are implemented to support the team. It includes:
      1. Unit Tests
      2.Component Tests
    • Agile Quadrant II – It contains test cases that are business driven and are implemented to support the team. This Quadrant focuses on the requirements. The kind of tests performed in this phase include:
      1. Testing of possible scenarios and workflows
      2. Testing of User experience
      3. Pair testing
    • Agile Quadrant III – This quadrant provides feedback to quadrants one and two. The test cases can be used as the basis to perform automation testing. Here, many rounds of iteration reviews are carried out which builds confidence in the product. The kind of testings done in this quadrant are:
      1. Usability Testing
      2. Exploratory Testing
      3. Pair testing with customers
      4. Collaborative testing
      5. User acceptance testing
    • Agile Quadrant IV – The fourth quadrant concentrates on the non-functional requirements such as performance, security, stability, etc. This quadrant helps the application to deliver the non-functional qualities and expected value. The tests performed are:
      1. Non-functional tests such as stress and performance testing
      2. Security testing with respect to authentication and hacking
      3. Infrastructure testing
      4. Data migration testing
      5. Scalability testing
      6. Load testing

    Now that you know the different test plan and quadrants of agile testing, let’s have a look at the companies that are using this methodology.

    Companies Using Agile Testing

    Agile testing reduces the cost of bugs by fixing them early. This approach yields a customer-centric approach by delivering a high-quality product as early as possible. So most of the companies have started implementing agile testing methodology. Some of the names include:

    With this, we have come to the end of our article. I hope you understood the methodologies of agile testing and why it is important in the world of software testing.

    Now that you know what is Agile Testing, check out the Software Testing Fundamentals Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete software testing life-cycle. You will be learning different levels of testing, test environment setup, test case design technique, test data creation, test execution, bug reporting, CI/CD pipeline in DevOps, and other essential concepts of software testing. 

    Got a question for us? Please mention it in the comments section of “What is Agile Testing” and we will get back to you.

    The post What is Agile Testing? Know about Methods, Advantages and Principles appeared first on Edureka.

    What is Scala? A Complete Guide to Scala Programming

    $
    0
    0

    What is Scala? A Robust and High-Caliber programming language that changed the world of big data. Scala is capable enough to outrun the speed of the fastest existing programming languages. I’ll walk you through this What is Scala article so that you can understand the true capabilities of Scala.

    I’ll line up the docket for this as below.

    So, let us begin with our first question.

    What is Scala?

    Well, Scala is a programming language invented by Mr. Martin Odersky and his research team in the year 2003.

    Scala is a compiler based and a multi-paradigm programming language which is compact, fast and efficient. The major advantage of Scala is the JVM (Java Virtual Machine). Scala code is first compiled by a Scala compiler and the byte code for the same is generated, which will be then transferred to the Java Virtual Machine to generate the output.

    What-is-Scala?-working-of-Scala-Edureka

    Thus, the Scala became the key to success for managing the huge amount of big-data.

    Now that we know the importance of Scala, let us now understand why actually it is the most preferred language in the present trends.

    Why we need Scala?

    What-is-Scala?-requirements-of-Scala-Edureka

     

    • Scala is capable to work with the data which is stored in a Distributed fashion. It accesses all the available resources and supports parallel data processing.
    • Scala supports Immutable data and it has support to the higher order functions.
    • Scala is an upgraded version of Java which was designed to eliminate unnecessary code. It supports multiple Libraries and APIs which will allow the programmer to achieve Less Down Time.
    • Scala supports multiple type Constructs which enables the programmer to work with wrappers/container types with ease.


    Now that we have understood the requirements for which we needed Scala. Let us move into the comparison between the other languages and find out why it gets an edge over the other similar programming languages.

     

    Scala and Other Languages

    The Name Scala portraits the scalability the language is capable of offering, now you might raise a question. Aren’t the latest programming Languages like Python, Ruby, Perl and the Legendary Java not scalable?

    What-is-Scala?-power-of-Scala-Edureka

    The answer is yes, they are scalable, but with some restrictions like the boiler plated codes like system.print.ln in Java. Scala is invented to overcome these limitations and minimize the execution time and complexity of the code.

    In the year 2006 Twitter was introduced in America and the developers used ruby on rails as their weapon of choice to develop this application, which later proved out to be a wrong choice when they had to manage the gigantic amount Big-Data which was dropping into the Twitter.

    What-is-Scala?-Applications-without- the-use-of-Scala-EdurekaThen they switched their backend to Java and used Scala as their new programming language to handle the big data using Hadoop and Spark frameworks which worked in a spectacular way.

    What-is-Scala?-Applications-of-Scala-Edureka

    Now we know the capabilities of Scala, Let us now understand its powerful features:

     

    Features of Scala

    • Object-oriented Programing Language:

    Scala is both a functional Programming Language and an object-oriented programming Language. Every variable and value which is used in Scala is implicitly saved as an object by default.

    • Extensible Programming Language:

    Scala can support multiple language constructs without the need of any Domain Specific Language (DSL)Extensions, Libraries, and APIs.

    What-is-Scala?-features-of-Scala-Edureka

     

    • Statically Typed Programming Language:

    Scala binds the Datatype to the variable in its entire scope.

    • Functional Programming Language:

    Scala provides a lightweight syntax for defining functions, it supports higher-order functions, it allows functions to be nested.

    • Interoperability:

    Scala compiles the code using scala compiler and converts code into Java Byte Code and Executes it on JVM.

    These were the Features of Scala and let us get into few of the frameworks of Scala is capable to support.

    Frameworks of Scala

    What-is-Scala?-frameworks-of-Scala-Edureka

     

    Akka, Spark, Play, Neo4j, Scalding are some of the major frameworks that Scala can support.

    • Akka is a toolkit on runtime for building highly concurrent, distributed, and fault-tolerant applications on the JVM. Akka is written in Scala, with language bindings provided for both Scala and Java. 
    • Spark Framework is designed to handle, and process big-data and it solely supports Scala.
    • Play framework is designed to create web applications and it uses Scala in the process in order to obtain the best in class performance.
    • Scalding is a domain-specific language (DSL)in the Scala programming language, which integrates Cascading. It is a functional programming paradigm used in Scala which is much closer than Java to the original model for MapReduce functions.
    • Neo4j is a java spring framework supported by Scala with domain-specific functionality, analytical capabilities, graph algorithms, and many more. 

    These were the popular Frameworks supported by Scala, Now let us understand the variables and data types in Scala.

    Variables in Scala

    Variables can be defined as the reserved memory locations used to store the values. Similarly, we do have variables in Scala Programming Language as well. The Variables in Scala are divided into two types.

    What-is-Scala-Types-of-variables-Edureka

    Mutable Variables

    These variables allow us to change a value after the declaration of a variable. Mutable variables are defined by using the var keyword. The first letter of data type should be in capital letter because in Scala data type is treated as an object.

    var b = "Edureka"
    b = "Brain4ce Organisation"
    

    output:

    b: String = Edureka
    b: String = Brain4ce Organisation


    In this case, the variable will accept the new string and displays it.

    Immutable Variable 

    These variables do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the val keyword. The first letter of data type should be in capital letter because in the Scala data type is treated as objects.

    val a = "hello world"
    a = "how are you"
    

    output:

    a: String = hello world
    <console>:25: error: reassignment to val
    a = “how are you”
    ^

    What-is-Scala-errors-of-Scala-Edureka

    This code will give an error and the new value will not be accepted by the variable a.

    Lazy Evaluation

    lazy val x = 100
    x*2
    

    output:

    x: Int = <lazy>
    res: Int = 200

     

    Lazy Evaluation is the primary feature of Scala which bought it the dignity of a whole new level. Here, the declared variable will not be accessed or any operation is not performed on to the variable unless the programmer particularly accesses it and performs an operation on to it.

    In simple words, it is an On-Demand execution of an operation which saves a lot of memory and processing resources in real-time.

    Datatypes supported in Scala are as follows.

    datatypes-of-Scala-Edureka

     

     

    Collections in Scala

    Arrays

    An array is a data structure which stores a fixed-size sequential collection of elements of the same data type.

    We shall look into a few examples of arrays in Scala

    • Here we are creating an Array of integer type which is empty and will store 0 as a default value in all its memory locations.
    val array = new Array[Int](10)
    

    output:

    array: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

     

    • We can access the memory location and ingest a value into the array.
    array(0) = 10
    array(1) = 2
    

    output:

    array: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    res: Array[Int] = Array(10, 2, 0, 0, 0, 0, 0, 0, 0, 0)

     

    • Let us create an array of String Datatype and print each of the values in a new line using a for loop.
    val mystring = Array("Edureka", "Brain4ce", "Organisation")
    for ( x <- mystring )
    {
    println( x )
    }
    

    output:

    Edureka
    Brain4ce
    Organisation

     

    • Let us now learn about ArrayBuffer. We need to import the following Library before we perform any of the operations on an Array Buffer
    import scala.collection.mutable.ArrayBuffer
    

    output:

    import scala.collection.mutable.ArrayBuffer

     

    • Let us create an Array Buffer of Integer type.
    val a = ArrayBuffer[Int]()
    

    output:

    a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

     

    • Let us insert an element into the Array Buffer
    a += 1
    

    output:

    res: a.type = ArrayBuffer(1)

     

    • Let us insert Multiple elements into the Array Buffer.
    a += (2,3,4,5)
    

    output:

    res: a.type = ArrayBuffer(1, 2, 3, 4, 5)

     

    • Let us insert a complete Array into the Array Buffer
    a ++= Array(6, 7, 8)
    

    output:

    res: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

     

    • Let us perform some basic operations on the Array Buffer.
    • This function is used to trim the last two elements of the Array Buffer.
    a.trimEnd(2)
    

    output:

    res: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)
    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)

     

    • This function is used to insert element 9 in the 2nd memory location of the Array Buffer.
    a.insert(2, 9)
    

    output:

    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)
    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 9, 3, 4, 5, 6)

     

    • This function is used to insert elements (0,9,6,1) in the 2nd memory location of the Array Buffer.
    a.insert(2,0,9,6,1)
    

    output:

    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 9, 3, 4, 5, 6)
    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 0, 9, 6, 1, 9, 3, 4, 5, 6)

     

    This function is used to remove an element in the second memory location of the Array Buffer.

    a.remove(2)
    

    output:

    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 0, 9, 6, 1, 9, 3, 4, 5, 6)
    res: Int = 0
    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 9, 6, 1, 9, 3, 4, 5, 6)

     

    • This function is used to remove three elements from the Array buffer, starting from the second memory location.
    a.remove(2, 3)
    

    output:

    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 9, 6, 1, 9, 3, 4, 5, 6)
    res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 9, 3, 4, 5, 6)

     

    • Let us perform some common operations on the Array Buffer
    • Sum function is used to perform the summation of all the elements in the Array Buffer.
    Array(1,2,3,4).sum
    

    output:

    res: Int = 10

     

    • Max function is used to find the element with the maximum in the Array Buffer.
    Array(1,2,3,4).max
    

    output:

    res: Int = 4

     

    • Let us perform a quicksort on the Array Buffer.
    val a = Array(1,5,3,2,4)
    scala.util.Sorting.quickSort(a)
    

    output:

    a: Array[Int] = Array(1, 5, 3, 2, 4)
    res: Array[Int] = Array(1, 2, 3, 4, 5)

     

    Lists

    The Scala List is an immutable sequence of elements, implemented as a linked list. Unlike an array, a linked list consists of many small objects, each containing a reference to an object as well as a reference to the rest of the list

    Now we shall look into few examples of lists in Scala.

    • Creating a Scala List object
    val list = 1 :: 2 :: 3 :: Nil
    val list = List(1,2,3)
    

    output:

    list: List[Int] = List(1, 2, 3)
    list: List[Int] = List(1, 2, 3)

     

    • Adding Element to List
    val x = List(2)
    val y = 1 :: x
    val z = 0 :: y
    

    output:

    x: List[Int] = List(2)
    y: List[Int] = List(1, 2)
    z: List[Int] = List(0, 1, 2)

     

    • delete elements from a Scala List or ListBuffer
    val originalList = List(5, 1, 4, 3, 2)
    val newList = originalList.filter(_ > 2)
    

    output:

    originalList: List[Int] = List(5, 1, 4, 3, 2)
    newList: List[Int] = List(5, 4, 3)

     

    • Let us import List Buffer
    import scala.collection.mutable.ListBuffer
    

    output:

    import scala.collection.mutable.ListBuffer

     

    • Creating List Buffer
    val x = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)
    

    output:

    x: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)

     

    • You can delete one element at a time, by value:
    x -= 5
    

    output:

    res: x.type = ListBuffer(1, 2, 3, 4, 6, 7, 8, 9)

     

    • You can delete elements by position:
    x.remove(0)
    

    output:

    res: Int = 1
    res: scala.collection.mutable.ListBuffer[Int] = ListBuffer(2, 3, 4, 6, 7, 8, 9)

     

    • The List ‘range’ method
    val x = List.range(1,10)
    

    output:

    x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

     

    • The range function can also take a third argument which serves as a “step
    val x = List.range(0,10,2)
    

    output:

    x: List[Int] = List(0, 2, 4, 6, 8)

     

    • The List ‘fill’ method
    val x = List.fill(3)("Apple")
    

    output:

    x: List[String] = List(Apple, Apple, Apple)

     

    • The List class ‘tabulate’ method
    • The tabulate method creates a new List whose elements are created according to the function you apply
    val x = List.tabulate(5)(n = n + n)
    

    output:

    x: List[Int] = List(0, 2, 4, 6, 8)

     

    • prepend items to a List
    • create a List
    val x = List(1,2,3)
    

    output:

    x: List[Int] = List(1, 2, 3)

     

    • prepend an element to the list
    val y = 0 :: x
    

    output:

    y: List[Int] = List(0, 1, 2, 3)

     

    • Appending and merging Lists
    val a = List(1,2,3)
    val b = List(4,5,6)
    val c = a ::: b
    

    output:

    y: List[Int] = List(0, 1, 2, 3)
    a: List[Int] = List(1, 2, 3)
    b: List[Int] = List(4, 5, 6)
    c: List[Int] = List(1, 2, 3, 4, 5, 6)

     

    • You can also merge two Scala lists using the List’s concat method:
    val c = List.concat(a, b)
    

    output:

    c: List[Int] = List(1, 2, 3, 4, 5, 6)

     

    • Iterating lists with foreach
    val x = List(1,2,3)
    x.foreach { println }
    

    output:

    x: List[Int] = List(1, 2, 3)
    1
    2
    3

     

    • add one element at a time to the ListBuffer
    var flowers = new ListBuffer[String]()
    flowers += "Rose"
    flowers += "Lilly"
    flowers += "Tulip"
    

    output:

    flowers: scala.collection.mutable.ListBuffer[String] = ListBuffer()
    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Rose)
    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Rose, Lilly)

    • add multiple elements
    flowers += ("Daisy", "Sunflower", "Jasmine")
    

    output:

    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Rose, Lilly, Tulip, Daisy, Sunflower, Jasmine)

     

    • remove one element
    flowers -= "Rose"
    

    output:

    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Lilly, Tulip, Daisy, Sunflower, Jasmine)

     

    • remove multiple elements
    flowers -= ("Lilly", "Tulip")
    

    output:

    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Daisy, Sunflower, Jasmine)

     

    • remove multiple elements specified by another sequence
    flowers --= Seq("Daisy", "Sunflower")
    

    output:

    res: scala.collection.mutable.ListBuffer[String] = ListBuffer(Jasmine)

     

    • convert the ListBuffer to a List when you need to
    val flowersList = flowers.toList
    

    output:

    flowersList: List[String] = List(Jasmine)

     

    Sets

    A Set is a collection that contains no duplicate elements. By default, Scala uses the immutable Set. If you want to use the mutable Set, you’ll have to import the library called,

    import scala.collection.mutable.Set class explicitly.

    We shall try out some examples of sets in Scala.

    • Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and the mutable.
    var s : Set[Int] = Set()
    var s : Set[Int] = Set(1,1,5,5,7)
    

    output:

    var s : Set[Int] = Set()
    var s : Set[Int] = Set(1,1,5,5,7)

     

    • Immutable set
    var s = Set(1,3,5,7)
    

    output:

    s: scala.collection.immutable.Set[Int] = Set(1, 3, 5, 7)

     

    • Basic operational methods
    val fruit = Set("apples", "oranges", "pears")
    println( "Head of fruit : " + fruit.head )
    println( "Tail of fruit : " + fruit.tail )
    println( "Check if fruit is empty : " + fruit.isEmpty )
    val nums: Set[Int] = Set()
    println( "Check if nums is empty : " + nums.isEmpty )
    

    output:

    fruit: scala.collection.immutable.Set[String] = Set(apples, oranges, pears)
    Head of fruit : apples
    Tail of fruit : Set(oranges, pears)
    Check if fruit is empty : false
    nums: Set[Int] = Set()
    Check if nums is empty : true

     

    • Concatenating Sets
    • You can use either ++ operator or Set.++() method to concatenate two or more sets,
      but while adding sets it will remove duplicate elements.
    
    val fruit1 = Set("apples", "oranges", "pears")
    val fruit2 = Set("mangoes", "banana", "oranges")
    val fruit = fruit1 ++ fruit2
    fruit
    

    output:

    fruit1: scala.collection.immutable.Set[String] = Set(apples, oranges, pears)
    fruit2: scala.collection.immutable.Set[String] = Set(mangoes, banana, oranges)
    fruit: scala.collection.immutable.Set[String] = Set(banana, apples, mangoes, pears, oranges)

     

    • use two or more sets with ++ as operator 
    • Mutable set
    • Add elements to a mutable Set with the +=, ++=, and add methods:
    • use var with mutable
    var set = scala.collection.mutable.Set[Int]()
    

    output:

    set: scala.collection.mutable.Set[Int] = Set()

     

    • add one element
    set += 1
    

    output:

    res: scala.collection.mutable.Set[Int] = Set(1)

     

    • add multiple elements
    set += (2, 3)
    set.add(6)
    set.add(2)
    

    output:

    res: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
    res: Boolean = true
    res: Boolean = false

     

    Maps

    Scala Map is a collection of a Key-value pair. A map cannot have duplicate keys, but different keys can have the same values

    We shall try a few examples of maps in Scala.

    val colors1 = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
    val colors2 = Map("blue" -> "#0033FF", "yellow" -> "#FFFF00", "red" -> "#FF0000")
    colors1.keys
    colors1.values
    colors1.isEmpty
    var colors = colors1 ++ colors2
    

    output:

    res: Iterable[String] = Set(red, azure, peru)
    res: Iterable[String] = MapLike(#FF0000, #F0FFFF, #CD853F)
    res: Boolean = false

     

    Let us check another example in maps.

    val mapping = Map("virat" -> "kohili", "mahendra" -> "singhdhoni")
    val mapping = scala.collection.mutable.Map("virat" -> "kohili", "mahendra" -> "singhdhoni")
    mapping("virat")
    mapping -= "mahendra"
    mapping += ("ajay"-> "sharma")
    mapping.getOrElse("virat", 0)
    

    output:

    mapping: scala.collection.immutable.Map[String,String] = Map(virat -> kohili, mahendra -> singhdhoni)
    mapping: scala.collection.mutable.Map[String,String] = Map(mahendra -> singhdhoni, virat -> kohili)
    res: String = kohili
    res: mapping.type = Map(virat -> kohili)
    res: mapping.type = Map(virat -> kohili, ajay -> sharma)
    res: Any = kohili

     

    Tuples

    Scala tuple combines a fixed number of items together so that they can be passed around. Unlike an array or list, a tuple can hold objects with different types, but they are also immutable. The following is an example of a tuple holding an integer, a string.

    We shall try a few examples of tuples in Scala.

    val a = (1,2,"Ajay","Devgan")
    a._1
    a._3
    

    output:

    a: (Int, Int, String, String) = (1,2,Ajay,Devgan)
    res: Int = 1
    res: String = Ajay


    These were the Collections supported by Scala, Now let us understand the Control Statements.

     

    Control Statements in Scala

    Now with this, we shall move into our next topic, the control statements.

    control-statements-of-Scala-Edureka

    If

    An if statement decides to execute which of the two given statements.

    for (i <- 0 to 5; j <- 0 to 5 if i==j)
    println(i + j)
    

    output:

    0
    2
    4
    6
    8
    10

     

    if else

    An if statement which will be followed by an else statement which executes one of the two statements. if the condition provided at the if block is true then the if block statements will be executed. else, the statements at the else block will be executed.

    var x = 5
    val s = if (x > 0 && x < 6) 1 else 0
    val s =if (x > 0 && x < 6) "positive" else 0
    

    output:

    x: Int = 5
    s: Int = 1
    s: Any = positive

     

    While

    While is a control statement which checks the condition and determines whether to execute a particular set of statements present in the loop or not.

    var args = "Edureka"
    println("length is " + args.length)
    var i = 0
    while(i < args.length)
    {
    println(args(i))
    i+= 1
    }
    

    output:

    E
    d
    u
    r
    e
    k
    a

     

    Do while

    Do While loop is similar to While loop with the only difference which is the condition to the loop lies at the end of the loop program block as shown below. The Do while loop executes at least for once as the condition checked after the execution of statements in the block.

    var x=7
    do
    {
    println(x)
    x=x-1
    }while(x > 0);
    

    output:

    7
    6
    5
    4
    3
    2
    1

     

    For

    For loop is a simple loop which has an initializing variable, counter variable and a condition in it. The initializing variable will be initialized to a certain value and counter variable counts the iterations and the iterations will run until the provided condition is true.

    for ( i <- 1 to 5)
    println(i)
    #Advaned For Loop
    for (i <- 0 to 5 if i==j)
    println(10*i + j)
    

    output:

    1
    2
    3
    4
    5


    output (Advanced For Loop):

    0                                                         
    11
    22
    33
    44
    55



    For each iteration of your for loop, yield generates a value which will be remembered.
    It’s like the for loop has a buffer you can’t see, and for each iteration of your for loop, another item is added to that buffer. When your for loop finishes running,
    it will return this collection of all the yielded values.

    for (i <- 1 to 5) yield i
    for (i <- 1 to 5) yield i * 2
    

    output:

    res: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
    res: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

     

    Foreach

    Foreach control statement is similar to the for loop on the only difference is it prints each value and to iterate items in a list, we can use for loop. It operates on arrays or collections such as ArrayList, which can be found in the System.

    var args= "Hello"
    args.foreach(println(arg))
    

    output:

    H
    e
    l
    l
    o

     

    Find the area of a circle

    def area (radius: Int): Double= {
    println("This is a function to perfrom double operations")
    3.14 * radius * radius
    }
    area(radius)
    

    output:

    res: Double = 1384.74

     

    Now Let us understand the Applications where we require Scala.

    Applications of Scala

    Scala is a powerful programming language that has the capabilities to support multiple functionalities.

    Some of the major applications of Scala are as follows:

    • Designing Web Applications and Web Pages
    • Spark Framework uses Scala to perform real-time data streaming
    • Concurrency and Distributed data processing applications
    • Scala supports both Batch Data Processing and Parallel Data Processing
    • Spark Framework uses Scala in Data Analytics

    Applications-of-Scala-Edureka

    Now, these were a few important applications of Scala, Let us now look into the scope we have for Scala Programming Language.

    Scope for Scala

    Scala is the miracle of the 20th century in multiple streams. It has seen astounding growth since day one and it is for sure it is one of the programming languages which is in higher demand. The stats below explain more about the scope of Scala in the near future.

    job-opportunities-of-Scala-Edureka

    The chart below describes the permanent jobs and Contract based jobs available based on the knowledge of Scala Programming Language.

     

    Applications-of-Scala-EdurekaSo, with this, we come to an end of this What is Scala article. I hope we sparked a little light upon your knowledge about Scala, Its features and the various types of operations that can be performed using Scala.

    This article based on Apache Spark and Scala Certification Training is designed to prepare you for the Cloudera Hadoop and Spark Developer Certification Exam (CCA175). You will get in-depth knowledge on Apache Spark and the Spark Ecosystem, which includes Spark DataFrames, Spark SQL, Spark MLlib and Spark Streaming. You will get comprehensive knowledge on Scala Programming language, HDFS, Sqoop, Flume, Spark GraphX and Messaging System such as Kafka.

     

    The post What is Scala? A Complete Guide to Scala Programming appeared first on Edureka.


    Your Complete Solution to Shell Scripting Interviews

    $
    0
    0

    Linux has started to expand its market rapidly since the past few years and Shell Scripting in Linux is one of the Top 10 occurring IT job-requirements. So, we thought of making your job easier by making an ensemble of the most commonly asked Shell Scripting Interview Questions which will get you ready for any job interview that you wish to appear.

    The questions have been segregated into 3 parts;

    Interview Questions for Beginners

    Q1. What is Shell?

    The Shell is a Command Line Interpreter. It translates commands entered by the user and converts them into a language that is understood by the Kernel. The shell interprets a command typed in at the terminal, and calls the program that you want. 

    Q2. What is a Shell Script? Can you name some of its advantages? 

    A shell script is a command-containing text-file that contains commands in order of their execution. Typical operations performed by shell scripts include printing text, file manipulation, and program execution.

    Following are the two main advantages of shell scripting:

    • It facilitates developing your own custom OS with relevant features which best suit your needs.
    • It facilitates designing software applications according to their respective platforms.

    Q3. What are the different types of variables used in Shell Script?

     A shell script has two types of variables :

    • System-defined variables are created/defined by the Operating System(Linux) itself. These variables are generally defined in Capital Letters and can be viewed by “set” command.
    • User-defined variables are created or defined by system users and the values of variables can be viewed by using the command “echo”.

    Q4. What are the different types of commonly used shells on a typical Linux system?

    There are primarily two kinds of shells in Linux OS, namely, Bourne Shell and C-Shell. Examples of derivative from each are as follows;

    • Bourne Shell: Bourne Shell, Bourne-Again Shell, Korn Shell, POSIX Shell.
    • C-Shell: C-Shell, TENEX C-Shell, Z-Shell

    Q5. How do you create a shortcut in Linux?

    This can be done with the help of links present in Linux OS.

    Hard Link: Hard links are linked to the inode of the file and have to be on the same file system as of the file. Deleting the original file does not affect the hard link.

    Soft Link: Soft links are linked to the file name and can reside on a different file system as well. Deleting the original file makes the soft link inactive.

    Q6. Tell something about the Super Block in Shell scripting?

    A Super Block is essentially a program that contains a record of specific file systems.

    Characteristics such as the block size, the empty and the filled blocks and their respective counts, the size and location of the inode tables, the disk block map, and usage information, and the size of the block groups are available in a superblock.

    Q7. What is GUI scripting?

    GUI is used for controlling a computer and its applications. GUI scripting supports different applications. It mostly depends on the operating system.

    Q8. What are the various stages of a Linux process it passes through?

    A Linux process generally passes through four stages:

    • Waiting: The Linux process waits for the resource.
    • Running: The Linux process is currently being executed.
    • Stopped: The Linux process is stopped after successful execution.
    • Zombie: The process has stopped but is still active in the process table.

    Q9. What is the difference between break and continue commands?

    • Break: It is a simple way to escape out of a loop in progress. We can use the break command to exit out from any loop, including while and until loops.
    • Continue: It causes the present iteration of the loop to exit, instead of the entire loop.

    Q10. What is the significance of the Shebang line in Shell Scripting?

    The Shebang line is present at the top of the script,e.g. #!/bin/sh. It simply provides information regarding the location where the engine is placed. The engine is the one that executes the script. 

    Shell Scripting Interview Questions & Answers | Edureka

    Q11. How to pass an argument to a script?

    #!/bin/sh
    ct $1

    q11 - Shell Scripting Interview Questions - Edureka

     question 11 – Shell Scripting Interview Questions – Edureka 

    Q12. How to use arguments in a Script?

    #!/bin/sh
    cp $1 $2

    q12 - Shell Scripting Interview Questions - Edureka

     question 12 – Shell Scripting Interview Questions – Edureka 

    Q13. How to calculate the number of passed arguments?

    #!/bin/sh
    echo "Number of Parameters passed:$#"

    q13 - Shell Scripting Interview Questions - Edureka

    question 13 – Shell Scripting Interview Questions – Edureka 

    Q14. How to get script name inside a script?

    !/bin/sh
    echo "Script Name:$0"

    q14 - Shell Scripting Interview Questions - Edureka

    question 14 – Shell Scripting Interview Questions – Edureka

    Q15. How to check if the previous command was run successfully?

    #!/bin/sh
    var=$?
    if var=0
    then
    echo "Script was Run successfully"

    else
    echo "Script was unsuccessful"
    fi

    q15 - Shell Scripting Interview Questions - Edureka

    question 15 – Shell Scripting Interview Questions – Edureka

    Q16. How to get the last line from a file using just the terminal?

    tail -1 <filename>

    Q17. How to get the first line from a file using just the terminal?

    head -1 <filename>

    Q18. How to get the 3rd element/column from each line from a file?

    #!/bin/sh
    awk '{print $3}' $1

    q18 - Shell Scripting Interview Questions - Edureka

    question 18 – Shell Scripting Interview Questions – Edureka

    Q19. How to write a function?

    #!/bin/sh

    function example {
    echo "Hello Learner"
    }

    Q20. Write down the Syntax for all the loops in Shell Scripting.

    For Loop:

    for var in word1 word2 ... wordN
    do
       Statement(s) to be executed for every word.
    done
    
    

    While Loop:

    while command
    do
       Statement(s) to be executed if command is true
    done
    
    

    Until Loop:

    until command
    do
       Statement(s) to be executed until command is true
    done

    Interview Questions for Intermediate

    Q21. What makes C shell a more preferable option than the Bourne Shell?

    C is a more preferable option in the following cases:

    • All the commands can be aliased simply with the C shell whereas the same is not possible in case of Bourne Shell.
    • Lengthy commands can be used again and again in C shell whereas the Bourne doesn’t allow the same in all the cases.
    • The command history can be accessed through the C shell but it cannot be accessed through the Bourne.

    Q22. How would you compare the strings in a Shell Script?

    The test command is used to compare the text strings. The test command compares text strings by comparing each character in each string.

    Q23. How to redirect both standard output and standard error to the same location?

    The two methods to redirect standard output and standard error to the same location are the following;

    • 2>&1(# ls /usr/share/doc > out.txt 2>&1 )
    • &>(# ls /usr/share/doc &> out.txt )

    Q24. Differentiate between ‘ and ” quotes.

    • Single Quotes: Used in case evaluation of variables to values is undesired.
    • Double Quotes: Used in case evaluation of variables to values is required.

    Q25. When should shell programming/scripting not be used?

    It is not advisable to use Shell scripting in the following cases;

    • When the task is very much complex, e.g. writing the entire payroll processing system.
    • Where there is a high degree of productivity required.
    • When it needs or involves different software tools.

    Q26. What is the lifespan of a variable inside a shell script?

    The lifespan of a variable inside shell script is only until the end of execution.

    Q27. What is a file system?

    The file system is a collection of files which contain information related to the files.

    Q28. What are the default permissions of a file when it is created?

    On Linux and other Unix-like operating systems, new files are created with a default set of permissions. The umask or user mask command is used to determine the default permissions for newly created files. It is a 4-digit Octal number which is set and expressed using symbolic values. The default permission of a file when it is created is 664 i.e. rw-rw-r-. The table for file permissions is given below;

    0 0 No permissions
    1 1 execute
    2 2 write
    3 1+2 execute + write
    4 4 read
    5 1+4 execute + read
    6 2+4 write + read
    7 1+2+4 execute + write + read

    Q29. What does it mean by #!/bin/sh or #!/bin/bash at the beginning of every script?

    script may specify #!/bin/bash on the first line, meaning that the script should always be run with bash, rather than another shell. /bin/sh is an executable representing the system shell. Actually, it is usually implemented as a symbolic link pointing to the executable for whichever shell is the system shell.

    Q30. What is the difference between $* and $@?

    $@ treats each quoted arguments as separate arguments but $* will consider the entire set of positional parameters as a single string.

    Q31. Determine the output of the following command: name=Shubham && echo ‘My name is $name’.

    q31 - Shell Scripting Interview Questions - Edureka

    question 31 – Shell Scripting Interview Questions – Edureka

    Q32. Determine the output of the following command: [ -z “” ] && echo 0 || echo 1 

    q32 - Shell Scripting Interview Questions - Edureka

    question 32 – Shell Scripting Interview Questions – Edureka

    Q33. Determine the output of the following command: echo ${new:-variable}

    q34 - Shell Scripting Interview Questions - Edureka

    q33 – Shell Scripting Interview Questions – Edureka

    Q34. How to get part of string variable with echo command only?

    #!/bin/sh
    echo ${variable:x:y}
    #x - start position
    #y - length

    variable="My name is Upasana, and I work at Edureka."
    echo ${variable:11:7} # will display Upasana

    q34 - Shell Scripting Interview Questions - Edureka

    q34 – Shell Scripting Interview Questions – Edureka

    Q35. Rewrite the command to print the sentence and convert the variable to plural: echo “I like $variable”.

    q35 - Shell Scripting Interview Questions - Edureka

    q35 – Shell Scripting Interview Questions – Edureka

    Q36. How to print all the arguments provided to the script?

    #!/bin/bash  for i; do     echo $i  done
    
    
    q36 - Shell Scripting Interview Questions - Edureka

    q36 – Shell Scripting Interview Questions – Edureka

    Q37. How to print PID of the current shell?

    #!/bin/sh

    for PID in $$
    do
    echo $PID
    done

    q37 - Shell Scripting Interview Questions - Edureka

    q37 – Shell Scripting Interview Questions – Edureka

    Q38. How to print all array elements and their respective indexes?

    !/bin/sh
    array=("This" "is" "Shell" "Scripting")
    echo ${array[@]}
    echo ${!array[@]}

    q39 - Shell Scripting Interview Questions - Edureka

    q38 – Shell Scripting Interview Questions – Edureka

    Q39. How to print the first array element?

    #!/bin/sh
    array=("This" "is" "Shell" "Scripting" )
    echo ${array[0]}

    q38 - Shell Scripting Interview Questions - Edureka

    q39 – Shell Scripting Interview Questions – Edureka

    Q40. What is the Crontab?

    Crontab stands for cron table because it uses the job scheduler cron to execute tasks. The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. 

    The schedule is called the crontab, which is also the name of the program used to edit that schedule.

    Interview Questions for the Experienced

    Q41. How many fields are present in a crontab file and what does each field specify?

    The crontab file has six fields.

    The first five fields contain information on when to execute the command and they are as follows;

    • minute(0-59)
    • hour(0-23)
    • day(1-31)
    • month(1-12)
    • day of the week(0-6, Sunday = 0).

    The sixth field contains the command to be executed.

    Q42. What are the two files of crontab command?

    The two files of crontab command are:

    • cron.allow which decides the users need to be permitted for using the crontab command.
    • cron.deny which decides the users need to be prevented from using the crontab command.

    Q43. What command needs to be used to take the backup?

    The tar command is used to take the backup. It stands for tape archive. The command is mainly used to save and restore files to and from an archive medium like tape.

    Q44. What are the different commands available to check the disk usage?

    There are three different commands available to check the disk usage.

    • df: It is used to check the free disk space.
    • du: It is used to check the directory wise disk usage.
    • dfspace: It is used to check the free disk space in terms of MB.

    Q45. What are the different communication commands available in the Shell?

    There are four different communication commands available in Shell.

    • mail
    • news
    • wall
    • motd

    The total disk space used by Edureka can be found out as shown below.

    du –s/home/Edureka

    Q47. How to debug the problems encountered in the shell script/program?

    Given below are some common methods used to debug the problems in the script.

    • Debug statements can be inserted in the shell script to output/display the information which helps to identify the problem.
    • Using set -x we can enable debugging in the script.

    Q48. What is the difference between = and ==?

    • = This is used for assigning value to the variable.
    • == This is used for string comparison.

    Q49. How to open a read-only file in the Shell?

    A read-only file can be opened using the below command:

    vi –R <File Name>

    Q50. How can the contents of a file inside jar be read without extracting in a shell script?

    The contents of the file inside a jar can be read without extracting as shown below.

    tar –tvf <File Name>.tar

    Q51. Write a shell script to get current date, time, user name and current working directory.

    #!/bin/sh
    echo "Hello, $LOGNAME"
    echo "Today's date is `date`"
    echo "Username is `who i am`"
    echo "Current directory is `pwd`"

    q51 - Shell Scripting Interview Questions - Edureka

    q51 – Shell Scripting Interview Questions – Edureka

    Q52. How to find all the files modified in less than 3 days and save the record in a text file?

    find . -type f -mtime -3 -exec ls -l {} \; > last3days.txt

    Q53. Write a Shell Script that adds two numbers if provided as the command Line Argument and if the two numbers are not entered throws an Error Message.

    #!/bin/sh
    # The Shebang

    if [ $# -ne 2 ]
    # If two Inputs are not received from Standard Input

    then
    # then execute the below statements

    echo "Usage - $0 x y"
    # print on standard output, how-to use the script (Usage - ./1.sh x y )

    echo " Where x and y are two nos for which I will print sum"
    # print on standard output, “Where x and y are two nos for which I will pri$

    exit 1
    # Leave shell in Error Stage and before the task was successfully carried o$

    fi

    # print on standard output, how-to use the script (Usage - ./1.sh x y )

    echo " Where x and y are two nos for which I will print sum"
    # print on standard output, “Where x and y are two nos for which I will pri$

    exit 1
    # Leave shell in Error Stage and before the task was successfully carried o$

    fi
    # End of the if Statement.

    echo "Sum of $1 and $2 is `expr $1 + $2`"
    # If the above condition was false and user Entered two numbers as a command$

    Case 1: When parameters are not passed

    q52(1) - Shell Scripting Interview Questions - Edurekaq52.1 – Shell Scripting Interview Questions – Edureka

    Case 2: When parameters are correctly passed

    q52(2) - Shell Scripting Interview Questions - Edurekaq52.2 – Shell Scripting Interview Questions – Edureka

    Q54. Print a given number, in reverse order using a Shell script such that the input is provided using command Line Argument only.

    #!/bin/sh
    if [ $# -ne 1 ]
    then
    echo "Usage: $0 number"
    echo " Reverse of the given number will be printed"
    echo " For eg. $0 0123, 3210 will be printed"
    exit 1
    fi

    n=$1
    rev=0
    sd=0

    while [ $n -gt 0 ]
    do
    sd=`expr $n % 10`
    rev=`expr $rev \* 10 + $sd`
    n=`expr $n / 10`
    done

    Case 1: When parameters are not passed

    q54(1) - Shell Scripting Interview Questions - Edurekaq54.1 – Shell Scripting Interview Questions – Edureka

    Case 2: When the parameter is correctly passed

    q54(2) - Shell Scripting Interview Questions - Edurekaq54.2 – Shell Scripting Interview Questions – Edureka

    Q55. Calculate a real number calculation directly from the terminal and not any shell script. 

    q55 - Shell Scripting Interview Questions - Edureka

    q55 – Shell Scripting Interview Questions – Edureka

    Q56. How can you get the value of pi till a 100 decimal places?

    q56 - Shell Scripting Interview Questions - Edureka

    q56 – Shell Scripting Interview Questions – Edureka

    Q57. How will you find the total disk space used by a specific user?

    du -sh ~

    q58 - Shell Scripting Interview Questions - Edureka

    q57 – Shell Scripting Interview Questions – Edureka

    Q58. How to check if a directory exists?

    #!/bin/sh

    if [ -d $mydir ]
    then
    echo "Directory exists"
    fi

    q57 - Shell Scripting Interview Questions - Edurekaq58 – Shell Scripting Interview Questions – Edureka

    Q59. Can you write a script to portray how set –x works?

    #!/bin/sh
    #set -x
    i=1
    while [ $i -lt 6 ]
    do
    print "in loop iteration: $i"
    ((i+=1))
    done
    exit

    q59.1 - Shell Scripting Interview Questions - Edureka

    q59.1 – Shell Scripting Interview Questions – Edureka

    #!/bin/sh
    set -x
    i=1
    while [ $i -lt 6 ]
    do
    print "in loop iteration: $i"
    ((i+=1))
    done
    exit

    q59.2 - Shell Scripting Interview Questions - Edureka

    q59.2 – Shell Scripting Interview Questions – Edureka

    Q60. Suppose you execute a command using exec, what will be the status of your current process in the shell?

    All the forked processes which are new get overlays when the exec is executed. The command simply gets executed without making any impact on the current process. Also, no new process will be created in this scenario.

    These were all the questions we could think of, on the various aspects of Shell Scripting in Linux, that would cover you for any interview you’d appear for, in the shortest possible time frame. If you have any interesting questions that have been asked to you in an interview you’ve appeared before, feel free to drop them at the comments bar and we shall answer them for you. You could also refer to this video which explains the solutions to these problems in depth.

    The post Your Complete Solution to Shell Scripting Interviews appeared first on Edureka.

    What Are Variables And Data Types In Python?

    $
    0
    0

    Python programming language is one of the most sought out programming languages nowadays. Developers want to focus on the implementation part rather than spending time writing complex programs. This is where python actually delivers, with the ease of access and readability. Fundamental concepts are the foundation of any programming language and hence in this blog we will learn the concept of variables and data types in python. Following are the topics covered in this blog: 

    What Are Variables In Python?

    Variables and data types in python as the name suggests are the values that vary. In a programming language, a variable is a memory location where you store a value. The value that you have stored may change in the future according to the specifications.

    variables-variables and data types in python-edureka

    A Variable in python is created as soon as a value is assigned to it. It does not need any additional commands to declare a variable in python.

    There are a certain rules and regulations we have to follow while writing a variable, lets take a look at the variable definition and declaration to understand how we declare a variable in python.

    Variable Definition & Declaration

    Python has no additional commands to declare a variable. As soon as the value is assigned to it, the variable is declared.

    
    x = 10
    #variable is declared as the value 10 is assigned to it.
    
    

    There are a certain rules that we have to keep in mind while declaring a variable:

    1. The variable name cannot start with a number. It can only start with a character or an underscore.
    2. Variables in python are case sensitive.
    3. They can only contain alpha-numeric characters and underscores.
    4. No special characters are allowed.

    There are several data types in python. Lets take a look at the data types in python.

    Every value that we declare in python has a data type. Data types are classes and variables are the instances of these classes.

    Data Types In Python

    According to the properties they possess, there are mainly six data types in python. Although there is one more data type range which is often used while working with loops in python.

    types of data types-variables and data types in python-edureka

    Numerical Data Types

    Numerical data type holds numerical value. In numerical data there are 4 sub types as well. Following are the sub-types of numerical data type: 

    1. Integers
    2. Float
    3. Complex Numbers
    4. Boolean

    Integers are used to represent whole number values.

    
    x = 100
    y = 124
    # it will be the integer as long as the value is a whole number.
    
    

    To check the type of any variable data type, we can use the type() function. It will return the type of the mentioned variable data type.

    Float data type is used to represent decimal point values.

    
    x  = 10.25
    y = 12.30
    

    Complex numbers are used to represent imaginary values. Imaginary values are denoted with ‘j’ at the end of the number.

    
    x = 10 + 5j
    
    

    Boolean is used for categorical output, since the output of boolean is either true or false.

    
    num = 5 > 4
    #num is the boolean variable
    type(num)
    #the output will be bool
    print(num)
    #this will print true.
    

    Strings

    Strings in python are used to represent unicode character values. Python does not have a character data type, a single character is also considered as a string.

    We denote or declare the string values inside single quotes or double quotes. To access the values in a string, we use the indexes and square brackets.

    indexes-variables and data types in python-edureka

    name = 'edureka'
    name[2] 
    #this will give you the output as 'u'
    

    Strings are immutable in nature, which means you cannot change a string once replaced. 

    Command line input for strings

    x = input()
    print( 'hello' , x)
    

    Operations using strings

    
    name = 'edureka'
    name.upper()
    #this will make the letters to uppercase
    name.lower()
    #this will make the letters to lowercase
    name.replace('e') = 'E'
    #this will replace the letter 'e' with 'E'
    name[1: 4]
    #this will return the strings starting at index 1 until the index 4.
    
    

    Now that we have understood numbers and strings, lets understand the relatively complex data types.

    Lists

    List is one of the four collection data type that we have in python. When we are choosing a collection type, it is important to understand the functionality and limitations of the collection. Tuple, set and dictionary are the other collection data type is python.

    A list is ordered and changeable, unlike strings. We can add duplicate values as well. To declare a list we use the square brackets.

    
    mylist = [10,20,30,40,20,30, 'edureka']
    
    

    Accessing values from a list

    We use indexes to access values from a string.

    
    mylist[2:6]
    
    #this will get the values from index 2 until index 6.
    
    

    Adding/Replacing values in a list

    
    mylist[6] = 'python'
    
    #this will replace the value at the index 6.
    
    mylist.append('edureka')
    
    #this will add the value at the end of the list.
    
    mylist.insert(5, 'data science')
    
    #this will add the value at the index 5.
    
    

    Other operations that we can perform on a list are following:

                      Method Name                                  Property     
    clear() removes all the elements from the list
    copy() returns a copy of the list
    extend() add the elements of the list to the end of the current list
    count() returns the number of elements of the specified value
    index() returns the index of the element
      pop() removes the element from the specified position
    remove() removes the item with the specified value
    sort() sorts the list
    reverse() returns the reversed list

    Lists can store any data type as items. Be it numbers, strings or any other data type as well.

    
    a = [10,20,30]
    
    b = [60 , 50 , 40, a]
    
    #to access a value from the list a we can write
    
    b[3][2]
    
    #this will return 30 as output.
    
    

    Lets understand the next collection data type in python i.e tuples.

    Tuples

    Tuple is a collection which is unchangeable or immutable. It is ordered and the values can be accessed using the index values. A tuple can have duplicate values as well. To declare a tuple we use the round brackets.

    
    mytuple = (10,10,20,30,40,50)
    
    #to count the number of elements
    
    mytuple.count(10)
    
    #the output will be 2
    
    #to find the index
    
    mytuple.index(50)
    
    #the output will be 5. since the index number at 50 is 5.
    
    

    Since a tuple is unchangeable once you have declared it, there are not many operations you can perform on a tuple. But there is a bright side to using a tuple, you can store values in a tuple which you do not want to change while working in a project. Although you will be able to access the values, but there will not be any changes to be made.

    Sets

    A set is a collection which is unordered,  it does not have any indexes as well. To declare a set in python we use the curly brackets.

    
    myset = {10, 20 , 30 ,40, 50, 50}
    
    

    A set does not have any duplicate values, even though it will not show any errors while declaring the set, the output will only have the distinct values.

    To access the values in a set we can either loop through the set, or use a membership operator to find a particular value.

    for x in myset:
    print(x)
    #this will get all the values.
    20 in myset
    #this will  return true if the value is in the set.
    #to add a value in a set
    myset.add('edureka')
    #to add multiple values in a list
    myset.update([ 10, 20, 30, 40, 50])
    #to remove an item from a set
    myset.remove('edureka')
    #we can use the discard or pop method to remove an item from a set as well.
    myset = {10, 20, 30}
    myset1 = {10,30,50}
    myset.issubset(myset1)
    #this will return false
    myset.union(myset1)
    #this will return a set with the union of the two sets.
    
    
    Method Name Property
    clear() clears the items from a set
    copy() returns the copy of the set
    difference() returns a set with the difference of the two sets
    isdisjoint() returns if the sets have intersection
    issubset() returns if the set is a subset
    symmetricdifference() returns a set with the symmetric difference
    update() update the sets with union of the set

    Lets take a look at another collection data type which has key value pairs.

    Dictionary

    A dictionary is just like any other collection array in python. But they have key value pairs. A dictionary is unordered and changeable. We use the keys to access the items from a dictionary. To declare a dictionary, we use the curly brackets.

    
    mydictionary = { 'python': 'data science', 'machine learning' : 'tensorflow' , 'artificial intelligence': 'keras'}
    
    mydictionary['machine learning']
    
    #this will give the output as 'tensorflow'
    
    mydictionary.get('python')
    
    #this serves the same purpose to access the value.
    
    

    Since we are using the keys to access the items, they cannot be duplicate.The values can have duplicate items.

    Data Manipulation in a dictionary

    
    #adding a new value
    
    mydictionary['analysis'] = 'matplotlib'
    
    #replacing a value
    
    mydictionary['analysis'] = 'pandas'
    
    #deleting a value
    
    mydictionary.pop('analysis')
    
    #remove() , del also serves the same purpose for deleting a value.
    
    

    Other operations in a dictionary include the following.

    Method Name Property
    copy() returns a copy of the dictionary
    clear() clears the dictionary
    items() returns a list containing tuple of key value pairs
    keys() returns a list containing all the keys
    update() updates the dictionary with all the key-value pairs
    values() returns a list of all the values in a dictionary
    setdefault() returns the value of a specified key

    Range

    Range is a data type which is mainly used when we are using a loop. Lets take an example to understand this.

    
    for x in range(10):
    
    print(x)
    
    #this will print the numbers from 0-10. Range will have the numbers from 0-10
    
    

    Now that we have understood different data types that we have in python, there is another important concept of type casting which is helpful when we change from one data type into another. Lets understand the concept of type casting.

    Type Casting

    Type casting basically is the process of changing one data type into another. We have constructors for each of the data types in python.

    1. list()
    2. set()
    3. tuple()
    4. dict()
    5. str()
    6. int()
    7. float()

    We can simply use these constructors to use the specified data type or we can change a data type to another using these constructors. Lets understand this with an example.

    
    a = [ 10 , 20 ,30,40]
    
    #to change this list into a tuple i can simply write
    
    tuple(a)
    
    #now the list will change to a tuple.
    
    

    Using these constructors we can use various data types with the functionality of the other. Suppose we declare the list mentioned in the example as a tuple in a program, it will become immutable for that particular operation. Similarly we can use other constructors as well.

    Now that we have discussed variables and data types in python. I hope the properties of each data type and the operations are clear to you. If you want to kick-start your learning in python programming, you can refer to the edureka certification program for python programming. The curriculum is top notch and contains structured learning to master python.

    If you have any questions, write them in the comment section. We will get back to you.

    The post What Are Variables And Data Types In Python? appeared first on Edureka.

    Selenium Resume – Building an Impressive Test Engineer Resume

    $
    0
    0

    One thing you need to know when you want to apply for a job in the technical domain is to learn how to ace it. Taking a baby step towards understanding how to crack an interview, we’ll learn how to write an impressive Selenium resume. In this Selenium Resume article, you’ll understand why Selenium testing has great career opportunities.

    Let’s begin by looking at the topics to be covered in this blog:

    So we’ll start by learning about who exactly is an Automation Test Engineer.

    Selenium Resume: Who is an Automation Test Engineer?

    When an application or software is developed, it needs to be tested to see whether it gives the desired output or not. There are different ways to test an application. A person could manually test the application by giving inputs, checking the output and reporting it, or he could automate this process by executing a script.

    An Automation Tester is a person who writes the script to test the correctness of the application.

    Test Automation involves creating and applying technologies that control or monitor production and timely delivery of software products. Automated testing helps in reducing the time consumed to perform tedious tasks. 

    The duty of a test automation engineer includes designing, programming, simulating and deploying effective test automation solutions. The main objective of a test automation engineer is to automate as much of the testing as possible with a minimum set of code or scripts.

    An automation Tester designs the test cases by creating scripts that check the functionalities automatically. Automated testing entirely relies on the pre-scripted test which runs automatically to compare actual result with the expected results. Therefore, an Automation tester plays a superior role in making the application defect free.

    Automation - tester- Selenium resume- Edureka

    Let’s see the job description of an automation tester.

    Job Description of an Automation Test Engineer

    The simplest way to start building a Test Automation resume is by looking at the job description. This is the job description of one of the top companies Squareroot where you will find Selenium as one of the must-know tools.

    Selenium Test Engineer Job Responsibilities - Selenium Resume - Edureka

    This job description may vary based on the organization’s requirement. Now, let’s see the roles and responsibilities of an automation tester.

    Roles & Responsibilities of an Automation Test Engineer

    To be a successful automation tester, you need to know what you are intended to do. I have tried pointing out the major roles and responsibilities of an automation test Engineer:

    • Investigate the problems in the software
    • Identify & resolve all the bugs in the system
    • To define the test strategies
    • Designing and writing the test automation scripts
    • To develop, design test strategies for functional, non-functional and performance testing
    • To process, implement and monitor testing
    • To ensure the timely delivery of various testing milestones
    • Self-development skills to keep up to date with the trends

    An automation tester is not limited to these responsibilities,  it might vary according to the job requirements.

    Now that you guys have got a clear idea about the roles and the responsibilities of an automation tester, we’ll see the skills one must possess in order to become a prominent tester.

    Selenium Test Engineer Resume | Edureka

    Selenium Resume: Skills Required

    Give me six hours to chop down a tree and I will spend the first four sharpening the axe.”
    – Abraham Lincoln

    Similar to how sharpening the axe plays a major role in cutting a tree, skills play a major role in clearing an interview. One needs to know the basics of manual testing in order to understand what happens to the process if it is automated. This is a must to know skill in the field of testing.

    I have differentiated the skill set according to the experience level. First, we’ll check out the required skills for a fresher:

    • One must have basic knowledge of the test architecture
    • Solid understanding of computer languages and software development
    • Knows how to design the test frameworks
    • Should be well versed in creating test scripts
    • Ability to troubleshoot problems
    • Should possess creative thinking skills
    • Ability to communicate well

    Now let’s see the skills required by an experienced Automation Test Engineer:

    • Minimum 2-5 years of experience working in the software development field
    • At least 3+ years of hands-on testing experience
    • 3+ years in building, leading and managing product testing
    • Demonstrate leadership in developing and delivering test plans
    • Experience in working on the product lifecycle
    • Develop innovative strategies to improve the effectiveness of testing
    • Experience in working across Linux & Windows-based development
    • Understand business goals and specifications thoroughly

    The ones listed above are the basic skillset one company would ask for. This might vary from one company to another.

    Now that you have seen the skills required to ace an interview, we’ll see the Selenium job trends that have been increasing in the past years.

    Selenium Resume: Selenium Job Trends

    Selenium is one of the most widely used automation testing tools which one must master to build a career in the field of testing. There are many organizations that offer jobs for roles such as test engineer, test analyst, test manager, QA analyst, and whatever you name it. So, the vacancies are also increasing as the pay scale for this job is high. Below graph shows us the latest job trends.

    Job trends - Selenium resume - Edureka

    As you can see there is an exponential growth in the vacancies for the testing jobs, people take up both permanent as well as contract jobs as per their preference. The median salary specified according to ITJobsWatch is € 50,000. So if any of you want to become a successful automation tester, now is the right time to start working for it.

    Let’s understand the salary acquired by an automation tester.

    Selenium Resume: Salary Trends

    Now let’s talk about the stats. How much does an automation tester make in a year?

    • Software testing offers the most promising jobs across the globe which sums up to a total of $83,000 a year in the US.
    • Selenium is globally rated as a top priority in the test automation field scaling up from 29% to 36% people taking up testing as their career option. So, as a test automation engineer, one must master Selenium.
    • According to a recent survey, the average salary of an automation tester ranges between Rs 396,736 – Rs 1,525,969.
    • According to PayScale, the average pay for a Selenium Tester is $83,200 per year.  

    This is how Selenium tester’s value is been increasing in the recent past.

    Now let’s move on and see what are the basic factors we should consider while writing a Selenium resume.

    Key Points to be Considered while Writing a Resume

    To build an effective resume, we need to consider a few things.

    • A resume is the first impression in front of the interviewer.
    • It can be written in two ways, namely: Chronological and Functional
    • Chronological: This is a traditional way of writing a resume where you specify your experience according to the time it took place. It is generally used in the conservative fields.
    • Functional: This is a whole new approach where you mention your most relevant experience based on the required skills. This is a more simple way to portray yourself in front of an interviewer.
    • Your resume should be simple, concise and up to date.
    • The message should be clear.
    • For people who have less than 8 years of experience, should have a single page of resume.
    • Give priorities to those skills that are relevant to the job.
    • Do not forget about mentioning your achievements and your hobbies because this helps in breaking the ice with the interviewer.

    Now let’s move on to the most important part of this article and understand how to write a Selenium resume.

    Sample Selenium Resume

    sample resume - Selenium resume - Edureka

    First thing you need to know while you are writing your resume is to maintain proper alignment. This eventually catches the eye of an interviewer.

    • The introduction should be simple and should be up to mark.
    • Next is your education details. This should be covered in the order of your latest degree.
    • Followed by this will be your experience in this field.
    • Don’t worry if you are a fresher, you can mention the projects that you’ve worked on and justify your role in it.
    • If you are experienced, mention your latest job role and the projects you have worked on & your achievements in the previous organization.
    • Do mention your technical skills which specifies what you are good at.
    • Last, but not least, do mention your achievements and hobbies. Try not to talk more about this because it might distract the interviewer. Try keeping it simple.

    Now with this, we come to an end to this “Selenium resume” blog. I Hope you guys enjoyed this article and understood how to write a creative resume on your own. Now that you have understood the easiest way to build your resume, check out the Selenium Certification Course by Edureka, a trusted online learning company with a network of more than 650,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete Selenium features and its importance in testing software. Got a question for us? Please mention it in the comments section of “Selenium resume” and we will get back to you.

    The post Selenium Resume – Building an Impressive Test Engineer Resume appeared first on Edureka.

    Know how to build REST API with Node.js from scratch

    $
    0
    0

    Since the invention of WWW, various web technologies like RPC or SOAP were used to create and implement web services. But these technologies used heavy definitions for handling any communication task. Thus, REST was developed which helped in reducing the complexities and provided an architectural style in order to design the network-based application. Since Node.js technology is revolutionizing the server for the front-end developers, in this article I will be demonstrating the process of Building REST API with Node.js from scratch.

    Below are the topics that I will be covering in this article:

    What is REST API?

    REST or RESTful stands for REpresentational State Transfer. It is an architectural style as well as an approach for communications purpose that is often used in various web services development. In simpler terms, it is an application program interface (API) which makes use of the HTTP requests to GET, PUT, POST and DELETE the data over WWW.

    REST architectural style helps in leveraging the lesser use of bandwidth which makes an application more suitable for the internet. It is often regarded as the “language of the internet”. It is completely based on the resources where each and every component is regarded as a component and a single resource is accessible through a common interface using the standard HTTP method.

    To understand better, let’s dive a little deeper and see how exactly does a REST API work. Basically, the REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but requires a lot of effort to be built from the very scratch.

    The main functions used in any REST based architecture are:

    • GET − Provides read-only access to a resource.
    • PUT − Creates a new resource.
    • DELETE − Removes a resource.
    • POST − Updates an existing resource or creates a new resource.

    But all who claims cannot be referred to as RESTful API. In order to be regarded as a RESTful API, your application must satisfy certain constraints or principles. In the next section of this article on Building a REST API using Node.js, I will be talking about these principles in detail.

    Principles of REST

    Well, there are six ground principles laid down by Dr. Fielding who was the one to define the REST API design in 2000. Below are the six guiding principles of REST:

    1. Stateless
      Requests sent from a client to the server contains all the necessary information that is required to completely understand it. It can be a part of the URI, query-string parameters, body, or even headers. The URI is used for uniquely identifying the resource and the body holds the state of the requesting resource. Once the processing is done by the server, an appropriate response is sent back to the client through headers, status or response body.
    2. Client-Server
      It has a uniform interface that separates the clients from the servers. Separating the concerns helps in improving the user interface’s portability across multiple platforms as well as enhance the scalability of the server components.
    3. Uniform Interface
      To obtain the uniformity throughout the application, REST has defined four interface constraints which are:
      • Resource identification
      • Resource Manipulation using representations
      • Self-descriptive messages
      • Hypermedia as the engine of application state
    4. Cacheable
      In order to provide a better performance, the applications are often made cacheable. It is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is defined as cacheable, then the client cache can reuse the response data for equivalent responses in the future. It also helps in helps in preventing the reuse of the stale data.
    5. Layered system
      The layers system architecture allows an application to be more stable by limiting the component behavior.  This architecture enables load balancing and provides shared caches for promoting scalability. The layered architecture also helps in enhancing the application’s security as components in each layer cannot interact beyond the next immediate layer they are in.
    6. Code on demand
      Code on Demand is an optional constraint and is used the least. It permits a clients code or applets to be downloaded and extended via the interface to be used within the application. In essence, it simplifies the clients by creating a smart application which doesn’t rely on its own code structure.

    Now that you know what is a REST API and what all you need to mind in order to deliver an efficient application, let’s dive deeper and see the process of building REST API using Node.js.

    Practical Demonstration: Building REST API using Node.js

    Here, we will be creating a simple CRUD REST application for Library Management using Node.js and Express.js. To build this application, you will need to install the following:

    1. Node.js
    2. Express.js
    3. Joi
    4. nodemon (Node Monitor)

    In this example, I will be using the WebStorm IDE to write and execute the codes. You can use any IDE or code editor according to your choice. So, let’s get started.

    First, you need to create your project directory. Next, open the command prompt and navigate to your project directory. Once there, you need to call npm using the below command:

    npm init

    When you hit enter, Node.js will ask you to enter some details to build the .json file such as:

    cmd npm - Building REST API with Node.js - EdurekaHere you can define your entry point along with several other information. For this demo, I will be using script.js as an entry point. Next, we will be installing Express.js using the below command:

    npm i express

    Finally, I will be installing a node monitoring package called nodemon. It keeps a watch on all the files with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to restart the Node.js server each time any changes are made. nodemon will implicitly detect the changes and restart the server for you.

    npm i -g nodemon

    package.json

    
    {
    "name": "samplerestapi",
    "version": "1.0.0",
    "description": "Edureka REST API with Node.js",
    "main": "script.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
    },
    "author": "Edureka",
    "license": "ISC",
    "dependencies": {
    "express": "^4.16.4",
    "joi": "^13.1.0"
    }
    }
    
    

    script.js

    
    const express = require('express');
    const Joi = require('joi'); //used for validation
    const app = express();
    app.use(express.json());
    
    const books = [
    {title: 'Harry Potter', id: 1},
    {title: 'Twilight', id: 2},
    {title: 'Lorien Legacies', id: 3}
    ]
    
    //READ Request Handlers
    app.get('/', (req, res) => {
    res.send('Welcome to Edurekas REST API with Node.js Tutorial!!');
    });
    
    app.get('/api/books', (req,res)=> {
    res.send(books);
    });
    
    app.get('/api/books/:id', (req, res) => {
    const book = books.find(c => c.id === parseInt(req.params.id));
    
    if (!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Ooops... Cant find what you are looking for!</h2>');
    res.send(book);
    });
    
    //CREATE Request Handler
    app.post('/api/books', (req, res)=> {
    
    const { error } = validateBook(req.body);
    if (error){
    res.status(400).send(error.details[0].message)
    return;
    }
    const book = {
    id: books.length + 1,
    title: req.body.title
    };
    books.push(book);
    res.send(book);
    });
    
    //UPDATE Request Handler
    app.put('/api/books/:id', (req, res) => {
    const book = books.find(c=> c.id === parseInt(req.params.id));
    if (!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Not Found!! </h2>');
    
    const { error } = validateBook(req.body);
    if (error){
    res.status(400).send(error.details[0].message);
    return;
    }
    
    book.title = req.body.title;
    res.send(book);
    });
    
    //DELETE Request Handler
    app.delete('/api/books/:id', (req, res) => {
    
    const book = books.find( c=> c.id === parseInt(req.params.id));
    if(!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;"> Not Found!! </h2>');
    
    const index = books.indexOf(book);
    books.splice(index,1);
    
    res.send(book);
    });
    
    function validateBook(book) {
    const schema = {
    title: Joi.string().min(3).required()
    };
    return Joi.validate(book, schema);
    
    }
    
    //PORT ENVIRONMENT VARIABLE
    const port = process.env.PORT || 8080;
    app.listen(port, () => console.log(`Listening on port ${port}..`));
    
    

    Now, the next step is to check whether the handlers are working properly or not. For that, we will use a Chrome extension called Postman. To install Postman you can visit here and click on ‘Add to Chrome’.

    postman - Building REST API with Node.js - EdurekaOnce you have successfully installed Postman, open it and start testing your application. So, let’s start off by testing our GET method. Now, in order to do that you need to select GET from the drop-down list, type in the defined URI and hit send. If your code is working fine, then you will see the list of all the books which we have added manually in our code. In the below picture, you can see how my result looks like.

    GET - Building REST API with Node.js - EdurekaNow, let’s try adding a new book to our inventory list. For that, select ‘POST’ from the drop-down list and type in the defined URI for the POST method. Now, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as depicted in the below image. Now, in the text area, type in the title of your book as shown and hit send.

    POST - Building REST API with Node.js - EdurekaIf your POST method is working fine, your response body will contain the book title along with the book id. Now, let’s try to update the book title. Currently, my book title is “Angels and Demons” which I will be updating to “Angels & Demons”. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT request’s  URI along with the book id you wish to update. Next in the ‘Body’,  type in the new book title and hit enter.

    PUT - Building REST API with Node.js - EdurekaThis will give you a response with the book id and updated book title.

    Finally, let’s send a ‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URI of the delete request handler along with the book details, you want to remove and hit enter. If your transaction is successful, you will see the complete details of the entry you have removed in the response body.DELETE - Building REST API with Node.js - Edureka

    Now, let’s send a GET request for our final list of books.

    GET ALL - Building REST API with Node.js - EdurekaAs you can see from the above screenshot, the response body contains a total of three books with the book id 3 missing as we have already deleted that entry.

    With this, we come to an end of this article on Building REST API with Node.js. I tried to keep the concepts simple and crisp.  Now, if you want to get into more details of Node.js, you can check out my article on Node.js Tutorial.

    If you found this “REST API with Node.js” relevant, check out the Node.js Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

    Got a question for us? Please mention it in the comments section of this REST API with Node.js and we will get back to you.

    The post Know how to build REST API with Node.js from scratch appeared first on Edureka.

    All You Need to Know About Selenium WebDriver Architecture

    $
    0
    0

    Testing the system against all odds is a challenging task and you need a tool which can help you in this process. One such predominantly used tool by Automation Testers is Selenium. If you are a beginner and wish to know how Selenium functions internally, then you have landed at the perfect place. In this article, I will give you brief insights about Selenium WebDriver Architecture.

    Below are the topics covered in this article:

    You may also go through this recording where you can understand the topics in a detailed manner with examples.

    What is Selenium?

    Selenium - Selenium WebDriver Architecture - EdurekaSelenium is an open source portable framework used to automate testing of web applications. It is highly flexible when it comes to testing functional and regression test cases. Selenium test scripts can be written in different programming languages like Java, Python, C# and many more. These test scripts can run across various browsers like Chrome, Safari, Firefox, Opera and also provides support across various platforms like Windows, Mac OS, Linux, Solaris. Selenium also supports cross browsing where the test cases run across various platforms simultaneously. It also helps in creating robust, browser-based regression automation suites and perform tests.

    I hope you understood the fundamentals of Selenium. Now let’s move further and understand various tools that are available in the Selenium Suite.

    Selenium Suite of Tools

    Selenium is mainly comprised of a suite of tools, which include:

    • Selenium IDE
    • Selenium RC
    • Selenium WebDriver
    • Selenium Grid

    Selenium Suite - Selenium WebDriver Architecture - Edureka

    Let’s understand the functionalities of each of these tools in more detail.

    Selenium IDE

    IDE (Integrated Development Environment) is a Firefox plugin. It is one of the simplest frameworks in the Selenium Suite. It allows us to record and playback the scripts. If you wish to create scripts using Selenium IDE, you need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

    Next, let’s see what is Selenium RC.

    Selenium RC

    Selenium RC, also known as Selenium 1, was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. It mainly relies on JavaScript for automation. It supports Ruby, PHP, Python, Perl and C#, Java, Javascript. It supports almost every browser out there.

    Note: Selenium RC is officially deprecated.

    Selenium WebDriver

    Selenium WebDriver is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It directly communicates with the browser and controls it. Selenium WebDriver supports various programming languages like – Java, C#, PHP, Python, Perl, Ruby. and Javascript

    Selenium WebDriver supports the following:

    1. Operation System Support – Windows, Mac OS, Linux, Solaris
    2. Browser Support – Mozilla Firefox, Internet Explorer, Google Chrome 12.0.712.0 and above, Safari, Opera 11.5 and above, Android, iOS, HtmlUnit 2.9 and above.

    Selenium Grid

    Selenium Grid is a tool which is used together with Selenium RC. It is used to run tests on different machines against different browsers in parallel. Which implies – running multiple tests at the same time against different machines running different browsers and operating systems.

    So this was all about the Selenium Suite of Tools. Let’s dive deeper into this article and learn the functionalities and various components of Selenium WebDriver Architecture.

    Selenium WebDriver Architecture

    In order to understand Selenium WebDriver Architecture, we should first know what is a WebDriver API. Selenium Webdriver API helps in communication between languages and browsers. Each and every browser has different logic of performing actions on the browser. Below image depicts various components of Selenium WebDriver Architecture.

    Selenium Architecture - Selenium WebDriver Architecture - EdurekaIt comprises four main components which are:

    1. Selenium Client Library
    2. JSON WIRE PROTOCOL Over HTTP Client
    3. Browser Drivers
    4. Browsers

    Let’s understand each of these components in depth.

    1. Selenium Client Libraries/Language Bindings

    Selenium supports multiple libraries such as Java, Ruby, Python, etc. Selenium Developers have developed language bindings to allow Selenium to support multiple languages. If you wish to know more about libraries, kindly refer to the official site for Selenium libraries.

    2. JSON WIRE PROTOCOL Over HTTP Client

    JSON stands for JavaScript Object Notation. It is used to transfer data between a server and a client on the web. JSON Wire Protocol is a REST API that transfers the information between HTTP server. Each BrowserDriver (such as FirefoxDriver, ChromeDriver, etc.) has its own HTTP server.

    3. Browser Drivers

    Each browser contains a separate browser driver. Browser drivers communicate with the respective browser without revealing the internal logic of the browser’s functionality. When a browser driver has received any command then that command will be executed on the respective browser and the response will go back in the form of an HTTP response.

    4. Browsers

    Selenium supports multiple browsers such as Firefox, Chrome, IE, Safari, etc.

    Now let’s move further and know how exactly Selenium functions internally with the help of the below example.

    Demo

    In real time, you write a code in your UI (say Eclipse IDE) using any one of the supported Selenium client libraries (say Java).

    Example:

    The post All You Need to Know About Selenium WebDriver Architecture appeared first on Edureka.

    Viewing all 1753 articles
    Browse latest View live