code-rag-bench/online-tutorials huggingface dataset:
Python – Surrounding elements to K

12 Nov, 2020
Given Matrix, from each row, get surrounding elements of K, if present.
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 6 Output : [[7, 3], [5], [], [1]] Explanation : All elements surrounded by 6 are extracted.
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 1 Output : [[], [], [2], [6, 2]] Explanation : All elements surrounded by 1 are removed.  
Method #1: Using index() + loop + try/except
In this, we check for the index of elements using index(), and then get the required surrounding elements by accessing next and previous elements. If the element is not present, an empty list is returned.
Python3
# Python3 code to demonstrate working of # Surrounding elements to K# Using index() + loop + try/except  # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing K K = 6  res = []for sub in test_list:          # getting index     try :        idx = sub.index(K)    except Exception as e :        res.append([])        continue          # appending Surrounding elements    if idx != 0 and idx != len(sub) - 1:        res.append([sub[idx - 1], sub[idx + 1]])    elif idx == 0:        res.append([sub[idx + 1]])    else : res.append([sub[idx - 1]])  # printing result print("The Surrounding elements : " + str(res))
Output:
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]]
Method #2 : Using index() + in operator + loop
In this, we check if the element is present in a row before application of index(), to avoid using try/except block. Rest all functionalities are the same as the above method.
Python3
# Python3 code to demonstrate working of# Surrounding elements to K# Using index() + in operator + loop  # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing KK = 6  res = []for sub in test_list:      # getting index    # checking for element presence in row    if K in sub:        idx = sub.index(K)    else:        res.append([])        continue      # appending Surrounding elements    if idx != 0 and idx != len(sub) - 1:        res.append([sub[idx - 1], sub[idx + 1]])    elif idx == 0:        res.append([sub[idx + 1]])    else:        res.append([sub[idx - 1]])  # printing resultprint("The Surrounding elements : " + str(res))
Output:
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Debugging decorators in Python

21 Aug, 2020
Decorators in Python are really a very powerful feature. If you are a web developer and you have used the Django framework or even some other development frameworks you would have already come across decorators.
For an overview decorators are wrapper functions that wrap an existing function or a method and modify its features. Let’s take a short example. Consider that you have a speak function that returns a neutral message
Python3
def speak():    """Returns a neutral message"""    return "Hi, Geeks!"  # printing the outputprint(speak())
Output:
Hi, Geeks!

Suppose that you need to modify the function to return a message in a happy tone. So let’s create a decorator for this.
Python3
# decoratordef make_geek_happy(func):    def wrapper():        neutral_message = func()        happy_message = neutral_message + " You are happy!"        return happy_message    return wrapper  #using the decorator @make_geek_happydef speak():    """Returns a neutral message"""    return "Hi, Geeks!"  print(speak())
Output:
Hi, Geeks! You are happy!

In this way, the decorators can also be used to modify different functions and make them more useful. However, there are some drawbacks to this process. When we wrap the original function in a decorator the metadata of the original function gets lost. Consider the below program but this time we use the decorator in another way just to make you understand.
If you try to access any of the metadata of the positive_message function it actually returns the metadata of the wrapper inside the decorator. 
Python3
# decoratordef make_geek_happy(func):    def wrapper():        neutral_message = func()        happy_message = neutral_message + " You are happy!"        return happy_message    return wrapper  def speak():    """Returns a neutral message"""    return "Hi!"    # wrapping the function in the decorator# and assigning it to positive_messagepositive_message = make_geek_happy(speak)  print(positive_message())  print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__)
Output:
Hi! You are happy!
speak
Returns a neutral message
wrapper
None

These results make it really very difficult for debugging. But thanks to Python it also has a solution to fix this problem without much effort. We just need to use the functools.wraps() decorator included in the Python standard library.
Here’s an example:
Python3
# importing the moduleimport functools  # decoratordef make_geek_happy(func):    @functools.wraps(func)    def wrapper():        neutral_message = func()        happy_message = neutral_message + " You are happy!"        return happy_message    return wrapper  def speak():    """Returns a neutral message"""    return "Hi!"  positive_message = make_geek_happy(speak)print(positive_message())  print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__)
Output:
Hi! You are happy!
speak
Returns a neutral message
speak
Returns a neutral message

Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL - CAST DECIMAL to INT?

Cast DECIMAL to INT with the help of FLOOR() function. The syntax is as follows −
SELECT FLOOR(yourColumnName) from yourTableName where condition;
Let us first create a table. The following is the query to create a table.
mysql> create table DecimalToIntDemo
   -> (
   -> Amount DECIMAL(3,1)
   -> );
Query OK, 0 rows affected (0.88 sec)
Now you can insert records into the table with the help of insert command. The query is as follows −
mysql> insert into DecimalToIntDemo values(12.5);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DecimalToIntDemo values(50.4);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DecimalToIntDemo values(48.6);
Query OK, 1 row affected (0.10 sec)
Display all records with the help of select statement. The query is as follows −
mysql> select *from DecimalToIntDemo;
Here is the output −
+--------+
| Amount |
+--------+
|   12.5 |
|   50.4 |
|   48.6 |
+--------+
3 rows in set (0.00 sec)
Apply the above syntax which we discussed in the beginning. The query is as follows −
mysql> SELECT FLOOR(Amount) from DecimalToIntDemo
   -> where Amount > 10;
The following is the output that cast decimal to int −
+---------------+
| FLOOR(Amount) |
+---------------+
|            12 |
|            50 |
|            48 |
+---------------+
3 rows in set (0.00 sec)
Look at the above sample which gives only INT value.
Program to find the maximum number in rotated list in C++

Suppose there is an array, and that is sorted, consider that array is rotated at some pivot, that is unknown to us. So we have to find the maximum from that rotated array. So if the array is like[3,4,5,1,2], then the output will be 5.
To solve this, we will follow these steps −
low := 0 and high := last index of array, n := size of array, ans := 0
low := 0 and high := last index of array, n := size of array, ans := 0
while low <= highmid := low + (high - low)/2if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1
while low <= high
mid := low + (high - low)/2
mid := low + (high - low)/2
if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1
if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1
else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1
else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1
else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1
else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1
else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1
else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int search(vector <int>& arr, int low, int high){
      if(low == high){
         return arr[low];
      }
      int mid = low + (high - low) / 2;
      int ans = 0;
      if(arr[low] < arr[mid]){
         ans = max(arr[low], search(arr, mid, high));
      }
      else if (arr[high] > arr[mid]){
         ans = max(arr[mid], search(arr, low, mid));
      }
      else if(arr[low] == arr[mid]){
         ans = max(arr[low], search(arr, low + 1, high));
      }
      else if(arr[high] == arr[mid]){
         ans = max(arr[high], search(arr, low, high - 1));
      }
      return ans;
   }
   int findMax(vector<int>& nums) {
      return search(nums, 0, nums.size() - 1);
   }
};
main(){
   Solution ob;
   vector<int> v = {4,5,5,5,6,8,2,3,4};
   cout <<(ob.findMax(v));
}
[4,5,5,5,6,8,2,3,4]
8
DirectX - Buffers

For the GPU to access an array of vertices, they need to be placed in a special resource structure called a buffer, which is represented by the ID3D11Buffer interface.
A buffer that stores vertices is called a vertex buffer. Direct3D buffers not only store data, but also describe how the data will be accessed and where it will be bound to the rendering pipeline.
Because indices need to be accessed by the GPU, they need to be placed in a special resource structure — an index buffer. Creating an index buffer is very similar to creating a vertex buffer, except that the index buffer stores indices instead of vertices. Therefore, rather than repeating a discussion similar to the one carried out for vertex buffers, we just show an example of creating an index buffer −
UINT indices[24] = {
   0, 1, 2, // Triangle 0
   0, 2, 3, // Triangle 1
   0, 3, 4, // Triangle 2
   0, 4, 5, // Triangle 3
   0, 5, 6, // Triangle 4
   0, 6, 7, // Triangle 5
   0, 7, 8, // Triangle 6
   0, 8, 1 // Triangle 7
};
// Describe the index buffer we are going to create. Observe the
// D3D11_BIND_INDEX_BUFFER bind flag
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(UINT) * 24;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
// Specify the data to initialize the index buffer.
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = indices;
// Create the index buffer.
ID3D11Buffer* mIB;
HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB));
As with vertex buffers, and other Direct3D resources for that matter, before we can use it, we need to bind it to the pipeline. An index buffer is bound to the input assembler stage with theID3D11DeviceContext::IASetIndexBuffer method.
Following is an example call −
md3dImmediateContext->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0);

 Print
 Add Notes
 Bookmark this page
JavaScript RegExp - [^a-zA-Z]

[^a-zA-Z] matches any string not containing any of the characters ranging from a through z and A through Z.
Following example shows usage of RegExp expression.
<html>
   <head>
      <title>JavaScript RegExp</title>
   </head>
   
   <body>
      <script type = "text/javascript">
		 var str = "1323pabc";
         var pattern = /[^a-zA-Z]/g;

         var result = str.match(pattern);
         document.write("Test 1 - returned value : " +  result); 

         str = "abc";
         result = str.match(pattern);
         document.write("<br/>Test 2 - returned value : " +  result); 	 		 
      </script>
   </body>
</html>
Test 1 - returned value : 1,3,2,3
Test 2 - returned value : null


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C++ Program to Calculate Average of Numbers Using Arrays

Average of numbers is calculated by adding all the numbers and then dividing the sum by count of numbers available.
An example of this is as follows.
The numbers whose average is to be calculated are:
10, 5, 32, 4, 9
Sum of numbers = 60
Average of numbers = 60/5 = 12
A program that calculates average of numbers using arrays is as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int n, i;
   float sum = 0.0, avg;
   float num[] = {12, 76, 23, 9, 5};
   n = sizeof(num) / sizeof(num[0]);
   for(i = 0; i < n; i++)
   sum += num[i];
   avg = sum / n;
   cout<<"Average of all array elements is "<<avg;
   return 0;
}
Average of all array elements is 25
In the above program, the numbers whose average is needed are stored in an array num[]. First the size of the array is found. This is done as shown below −
n = sizeof(num) / sizeof(num[0]);
Now a for loop is started from 0 to n-1. This loop adds all the elements of the array. The code snippet demonstrating this is as follows.
for(i = 0; i < n; i++)
sum += num[i];
The average of the numbers is obtained by dividing the sum by n i.e amount of numbers. This is shown below −
avg = sum / n;
Finally the average is displayed. This is given as follows.
cout<<"Average of all array elements is "<<avg;
Terminal Control Functions in Python

To change the terminal controls in the Unix system, we can use the tty related methods in Python. Using the tty module, we can set two different modes of the terminal. The raw Mode and the cbreak mode.
To use the tty module, we should import it using −
import tty

There are some modules of the tty module, these are −
This method is used to change the terminal mode to raw mode. In the raw mode, the cursor moves to new line but the carriage return operation is not performed. Also we do not need to press Return key to send the input into the system, it automatically sends after writing it.
This method is used to change the terminal mode to cbreak mode. In this mode, the cursor moves to new line we do not need to press Return key to send the input into the system, it automatically sends after writing it.
import sys
import tty
import termios
file_desc = sys.stdin.fileno()
old_setting = termios.tcgetattr(file_desc)
tty.setraw(sys.stdin)
for i in range(5):
   char = sys.stdin.read(1)
   print("Char: " + str(char))
termios.tcsetattr(file_desc, termios.TCSADRAIN, old_setting)
$ python3 example.py
Char: K
   
   Char: E
      
      Char: 5
         
         Char: 2
            
            Char: @
C++ Program to Find Number of Articulation points in a Graph

Articulation Points (or Cut Vertices) in a Graph is a point iff removing it (and edges through it) disconnects the graph. An articulation point for a disconnected undirected graph, is a vertex removing which increases number of connected components.
Begin
   We use dfs here to find articulation point:
   In DFS, a vertex w is articulation point if one of the following two conditions is satisfied.
   1) w is root of DFS tree and it has at least two children.
   2) w is not root of DFS tree and it has a child x such that no vertex in subtree rooted with
       w has a back edge to one of the ancestors of w in the tree.
End
#include<iostream>
#include <list>
#define N -1
using namespace std;
class G {
   int n;
   list<int> *adj;
   //declaration of functions
   void APT(int v, bool visited[], int dis[], int low[],
   int par[], bool ap[]);
   public:
      G(int n); //constructor
      void addEd(int w, int x);
      void AP();
};
G::G(int n) {
   this->n = n;
   adj = new list<int>[n];
}
//add edges to the graph
void G::addEd(int w, int x) {
   adj[x].push_back(w); //add u to v's list
   adj[w].push_back(x); //add v to u's list
}
void G::APT(int w, bool visited[], int dis[], int low[], int par[], bool ap[]) {
   static int t=0;
   int child = 0; //initialize child count of dfs tree is 0.
   //mark current node as visited
   visited[w] = true;
   dis[w] = low[w] = ++t;
   list<int>::iterator i;
   //Go through all adjacent vertices
   for (i = adj[w].begin(); i != adj[w].end(); ++i) {
      int x = *i; //x is current adjacent
      if (!visited[x]) {
         child++;
         par[x] = w;
         APT(x, visited, dis, low, par, ap);
         low[w] = min(low[w], low[x]);
         // w is an articulation point in following cases :
         // w is root of DFS tree and has two or more chilren.
         if (par[w] == N && child> 1)
            ap[w] = true;
         // If w is not root and low value of one of its child is more than discovery value of w.
         if (par[w] != N && low[x] >= dis[w])
            ap[w] = true;
      } else if (x != par[w]) //update low value
         low[w] = min(low[w], dis[x]);
   }
}
void G::AP() {
   // Mark all the vertices as unvisited
   bool *visited = new bool[n];
   int *dis = new int[n];
   int *low = new int[n];
   int *par = new int[n];
   bool *ap = new bool[n];
   for (int i = 0; i < n; i++) {
      par[i] = N;
      visited[i] = false;
      ap[i] = false;
   }
   // Call the APT() function to find articulation points in DFS tree rooted with vertex 'i'
   for (int i = 0; i < n; i++)
      if (visited[i] == false)
         APT(i, visited, dis, low, par, ap);
      //print the articulation points
      for (int i = 0; i < n; i++)
         if (ap[i] == true)
            cout << i << " ";
}
int main() {
   cout << "\nArticulation points in first graph \n";
   G g1(5);
   g1.addEd(1, 2);
   g1.addEd(3, 1);
   g1.addEd(0, 2);
   g1.addEd(2, 3);
   g1.addEd(0, 4);
   g1.AP();
   return 0;
}
Articulation points in first graph
0 2
Difference between find Element and find Elements in Selenium

There are differences between findElement and findElements method in Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method returns a list of matching elements.
The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is
thrown by the findElement, however an empty list is returned by the findElements method.
A good usage of findElements method usage is counting the total number of images or accessing each of images by iterating with a loop.
WebElement i = driver.findElement(By.id("img-loc"));
List<WebElement> s =
driver.findElements(By.tagName("img"));
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 java.util.List;
public class FindElementFindElementMthds{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java      \\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm");
      //identify single element
      WebElement elm = driver.findElement(By.tagName("h2"));
      String s = elm.getText();
      System.out.println("Get text on element: " + s);
      //identify all elements with tagname
      List<WebElement> i = driver.findElements(By.tagName("img"));
      //count
      int c = i.size();
      System.out.println("Number of images: " + c);
      //browser close
      driver.close();
   }
}
Return Array from Functions in C++

C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −
int * myFunction() {
   .
   .
   .
}

Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows −
#include <iostream>
#include <ctime>

using namespace std;

// function to generate and retrun random numbers.
int * getRandom( ) {

   static int  r[10];

   // set the seed
   srand( (unsigned)time( NULL ) );
   
   for (int i = 0; i < 10; ++i) {
      r[i] = rand();
      cout << r[i] << endl;
   }

   return r;
}

// main function to call above defined function.
int main () {

   // a pointer to an int.
   int *p;

   p = getRandom();
   
   for ( int i = 0; i < 10; i++ ) {
      cout << "*(p + " << i << ") : ";
      cout << *(p + i) << endl;
   }

   return 0;
}
When the above code is compiled together and executed, it produces result something as follows −
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Repeating only even numbers inside an array in JavaScript

We are required to write a JavaScript function that should repeat the even number inside the
same array.
For example, given the following array −
const arr = [1, 2, 5, 6, 8];
We should get the output −
const output = [1, 2, 2, 5, 6, 6, 8, 8];
Therefore, let’s write the code for this function −
The code for this will be −
const arr = [1, 2, 5, 6, 8];
const repeatEvenNumbers = arr => {
   let end = arr.length -1;
   for(let i = end; i > 0; i--){
      if(arr[i] % 2 === 0){
         arr.splice(i, 0, arr[i]);
      };
   };
   return arr;
};
console.log(repeatEvenNumbers(arr));
The output in the console will be −
[
   1, 2, 2, 5,
   6, 6, 8, 8
]
HTML <area> coords Attribute

The cords attribute of the <area> element is used to set the coordinates of area in image map. Use the attribute with shape attribute and set the size & shape of an area.
Following is the syntax
<area coords="value">
Under the value above, you can set the following coordinates with different parameters −
Let us now see an example to implement the cords attribute of the <area> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Learning</h2>
<p>Learn these technologies with ease....</p>
<img src = /images/usemap.gif alt = "usemap" border = "0" usemap = "#tutorials"/>
<map name = "tutorials">
   <area shape = "poly" coords = "74,0,113,29,98,72,52,72,38,27"
      href = "/perl/index.htm" alt = "Perl Tutorial" target = "_blank" />
   <area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial"
      href = "/html/index.htm" target = "_blank" />
   <area shape = "circle" coords = "73,168,32" alt = "PHP Tutorial"
      href = "/php/index.htm" target = "_blank" />
</map>
</body>
</html>
In the above example, we have set the map on the following image −
<img src = /images/usemap.gif alt = "usemap" border = "0" usemap = "#tutorials"/>
Now, we have set the map and area within it for shape −
<map name = "tutorials">
   <area shape = "poly" coords = "74,0,113,29,98,72,52,72,38,27"
      href = "/perl/index.htm" alt = "Perl Tutorial" target = "_blank" />
   <area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial"
      href = "/html/index.htm" target = "_blank" />
   <area shape = "circle" coords = "73,168,32" alt = "PHP Tutorial"
      href = "/php/index.htm" target = "_blank" />
</map>
While setting the area, we have set the coordinates of the area with the cords attribute −
<area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial"
   href = "/html/index.htm" target = "_blank" />
GATE | GATE-CS-2014-(Set-3) | Question 12 - GeeksforGeeks

28 Jun, 2021
Let X and Y be finite sets and f: X -> Y be a function. Which one of the following statements is TRUE?(A) A(B) B(C) C(D) DAnswer: (D)Explanation:
Let x = {a, b, c} and y = {1, 2}
A Function f maps each element of x to 1 in y.
f(a)=1 , f(b)=1 , f(c) =1
A = {a, b} B = {b, c}
----------------------------------------------
A ]
| f(A u B) | = |f({a, b, c})| = 3
| f(A)|+|f(B)| = 2 + 2 = 4 , LHS != RHS.
----------------------------------------------
B ]
f(A ∩ B) = f({b}) = { 1 }
f(A) ∩ f(B) = {1, 1} ∩ {1, 1} = {1, 1}
LHS != RHS
-----------------------------------------------
C ]
|f(A ∩ B)| = |f({b})| = |{ 1 }| = 1
min{|f(A)|,|f(B)|} = min(2,2) = 2
LHS != RHS
-----------------------------------------------
D ] In a function a value can be mapped only to one value.
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
jQuery | remove() - GeeksforGeeks

13 Feb, 2019
The remove() method in JQuery used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements.Syntax:
$(selector).remove()

Return Value: It will return all the data of the selected elements deleted.Example 1:
Input: $("p").remove()
Output: Output will be all the elements of the paragraph get deleted.
Code 1:
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/                 libs/jquery/3.3.1/jquery.min.js">        //this is JQuery CDN directed from the JQuery website    </script>    <script>        $(document).ready(function() {            $("button").click(function() {                $("p").remove();            });        });    </script></head>  <body>    <div style="padding-left:220px;padding-top:100px;">        <p style="font-size:35px;">Welcome to GFG!!!.</p>        <button style="padding:15px;">Click ME</button>    </div></body>  </html>
Output:Before clicking the button :After clicking on button :We can also find and remove elements using its class name with the help of JQuery remove() method.Syntax:
$(".class_name").remove()

Return value: It will return all the portion deleted on the page with the class name.Example 2:
Input: $(".geek").remove()
Output: Here "gfg!!!" get deleted. 
Code #2:
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs                /jquery/3.3.1/jquery.min.js">        //this is JQuery CDN directed from the JQuery website    </script>    <script>        $(document).ready(function() {            $("button").click(function() {                $(".geeks").remove();            });        });    </script></head>  <body>    <div style="margin-left:180px; font-size:35px;padding-top:100px">        <p class="geeks">Welcome to GFG!!!.</p>        <p class="geeks">Hello, My class is geeks</p>        <button>Click ME</button>    </div></body>  </html>
Output:Before clicking on button :After clicking on button :Except button everything get remove
jQuery-HTML/CSS
JavaScript
JQuery
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 PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to add options to a select element using jQuery?
Software Serial in Arduino

The SoftwareSerial library was developed to ensure that any pins of Arduino can exchange Serial data with other peripherals, like GNSS receivers, using software. Arduino Uno, for example, has only one HardwareSerial port (pins 0 and 1), which is connected to the USB via the USB to UART conversion chip. Thus, if you have any other peripheral that requires serial communication, in the absence of SoftwareSerial, you’d have to do away with USB Serial communication.
SoftwareSerial has some limitations −
If you are using multiple SoftwareSerial ports, only one can receive data at a time
If you are using multiple SoftwareSerial ports, only one can receive data at a time
Speeds can be up to a maximum of 115200 bps
Speeds can be up to a maximum of 115200 bps
Other limitations of this library, specific to some Arduino boards, can be found here.
The SoftwareSerial library is included in Arduino IDE Versions 1.0 and above, and you don’t need to install it separately. Defining the Software Serial is very straightforward. An example is shown below −
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
As you can see, you need to create a SoftwareSerial object using two arguments − the RX pin and the TX pin. The other functions are similar to Serial. For example,
Serial.begin(9600) translates to mySerial.begin(9600)
Serial.println("Hello World") has the equivalent mySerial.println("Hello World") and so on.
You are encouraged to go through the examples that come in with the SoftwareSerial library. They can be found in File → Examples → SoftwareSerial.
How to find index of last occurrence of a substring in a string in Python?

Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of last occurrence if found, else -1. You can use it as follows:
>>> 'some of the some'.rfind('some')
12
>>> 'some of the some'.rfind('none')
-1
>>> "NikolaTesla".rfind('kola')
2
How to handle proxy in Selenium in Java?

We can handle proxy in Selenium in Java with the help of PROXY class.
import java.io.IOException;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class ProxySelJav {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      WebDriver driver;
      String prox = "localhost:8080";
      // set browser settings with Desired Capabilities
      Proxy p = new Proxy(); p.setHttpProxy(prox).setFtpProxy(prox).setSslProxy(prox)
      .setSocksProxy(prox);
      DesiredCapabilities c = new DesiredCapabilities();
      c.setCapability(CapabilityType.PROXY, p);
      // utilize capabilities on launching browser driver
      driver = new Firefox(c);
   }
}
C/C++ Program for Linear Search

11 Jun, 2022
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. 
ALGORITHM :Step 1: Start Step 2: Declare an array, and search data variable-x.Step 3: Traverse the entire array until search data is found.                 If search data  is present then                                return its location             else                                return -1Step 4: print data Step 5: Stop
Pseudocode :
PROCEDURE LINEAR_SEARCH (LIST, VALUE)
  FOR EACH ITEM IN THE LIST
      IF SEARCH ITEM == VALUE
             RETURN THE ITEM'S LOCATION
      ELSE
            RETURN -1
 END FOR
END PROCEDURE
C/C++
C++
#include <bits/stdc++.h>using namespace std; // Linearly search x in arr[]. If x is present then return// its location, otherwise return -1int search(int arr[], int n, int x){    int i;    for (i = 0; i < n; i++)        if (arr[i] == x)            return i;    return -1;} // Driver codeint main(){    int arr[] = { 3, 4, 1, 7, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    int x = 4;     int index = search(arr, n, x);    if (index == -1)        cout << "Element is not present in the array";    else        cout << "Element found at position " << index;     return 0;}
Output:
Element found at position 1
The time complexity of the above algorithm is O(n). 
BEST CASE COMPLEXITY The best-case time  complexity – O(1).when the search element is present at the first location of the array it will return the search data location and will terminate the loop and the best case occur. So the best-case time complexity of the linear search is o(1). AVERAGE CASE COMPLEXITY when the search element is present at the random location of the array then the array will traverse until search data is found.The average case time complexity – O(n).WORST-CASE COMPLEXITYwhen the search element is present at the last location of the array then the worst case occurs So the worst-case time complexity of the linear search is o(1).The worst-case time complexity – O(n)SPACE COMPLEXITY:
The space complexity of the linear search is o(n) cause it takes no extra space to store data. 
Please refer complete article on Linear Search for more details!
reshmapatil2772
C Programs
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
How to Append a Character to a String in C
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array
matplotlib.pyplot.jet() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The jet() function in pyplot module of matplotlib library is used to set the colormap to “jet”.
Syntax: matplotlib.pyplot.jet()
Parameters: This method does not accepts any parameter.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.jet() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np         ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad)        angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang        x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten()        triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                       < radm)        tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.jet()plt.title('matplotlib.pyplot.jet() function Example',                                    fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm           dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y)        extent = np.min(x), np.max(x), np.min(y), np.max(y)                Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest',                              extent = extent, alpha = 1)        def geeks(x, y):    return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))        Z2 = geeks(X, Y)        plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear',                 extent = extent)plt.jet()plt.title('matplotlib.pyplot.jet() function Example',                                   fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
C program to Check Whether a Number is Positive or Negative or Zero?

A number which is greater than 0 is positive and less than 0 are negative. The concept of positive and negative is very important in number theory and programming also. Calculations rely on this concept only.
Input: 0
Output:0 is zero
Using conditional statement check the number with 0 weather it is greater than 0 or smaller than 0.
#include <iostream>
using namespace std;
int main() {
   int n=0;
   if(n>0) {
      printf("%d is positive",n);
   } else if(n<0) {
      printf("%d is negative",n);
   } else {
      printf("%d is zero",n);
   }
   return 0;
}
Placing plot on Tkinter main window in Python

Oftentimes, we need to deal with plots in our Tkinter GUI-based application. To support the plots for the available data points, Python provides a Matplotlib package that can be imported into the application easily. In order to add a plot for the given data points, we have to install several other packages such as NumPy along with Matplotlib. NumPy is a Python library that helps to deal with scientific calculation in the Data.
In this example, we will create data points for the car prices starting from (100000) with the units in the range of 1000 to 5000.
#Import the required Libraries
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt

#Create an instance of Tkinter frame
win= Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")

def graph():
   car_prices=np.random.normal(100000, 5000, 1000)
   plt.hist(car_prices, 20)
   plt.show()

#Create a button to show the plot
Button(win, text= "Show Graph", command= graph).pack(pady=20)
win.mainloop()
If we will run the above code, it will display a window that contains a button "Show Graph".
When we click the button, it will display the graph on the screen.
C++ Vector Library - vector() Function

The C++ default constructor std::vector::vector() constructs an empty container, with zero elements. Size of this container is always zero.
The storage for container is allocated by internal allocator.
Following is the declaration for std::vector::vector() constructor form std::vector header.
explicit vector (const allocator_type& alloc = allocator_type());

explicit vector (const allocator_type& alloc = allocator_type());

alloc − allocator object
This allocator object is responsible for performing all memory allocation of this container.
Container keeps and uses the internal copy of this container. Member type allocator_type is a internal allocator which is second parameter of the class template.
Constructor never returns value
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::vector() constructor.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v1;

   cout << "size of v1 = " << v1.size() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
size of v1 = 0

 Print
 Add Notes
 Bookmark this page
How to create a  Python dictionary from text file?

Assuming a following text file (dict.txt) is present
1 aaa2 bbb3 ccc
Following Python code reads the file using open() function. Each line as string is split at space character. First component is used as key and second as value
d = {}
with open("dict.txt") as f:
for line in f:
    (key, val) = line.split()
    d[int(key)] = val

print (d)
The output shows contents of file in dictionary form
{1: 'aaa', 2: 'bbb', 3: 'ccc'}
Ways to sort list of dictionaries using values in python

In this article, you will learn how to sort the list of dictionaries using values in Python. We will use inbuilt method calls sorted to sort the dictionary.
We will follow the steps mentioned below to sort a dictionary using values.
Pass the list containing dictionaries and keys to the sorted method.We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method
We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method
1.Using lambda function
2.Using itemgetter method
Let's see the examples.
 Live Demo
## list of dictionaries
dicts = [
   {"name" : "John", "salary" : 10000},
   {"name" : "Emma", "salary" : 30000},
   {"name" : "Harry", "salary" : 15000},
   {"name" : "Aslan", "salary" : 10000}
]

## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = lambda item: item['salary']))
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]
The processing of sorting list of dictionaries using the itemgetter is similar to the above process. We pass the value to the key using itemgetter method, that's the only difference. Let's see.
 Live Demo
## importing itemgetter from the operator
from operator import itemgetter
## list of dictionaries
dicts = [
   {"name" : "John", "salary" : 10000},
   {"name" : "Emma", "salary" : 30000},
   {"name" : "Harry", "salary" : 15000},
   {"name" : "Aslan", "salary" : 10000}
]

## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = itemgetter('salary')))
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]
How to create a tuple with string and int items in C#?

Firstly, set two items in the tuple.
Tuple<int, string> tuple = new Tuple<int, string>(20, "Tom");
Now check for first item in the tuple, which is an integer.
if (tuple.Item1 == 20) {
   Console.WriteLine(tuple.Item1);
}
Now check for second item in the tuple, which is a string −
if (tuple.Item2 == "Tom") {
   Console.WriteLine(tuple.Item2);
}
The following is an example to create a tuple with string and int items.
 Live Demo
using System;
using System.Threading;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Tuple<int, string> tuple = new Tuple<int, string>(20, "Tom");
         if (tuple.Item1 == 20) {
            Console.WriteLine(tuple.Item1);
         }
         if (tuple.Item2 == "Tom") {
            Console.WriteLine(tuple.Item2);
         }
      }
   }
}
20
Tom
Can finally block be used without catch in Java?

Yes, it is not mandatory to use catch block with finally. You can have to try and finally.
Live Demo
public class Test {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
First element value: 6
Exception in thread "main" The finally statement is executed
java.lang.ArrayIndexOutOfBoundsException: 3
      at a5Exception_Handling.Test.main(Test.java:7)
PHP vs HTML - GeeksforGeeks

30 Aug, 2019
Example of PHP code:
<?php  echo "GeeksforGeeks";  ?> 
Example of HTML code:
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>    <p>Hello</p></body>  </html>
PHP vs HTML
Interesting Facts:
Famous websites like Facebook, Technorati, Yahoo, Wikipedia.org, WordPress.org, Twitter.com, Flickr, etc are powered by PHP.
PHP is deployed to more than 244 million websites. (Netcraft’s web survey 2013)
When PHP was developed, it stands for Personal Home Page.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.My Personal Notes
arrow_drop_upSave
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML
PHP
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
PHP 7 - Anonymous Classes

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.
<?php
   interface Logger {
      public function log(string $msg);
   }

   class Application {
      private $logger;

      public function getLogger(): Logger {
         return $this->logger;
      }

      public function setLogger(Logger $logger) {
         $this->logger = $logger;
      }  
   }

   $app = new Application;
   $app->setLogger(new class implements Logger {
      public function log(string $msg) {
         print($msg);
      }
   });

   $app->getLogger()->log("My first Log Message");
?>
It produces the following browser output −
My first Log Message


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Batch Script - Functions with Parameters

Functions can work with parameters by simply passing them when a call is made to the function.
Call :function_name parameter1, parameter2... parametern

The parameters can then be accessed from within the function by using the tilde (~) character along with the positional number of the parameter.
Following example shows how a function can be called with parameters.
@echo off
SETLOCAL
CALL :Display 5 , 10
EXIT /B %ERRORLEVEL%
:Display
echo The value of parameter 1 is %~1
echo The value of parameter 2 is %~2
EXIT /B 0
As seen in the above example, ~1 is used to access the first parameter sent to the function, similarly ~2 is used to access the second parameter.
The above command produces the following output.
The value of parameter 1 is 5
The value of parameter 2 is 10

 Print
 Add Notes
 Bookmark this page
How to find if a column is auto_increment in MySQL?

To find if a column is auto_increment in MySQL, you can use the following syntax −
select COLUMN_NAME from information_schema.columns where
TABLE_SCHEMA='yourDatabaseName' and TABLE_NAME='yourTableName' and EXTRA
like '%auto_increment%';
Let us first create a table. Here, ClientId is set AUTO_INCREMENT −
mysql> create table autoIncrementTableDemo
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20),
   -> ClientAge int,
   -> ClientAddress varchar(100),
   -> ClientCountryName varchar(100)
   -> );
Query OK, 0 rows affected (0.61 sec)
Now, let us find whether any of the column is auto_increment −
mysql> select COLUMN_NAME from information_schema.columns where
TABLE_SCHEMA='test' and TABLE_NAME='autoIncrementTableDemo' and EXTRA like
'%auto_increment%';
Following is the output that gives the column i.e. auto_increment −
+-------------+
| COLUMN_NAME |
+-------------+
| ClientId    |
+-------------+
1 row in set (0.00 sec)