code-rag-bench/online-tutorials huggingface dataset:
Difference between YAML(.yml) and .properties file in Java SpringBoot - GeeksforGeeks

30 Jun, 2021
These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. 
YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properties while developing the applications. 
If you have ever used Elastic Search instance and MongoDB database, both of these applications use YAML(.yml) as their default configuration format. 
Example:  
#.yml file

some_key:value
some_number:9
some_bool:true
Nesting: For nesting, the .yml file support hierarchy using spaces.  
# .yml file

somemap:
  key:value #use space not tab
  number:9

#inline format                         
  map2: {bool=true, date=2016-01-01}
Let’s define a list in such files: YAML as part of its specification supports the list.  
#.properties file

# A List
numbers[0] = one
numbers[1] = two

# Inline List
numbers = one, two
.properties File: This file extension is used for the configuration application. These are used as the Property Resource Bundles files in technologies like Java, etc. 
Example:  
#.properties file

some_key = value
some_number = 9
some_bool = true
Nesting: For nesting, the .properties file support dot(.) notation. The inline format in the .yml file is very similar to JSON 
#.properties file

somemap.key = value 
somemap.number = 9

map2.bool = true
map2.date = 2016-01-01
Let’s define a list in such files: .properties file doesn’t support list but spring uses an array as a convention to define the list in the .properties file.  
#.yml file

numbers:
  - one # use a dash followed by space
  - two

# Inline List
numbers:[one, two]
Table of Difference:  
What should I use .properties or .yml file? 
Strictly speaking, .yml file is advantageous over .properties file as it has type safety, hierarchy and supports list but if you are using spring, spring has a number of conventions as well as type conversions that allow you to get effectively all of these same features that YAML provides for you. 
One advantage that you may see out of using the YAML(.yml) file is if you are using more than one application that read the same configuration file. you may see better support in other languages for YAML(.yml) as opposed to .properties. 
simmytarika5
surinderdawra388
Java-Properties
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
How to print exception messages in android?

This example demonstrate about How to print exception messages in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="100dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </TextView>
</LinearLayout>
In the above code, we have taken textview to show exception message.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
   TextView text;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      text = findViewById(R.id.text);
      try {
         int a = 0;
         int b = 10;
         int result = b/a;
         System.out.println(result);
      } catch(Exception e) {
         text.setText(e.toString());
         e.printStackTrace();
      }
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
RequireJS - Defining Function

The define() function can be used to load the modules (module can be an object, function, class or a code which is executed after loading a module). You can load different versions of the same module in the same page. The different versions can be analyzed in the same order, even if they are loaded in a different order.
define(['module1', 'module2'], function (module1, module2) {
   //define the module value by returning a value
   return function () {};
});

You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module. These modules can be passed as parameters of the definition function.
The following example shows the usage of the define() function while loading the modules. Create an html file with the name index.html and place the following code in it −
<!DOCTYPE html>
<html>
   <head>
      <title>Define() Function</title>
      <script data-main = "main" src = "require.js"></script>
   </head>
   
   <body>
      <h2>RequireJS Define() Function Example</h2>
   </body>
</html>
Create a js file with the name main.js and add the following code in it −
define(function (require) {
   var myteam = require("./team");
   var mylogger = require("./player");
   alert("Player Name : " + myteam.player);
   mylogger.myfunc();
});
Now, create two more js files with the names team.js and player.js and place the following code respectively −
define({
   player: "Sachin Tendulkar",
   team : "India"
});
define(function (require) {
   var myteam = require("./team");

   return {
      myfunc: function () {
         document.write("Name: " + myteam.player + ", Country: " + myteam.team);
      }
   };
});
Open the HTML file in a browser; you will receive an output as in the following screenshot −
Click on the "OK" button, you will get another output from modules −
 Print
 Add Notes
 Bookmark this page
Python Program to Reverse a String Using Recursion

When it is required to reverse a string using recursion technique, a user defined method is used along with recursion.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
 Live Demo
def reverse_string(my_string):
   if len(my_string) == 0:
      return my_string
   else:
      return reverse_string(my_string[1:]) + my_string[0]
my_str = str(input("Enter the string that needs to be reversed : "))
print("The string is :")
print(my_str)
print("The reversed string is :")
print(reverse_string(my_str))
Enter the string that needs to be reversed : Williw
The string is :
Williw
The reversed string is :
williW
A method named ‘reverse_string’ is defined, that takes a string as a parameter.
It checks the length of the string, and if it is not 0, then, the function is called again on all elements except the first element of the string, and the first element of the string is concatenated to the result of this fuction call.
Outside the function, the user is asked to enter a string as input.
The string is displayed on the console.
The recursion function is called by passing this string as a parameter.
It is displayed on the console as the output.
Find the Number of Unique Pairs in an Array using C++

We require the appropriate knowledge to create several unique pairs in an array syntax in C++. In finding the number of unique pairs, we count all unique pairs in a given array, i.e., all possible pairs can be formed where each pair should be unique. For example −
Input : array[ ] = { 5, 5, 9 }
Output : 4
Explanation : The number of all unique pairs are (5, 5), (5, 9), (9, 5) and (9, 9).

Input : array[ ] = { 5, 4, 3, 2, 2 }
Output : 16
There are Two Approaches for this Solution and they are −
In this approach, we will traverse through each possible pair, add those pairs to a set, and finally find out the size of the set. The time complexity of this approach is O(n2 log n).
#include <bits/stdc++.h>
using namespace std;
int main () {
   int arr[] = { 5, 4, 3, 2, 2 };
   int n = sizeof (arr) / sizeof (arr[0]);
   // declaring set to store pairs.
   set < pair < int, int >>set_of_pairs;

   for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
         set_of_pairs.insert (make_pair (arr[i], arr[j]));

   int result = set_of_pairs.size();

   cout <<"Number of unique pairs : " << result;
   return 0;
}
Number of unique pairs : 16
In this code, first, we declare a set variable, and then, using two loops, we are traversing through each possible pair and inserting each pair in the set using i and j. Then we are calculating the size of the set and printing the result.
Another approach is to first find out the number of unique numbers in an array; now, every other unique element, including itself, may create a pair with any other unique element, so the number of unique pairs equals the square of the number of all unique numbers. The time complexity of his approach is O(n).
#include <bits/stdc++.h>
using namespace std;

int main () {
   int arr[] = { 5, 4, 3, 2, 2 };
   int n = sizeof (arr) / sizeof (arr[0]);

   // declaring set to store unique elements.

   unordered_set < int >set_of_elements;
   // inserting elements in the set.
   for (int i = 0; i < n; i++)
      set_of_elements.insert (arr[i]);

   int size = set_of_elements.size ();
   // finding number of unique pairs
   int result = size * size;

   cout << "Number of unique pairs in an array: " << result;
   return 0;
}
Number of unique pairs : 16
In this code, we declare a set and then go through each element of the array inserting every element in the set. After that, we calculated the size of the set and found the result from formula n2, and printed the output.
In this article, we solve the problem of finding the number of unique pairs in an array where we discuss two ways to solve the problem, i.e., simple and efficient. In a simple approach, we insert all possible pairs in a set with time complexity of O(n2 log n), and in an efficient approach, we find all unique numbers and find the result with n2. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.
java.lang.reflect.Method.getParameterTypes() Method Example

The java.lang.reflect.Method.getParameterTypes() method returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters.
Following is the declaration for java.lang.reflect.Method.getParameterTypes() method.
public Class<?>[] getParameterTypes()

the parameter types for the method this object represents.
The following example shows the usage of java.lang.reflect.Method.getParameterTypes() method.
package com.tutorialspoint;

import java.lang.reflect.Method;

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

      Method[] methods = SampleClass.class.getMethods();
      Class[] parameterTypes = methods[1].getParameterTypes();

      for(Class parameterType: parameterTypes){
         System.out.println(parameterType.getName());   
 
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}
Let us compile and run the above program, this will produce the following result −
java.lang.String

 Print
 Add Notes
 Bookmark this page
Erlang - Processes

The granularity of concurrency in Erlang is a process. A process is an activity/task that runs concurrently with and is independent from the other processes. These processes in Erlang are different than the processes and threads most people are familiar with. Erlang processes are lightweight, operate in (memory) isolation from other processes, and are scheduled by Erlang’s Virtual Machine (VM). The creation time of process is very low, the memory footprint of a just spawned process is very small, and a single Erlang VM can have millions of processes running.
A process is created with the help of the spawn method. The general syntax of the method is given below.
spawn(Module, Name, Args)

Module − This is a predefined atom value which must be ?MODULE.
Module − This is a predefined atom value which must be ?MODULE.
Name − This is the name of the function to be called when the process is defined.
Name − This is the name of the function to be called when the process is defined.
Args − These are the arguments which need to be sent to the function.
Args − These are the arguments which need to be sent to the function.
Returns the process id of the new process created.
An example of the spawn method is shown in the following program.
-module(helloworld). 
-export([start/0, call/2]). 

call(Arg1, Arg2) -> 
   io:format("~p ~p~n", [Arg1, Arg2]). 
start() -> 
   Pid = spawn(?MODULE, call, ["hello", "process"]), 
   io:fwrite("~p",[Pid]).
The following things need to be noted about the above program.
A function called call is defined and will be used to create the process.
A function called call is defined and will be used to create the process.
The spawn method calls the call function with the parameters hello and process.
The spawn method calls the call function with the parameters hello and process.
When we run the above program we will get the following result.
<0.29.0>"hello" "process"

Now let’s look at the other functions which are available with processes.
is_pid
This method is used to determine if a process id exists.
is_process_alive
This is called as is_process_alive(Pid). A Pid must refer to a process at the local node.
pid_to_list
It converts a process id to a list.
registered
Returns a list with the names of all registered processes.
self
One of the most commonly used BIF, returns the pid of the calling processes.
register
This is used to register a process in the system.
whereis
It is called as whereis(Name). Returns the pid of the process that is registered with the name.
unregister
This is used to unregister a process in the system.
 Print
 Add Notes
 Bookmark this page
What is the difference between pairs() vs. ipairs() in Lua?

In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table.
While both of them have some similarities, it is also good to know that they have some very notable differences that we should be aware of.
The first difference between the pairs() and ipairs() function is that the pairs() function doesn’t maintain the key order whereas the ipairs() function surely does.
Consider the example shown below −
 Live Demo
u={}
u[1]="a"
u[3]="b"
u[2]="c"
u[4]="d"
u["aa"] = "zz"
u[7] = "e"
for key,value in ipairs(u) do print(key,value) end
print(“---”)
for key,value in pairs(u) do print(key,value) end
In the example above, the ipairs() function will print the order of the key in numeric order, whereas the pairs() function doesn’t guarantee it.
Also, if we look at the example a bit more closely, we will see the second difference, and that is that the ipairs() function doesn’t return non-numeric keys that are present in the table.
Consider the output for the reference.
1   a
2   c
3   b
4   d
---
1   a
2   c
3   b
4   d
7   e
aa zz
Python program to check whether two lists are circularly identical

Here two lists are given. Our task is to check and found weather two given lists are circularly identical or not.
Input : A = [100, 100, 10, 10, 100]
        B = [100, 100, 100, 10, 10]
Output : True

True as when these elements in the list will circularly rotate then they would be similar to other given list 
Step 1: Create First and Second List.
Step 2: Then Lists are converted to map.
Step 3: join () method is used for converting the list objects into the string.
Step 3: doubling list A and converted to the map.
Step 4: compare two list. If result is true then Two Lists are circularly identical and if return false then they are circularly non identical.

# Python program to check and verify whether two lists are circularly identical or not

A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)

B=list()
n1=int(input("Enter the size of the Second List ::"))
print("Enter the Element of the Second List ::")
for i in range(int(n1)):
   k=int(input(""))
   B.append(k)

C=list()
n3=int(input("Enter the size of the Third List ::"))
print("Enter the Element of the Third List ::")
for i in range(int(n3)):
   k=int(input(""))
   C.append(k)

print("Compare First List and Second List ::>")
print(' '.join(map(str, B)) in ' '.join(map(str, A * 2)))
print("Compare Second List and Third List ::>")
print(' '.join(map(str, C)) in ' '.join(map(str, A * 2)))
Enter the size of the First List :: 5
Enter the Element of First  List ::
10
10
0
0
10
Enter the size of the Second List :: 5
Enter the Element of the Second List ::
10
10
10
0
0
Enter the size of the Third List :: 5
Enter the Element of the Third List ::
1
10
10
0
0
Compare First List and Second List ::>
True
Compare Second List and Third List ::>
False
How to Display an OpenCV image in Python with Matplotlib? - GeeksforGeeks

16 Aug, 2021
The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV.
First, let’s look at how to display images using OpenCV:
Now there is one function called cv2.imread() which will take the path of an image as an argument. Using this function you will read that particular image and simply display it using the cv2.imshow() function. 
Python3
# import required moduleimport cv2 # read the Image by giving pathimage = cv2.imread('gfg.png') # display that imagecv2.imshow('GFG', image)
Output:
DIsplay image using OpenCV
Now let’s jump into displaying the images with Matplotlib module. It is an amazing visualization library in Python for 2D plots of arrays. The Matplotlib module is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
We are doing minor changes to the above code to display our image with Matplotlib module. 
Python3
# import required moduleimport cv2import matplotlib.pyplot as plt # read imageimage = cv2.imread('gfg.png') # call imshow() using plt objectplt.imshow(image) # display that imageplt.show()
Output:
image plot with Matplotlib
One can also display gray scale OpenCV images with Matplotlib module for that you just need to convert colored image into a gray scale image.
Python3
# import required modulesimport cv2import matplotlib.pyplot as plt # read the imageimage = cv2.imread('gfg.png') # convert color image into grayscale imageimg1 = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # plot that grayscale image with Matplotlib# cmap stands for colormapplt.imshow(img1, cmap='gray') # display that imageplt.show()
Output:
Display grayscale image plot with Matplotlib
This is how we can display OpenCV images in python with Matplotlib module.
gabaa406
simmytarika5
Python-matplotlib
Python-OpenCV
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to split string by a delimiter str in Python?

Python's String class has a method called split() which takes a delimiter as optional argument. Default delimiter for it is whitespace. You can use it in the following way:
>>> 'aa-ab-ca'.split('-')
['aa', 'ab', 'ca']
>>> 'abc mno rst'.split(' ')
['abc', 'mno', 'rst']
You can also use regex for this operation. The re.split method takes a delimiter regex and the string and returns the list. For example:
>>> import re
>>> re.split('-', 'aa-ab-ca')
['aa', 'ab', 'ca']
>>>re.split(' ', 'abc mno rst')
['abc', 'mno', 'rst']
Vertex cover Problem

For an undirected graph, the vertex cover is a subset of the vertices, where for every edge (u, v) of the graph either u or v is in the set.
Using a binary tree, we can easily solve the vertex cover problem.
This problem can be divided into two sub-problems. When the root is part of the vertex cover. For this case, the root covers all children edges. We can simply find the size of vertex cover for left and right sub-tree, and add 1 for the root.
Input:
A binary tree.
Output:
The vertex cover is 3.
 
vertexCover(root node)
In this problem, one binary tree will be formed, each node will hold the data and number of vertices covered by that node.
Input − The root of the binary tree.
Output − The number of vertices covered by root.
Begin
   if root is φ, then
      return 0
   if root has no child, then
      return 0
   if vCover(root) ≠ 0, then
      return vCover(root)
   withRoot := 1 + vertexCover(left(root)) + vertexCover(right(root))
   withoutRoot := 0

   if root has left child, then
      withoutRoot := withoutRoot + vertexCover(left(left(root))) + vertexCover(left(right(root)))
   if root has right child, then
      withoutRoot := withoutRoot + vertexCover(right(left(root))) + vertexCover(right(right(root)))
   return vCover(root)
End
#include <iostream>
#include <algorithm>
using namespace std;

struct node {
   int data;
   int vCover;
   node *left, *right;
};

node *getNode(int data) {
   node *newNode = new (node);
   newNode->data = data;
   newNode->vCover = 0; //set vertex cover to 0
   newNode->left = NULL;
   newNode->right = NULL;
   return newNode;    //newly created node
}

int vertexCover(node *root) {
   if(root == NULL)    //when tree is empty
      return 0;
   if(root->left == NULL && root->right == NULL)    //when no other edge from root
      return 0;
         
   if(root->vCover != 0)   //when vertex cover of this node is found, leave that node
      return root->vCover;
         
   int sizeWithRoot = 1 + vertexCover(root->left) + vertexCover(root->right);
   int sizeWithOutRoot = 0;
   
   if(root->left != NULL)   //when root is not included and go for left child
      sizeWithOutRoot += 1 + vertexCover(root->left->left) + vertexCover(root->left->right);
   if(root->right != NULL)    //when root is not included and go for right child
      sizeWithOutRoot += 1 + vertexCover(root->right->left) + vertexCover(root->right->right);
   
   root->vCover = (sizeWithRoot < sizeWithOutRoot)?sizeWithRoot:sizeWithOutRoot; //minimum vertex cover
   return root->vCover;
}

int main() {
   //create tree to check vertex cover
   node *root = getNode(20);
   root->left = getNode(8); root->right = getNode(22);
   root->left->left = getNode(4); root->left->right = getNode(12);
   root->left->right->left = getNode(10); root->left->right->right = getNode(14);
   root->right->right = getNode(25);
   cout << "Minimal vertex cover: " << vertexCover(root);
}
Minimal vertex cover: 3
Python IMDbPY – Searching movies matching with keyword - GeeksforGeeks

11 May, 2021
In this article we will see how we can find movies that have similar keyword. Keyword is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discover titles.In order to get movies that have similar keywords we use get_keyword method. 
Syntax : imdb_object.get_keyword(keyword)Argument : It takes string as argument i.e keywordReturn : It return list of movies object  
Below is implementation.  
Python3
# importing the moduleimport imdb  # creating instance of IMDbia = imdb.IMDb()  # keywordkeyword = "marvel"  # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0])
Output : 
50
Thor: Love and Thunder
Another example 
Python3
# importing the moduleimport imdb  # creating instance of IMDbia = imdb.IMDb()  # keywordkeyword = "heaven"  # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0])
Output : 
50
The Good Place (2016–2020))
 
sweetyty
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Reduce decimals while printing in Arduino

Often some functions can output really long floating-point numbers, with several decimal digits. Several times, we are just interested in the first couple of decimal digits, and the remaining digits just reduce the readability and make the Serial Monitor window cluttered.
In order to round of floating-point numbers when printing to the Serial Monitor, you can just add the number of decimal places required as the second argument to serial.print.
An example is shown below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println("Printing decimals");
   Serial.println(9.6745,0); //This prints 10
   Serial.println(9.6745,1); //This prints 9.7
   Serial.println(9.6745,2); //This prints 9.67  
}
void loop() {
   // put your main code here, to run repeatedly:
   
}
The output of the above program on the Serial Monitor will be −
As indicated in the comments, for the same floating-point number, the output will be different each time because we have specified different number of decimal places to use. Try it out yourself. Please note that this works only when your first argument to Serial.print() is a pure floating-point number. If it is a string, this won't work.
Thus, Serial.println("9.6745",0); won't print just '9'. In fact, this line will give you an error −
no matching function for call to 'println(const char [7], int)'
How to get innerHTML of whole page in selenium driver?

We can get the innerHTML of the whole page in Selenium. We shall use the method getPageSource and print the values captured by it in the console.
String s = driver.getPageSource();
We can also get the HTML source code via Javascript commands in Selenium. We shall utilize executeScript method and pass the command return document.body.innerHTML as a parameter to the method.
JavascriptExecutor j = (JavascriptExecutor) driver;
String s = (String) j.executeScript("return document.body.innerHTML;");
Code Implementation with getPageSource.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageHTMLcode{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      // getPageSource method to obtain HTML of page
      System.out.println("Get HTML of page: "+ driver.getPageSource());
      driver.quit();
   }
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class PageHTMLcodeJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      // Javascript executor to obtain page HTML
      JavascriptExecutor j = (JavascriptExecutor) driver;
      String s = (String) j.executeScript("return document.body.innerHTML;");
      System.out.println("Get HTML of page: "+ s);
      driver.quit();
   }
}
How to find the area of an image contour Java OpenCV library?

Contours are nothing but the line joining all the points along the boundary of a particular shape. Using this you can −
Find the shape of an object.
Find the shape of an object.
Calculate the area of an object.
Calculate the area of an object.
Detect an object.
Detect an object.
Recognize an object.
Recognize an object.
You can find the contours of various shapes, objects in an image using the findContours() method. In the same way you can draw
You can also find the area of the shapes in the given input images. To do so you need to invoke the contourArea() method of the Imgproc class. This method accepts the contour of a particular shape, finds and returns its area.
Following java example finds the area of each shape/object in the given image, draw the outlines of the shapes with an area less great than 5000 in red and the remaining in white.
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class FindContourArea {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the contents of the image
      String file ="D:\\Images\\javafx_graphical.jpg";
      Mat src = Imgcodecs.imread(file);
      //Converting the source image to binary
      Mat gray = new Mat(src.rows(), src.cols(), src.type());
      Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
      Mat binary = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0));
      Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV);
      //Finding Contours
      List<MatOfPoint> contours = new ArrayList<>();
      Mat hierarchey = new Mat();
      Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE,
      Imgproc.CHAIN_APPROX_SIMPLE);
      Mat draw = Mat.zeros(src.size(), CvType.CV_8UC3);
      for (int i = 0; i < contours.size(); i++) {
         Scalar color = new Scalar(0, 0, 255);
         //Calculating the area
         double cont_area = Imgproc.contourArea(contours.get(i));
         System.out.println(cont_area);
         if(cont_area>5000.0){
            Imgproc.drawContours(draw, contours, i, color, 2,
            Imgproc.LINE_8, hierarchey, 2, new Point() ) ;
         } else {
            color = new Scalar(255, 255, 255);
            Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8,
            hierarchey, 2, new Point() ) ;
         }
      }
      HighGui.imshow("Contours operation", draw);
      HighGui.waitKey();
   }
}
Input Image
4091.0
6336.0
189.0
6439.0
4903.0
In addition to the above output, the above program generates the following window −
How does ++ and -- operators work in Python?

In C, C++, Java etc ++ and -- operators increment and decrement value of a variable by 1. In Python these operators won't work. 
In Python variables are just labels to objects in memory. In Python numeric objects are immutable. Hence by a++ (if a=10) we are trying to increment value of 10 object to 11 which is not allowed.
>>> a=10
>>> a++
SyntaxError: invalid syntax
Instead we have to use += operator
>>> a=a+1
>>> a
11
What is ViewData in ASP .Net MVC C#?

ViewData is a dictionary of objects that are stored and retrieved using strings as keys.
It is used to transfer data from Controller to View. Since ViewData is a dictionary, it
contains key-value pairs where each key must be a string. ViewData only transfers
data from controller to view, not vice-versa. It is valid only during the current request.
Storing data in ViewData −
ViewData["countries"] = countriesList;
Retrieving data from ViewData −
string country = ViewData["MyCountry"].ToString();
ViewData does not provide compile time error checking. For example, if we mis-spell
the key names we wouldn't get any compile time error. We will get to know about the
error only at runtime.
using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ViewResult Index(){
         ViewData["Countries"] = new List<string>{
            "India",
            "Malaysia",
            "Dubai",
            "USA",
            "UK"
         };
         return View();
      }
   }
}
@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in (List<string>)ViewData["Countries"]){
   <li>@country</li>
}
</ul>
What are the differences between tight coupling and loose coupling in Java?

Tight coupling means classes and objects are dependent on one another. In general, tight coupling is usually not good because it reduces the flexibility and re-usability of the code while Loose coupling means reducing the dependencies of a class that uses the different class directly.
The tightly coupled object is an object that needs to know about other objects and is usually highly dependent on each other's interfaces.
Changing one object in a tightly coupled application often requires changes to a number of other objects.
In the small applications, we can easily identify the changes and there is less chance to miss anything. But in large applications, these inter-dependencies are not always known by every programmer and there is a chance of overlooking changes.
 Live Demo
class A {
   public int a = 0;
   public int getA() {
      System.out.println("getA() method");
      return a;
   }
   public void setA(int aa) {
      if(!(aa > 10))
         a = aa;
   }
}
public class B {
   public static void main(String[] args) {
      A aObject = new A();
      aObject.a = 100; // Not suppose to happen as defined by class A, this causes tight coupling.
      System.out.println("aObject.a value is: " + aObject.a);
   }
}
In the above example, the code that is defined by this kind of implementation uses tight coupling and is very bad since class B knows about the detail of class A, if class A changes the variable 'a' to private then class B breaks, also class A's implementation states that variable 'a' should not be more than 10 but as we can see there is no way to enforce such a rule as we can go directly to the variable and change its state to whatever value we decide.
aObject.a value is: 100
Loose coupling is a design goal to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.
Loose coupling is a much more generic concept intended to increase the flexibility of the system, make it more maintainable and makes the entire framework more stable.
 Live Demo
class A {
   private int a = 0;
   public int getA() {
      System.out.println("getA() method");
      return a;
   }
   public void setA(int aa) {
      if(!(aa > 10))
         a = aa;
   }
}
public class B {
   public static void main(String[] args) {
      A aObject = new A();
      aObject.setA(100); // No way to set 'a' to such value as this method call will
                         // fail due to its enforced rule.
      System.out.println("aObject value is: " + aObject.getA());
   }
}
In the above example, the code that is defined by this kind of implementation uses loose coupling and is recommended since class B has to go through class A to get its state where rules are enforced. If class A is changed internally, class B will not break as it uses only class A as a way of communication.
getA() method
aObject value is: 0
C++ program to take integer and float as input and return their sum

Suppose we have two numbers a and b, a is integer and b is a float. We shall have to take them from standard input and display the sum.
So, if the input is like a = 10 b = 56.23, then the output will be Sum: 66.23
To solve this, we will follow these steps −
To display output into the standard output device we can use extraction operator (<<)
To display output into the standard output device we can use extraction operator (<<)
To take input from standard input we can use insertion operator (>>)
To take input from standard input we can use insertion operator (>>)
Let us see the following implementation to get better understanding −
#include <iostream>
using namespace std;
int main(){
   int a;
   float b;
   cout << "Enter numbers:" << endl;
   cin >> a >> b;
   cout << "Sum:" << a + b;
}

10, 56.23
Enter numbers:
Sum:10
Amazon Interview Experience for SDE Intern | On-Campus 2020 - GeeksforGeeks

14 Oct, 2020
Round 1: Round 1 was an online assessment that consisted of four parts:
Code Debugging – 7 questions to be debugged in 20 minutes.Coding Test – 2 coding questions to be solved in 70 minutes.Workstyles assessment – 20minutesReasoning ability – 35 minutes
Code Debugging – 7 questions to be debugged in 20 minutes.
Coding Test – 2 coding questions to be solved in 70 minutes.
Workstyles assessment – 20minutes
Reasoning ability – 35 minutes
Round 2: Shortlisted students from Round 1 went through round 2 which was a technical interview Round.
The interview was held on Amazon Chime. The interviewer was very nice. After 2-3 minutes of introduction, he went straight to Coding questions. I was given a link to the code editor, and he explained to me the problems. The interview lasted approximately 60 minutes.
Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities.Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters.
Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities.
Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters.
Example: 
Input : {"abc", "dgf", "qsvu", "xzy"}
Output : "abcdegfhijklmnopqrstvuwxzy"
The first round was only about two coding problems to test your knowledge of data structures and algorithms. I was not able to solve the second problem. I couldn’t make it to the 2nd technical interview.
Amazon
Marketing
On-Campus
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Zoho Interview | Set 1 (On-Campus)
How do I catch a Ctrl+C event in C++?

The CTRL + C is used to send an interrupt to the current executing task. In this program, we will see how to catch the CTRL + C event using C++.
The CTRL + C is one signal in C or C++. So we can catch by signal catching technique. For this signal, the code is SIGINT (Signal for Interrupt). Here the signal is caught by signal() function. Then one callback address is passed to call function after getting the signal.
Please see the program to get the better idea.
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <signal.h>
using namespace std;
// Define the function to be called when ctrl-c (SIGINT) is sent to process
void signal_callback_handler(int signum) {
   cout << "Caught signal " << signum << endl;
   // Terminate program
   exit(signum);
}
int main(){
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);
   while(true){
      cout << "Program processing..." << endl;
      sleep(1);
   }
   return EXIT_SUCCESS;
}
$ g++ test.cpp
$ ./a.out
Program processing...
Program processing...
Program processing...
Program processing...
Program processing...
Program processing...
^CCaught signal 2
$
How to do Web API versioning with URI in C# ASP.NET WebAPI?

Once a Web API service is made public, different client applications start using our
Web API services. As the business grows and requirements change, we may have to
change the services as well, but the changes to the services should be done in way
that does not break any existing client applications.
This is when Web API versioning helps. We keep the existing services as is, so we
are not breaking the existing client applications, and develop a new version of the
service that new client applications can start using.
One of the option to implement versioning is by using URI. Below is an example on
how to implement the same.
Let us consider a version 1 (V1) of sudent controller which has the following action
methods.
Student Model V1 −
namespace DemoWebApplication.Models{
   public class StudentV1{
      public int Id { get; set; }
      public string Name { get; set; }
   }
}
Student Controller V1 −
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class StudentV1Controller : ApiController{
      List<StudentV1> students = new List<StudentV1>{
         new StudentV1{
            Id = 1,
            Name = "Mark"
         },
         new StudentV1{
            Id = 2,
            Name = "John"
         }
      };
      [Route("api/v1/students")]
      public IEnumerable<StudentV1> Get(){
         return students;
      }
      [Route("api/v1/students/{id}")]
      public StudentV1 Get(int id){
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return studentForId;
      }
   }
}
In the above example we have used Attribute Routing to implement the versioning.
The output of the above example is shown below −
Now let us say in the student controller, business has proposed a new change only for
the new users and the existing users should still use the Version 1. So in this case we
have to introduce Version 2 (V2).
Student Model V2 −
namespace DemoWebApplication.Models{
   public class StudentV2{
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
   }
}
Student Controller V2 −
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class StudentV2Controller : ApiController{
      List<StudentV2> students = new List<StudentV2>{
         new StudentV2{
            Id = 1,
            FirstName = "Roger",
            LastName = "Federer"
         },
         new StudentV2{
            Id = 2,
            FirstName = "Tom",
            LastName = "Bruce"
         }
      };
      [Route("api/v2/students")]
      public IEnumerable<StudentV2> Get(){
         return students;
      }
      [Route("api/v2/students/{id}")]
      public StudentV2 Get(int id){
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return studentForId;
      }
   }
}
The output of the above example is shown below.
SQL Query to Calculate Total Number of Weeks Between Two Specific Dates

23 Apr, 2021
Here we will see, how to calculate the number of weeks between the two given dates with the help of SQL query using DATEDIFF() function.
For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Use the below SQL statement to switch the database context to geeks:
USE geeks;
We have the following demo table in our geeks database.
CREATE TABLE demo_orders(
ORDER_ID INT IDENTITY(1,1) PRIMARY KEY,
ITEM_NAME VARCHAR(30) NOT NULL,
ORDER_DATE DATE NOT NULL
);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS demo_orders;
Use the below statement to add data to the demo_orders table:
INSERT INTO demo_orders --no need to mention columns explicitly as we are inserting
                        --into all columns and ID gets
                          --automatically incremented.
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
To verify the contents of the table use the below statement:
SELECT * FROM demo_orders;
Now let’s find the number of weeks between the dates of the order of ‘Maserati’ and ‘Ferrari’ in the table using DATEDIFF() function.
Below is the syntax for the DATEDIFF() function to find the no. of weeks between two given dates.
Syntax: DATEDIFF(week or ww or wk, <start_date>, <end_date>);
Example: 
DECLARE 
@start VARCHAR(10) = (
  SELECT order_date FROM demo_orders
  WHERE item_name = 'Maserati'),
@end VARCHAR(10) = (
  SELECT order_date FROM demo_orders
  WHERE item_name = 'Ferrari')
  

--@start variable holds the start date(i.e date of Maserati being purchased).

--@end variable holds the end date (i.e date of Ferrari being purchased).

SELECT DATEDIFF(ww, @start, @end) AS number_of_weeks;
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL | DROP, TRUNCATE