code-rag-bench/online-tutorials huggingface dataset:
MySQL query to find all rows where string contains less than four characters?

Use CHAR_LENGTH() and find the count of characters in every string and then get the strings which are less than four characters. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (1.38 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (1.60 sec)

mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (1.83 sec)

mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.32 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Name  |
+-------+
| John  |
| Bob   |
| Carol |
| David |
| Sam   |
+-------+
5 rows in set (0.00 sec)
Following is the query to find all rows where string contains less than four characters −
mysql> select *from DemoTable where CHAR_LENGTH(Name) < 4;
This will produce the following output −
+------+
| Name |
+------+
| Bob  |
| Sam  |
+------+
2 rows in set (0.00 sec)
How to set a value in a particular JTable cell with Java?

Let’s say initially our table is the following with a specific cell [2,1] with value “Kane” −
The following is an example to set a new value to the above table. Here, we will update the cell [2,1] −
table.setValueAt("Guptill", 2, 1);
Let us see the complete example −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
      BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER,
      TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.orange);
      table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      table.setValueAt("Guptill", 2, 1);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
The output is as follows with the updated value “Guptill” in the cell [2,1]. We initialized that particular table cell with value “Kane”, but using the setValueAt() method, we have updated it successfully with “Guptill” as shown below −
How to save canvas data to file in HTML5?

A Canvas is just a rectangular area on the HTML page. We can draw graphics in this rectangular area (Canvas) with the help of JavaScript.
 Canvas can be created in HTML5 as −
<canvas id = ”canvas1” width = ”250” height = ”150”></canvas>                                 
This creates an empty canvas with name canvas1 with width=200 and height=100.
 To draw graphics in it, we use JavaScript −
var canvas = document.getElementById("Canvas1");
 var ctx1 = canvas.getContext("2d");
ctx1.moveTo(0,0); ctx1.lineTo(300,200);
 ctx1.stroke(); // This method actually draw graphics as per context object             
To save this graphic, we need to save it as some data url like img.png or img.jpg
For this, we will write −
var imgurl= canvas.toDataURL( ) ; / / This method saves graphics in png
document.getElementById(‘cimg’).src = imgurl; // This will set img src to dataurl(png)
so that it can be saved as image.
In this way, we can save canvas data to file in HTML5.
MathWorks Interview Experience for Internship (On-Campus)

06 Oct, 2020
MathWorks visited our college for summer internship 2021. Students from CSE/ECE/EE with CGPA>=7 were eligible to give the online test. 
Round 1: It consisted of 12 MCQ questions and 2 coding questions and a duration of 60 minutes. The test was conducted on HackerRank. The MCQ questions mainly focussed on time complexities, data structures, and OOPS concepts with an easy to medium level of difficulty. We were asked to choose 2  different languages (C/C++/Java) for the two coding questions. The questions were as follows:
Given an array S, generate two subsets A and B such that the intersection of A and B is an empty set and their union gives the original array S. In addition, the sum of elements of A has to be greater than the sum of elements of B and number of elements in A is minimum. Return the sorted array A. If multiple such A’s are possible, return the sorted set A that has a maximal sum.Input : n=5
    3 7 5 6 2
    
Output: 6 7
Explanation: One possibility is A=[5,7] and B=[3,6,2].     Another possibility is A=[6,7] and B=[2,3,5].         Since the sum of A is maximum in the second case, return the array [6,7].
Input : n=5
    3 7 5 6 2
    
Output: 6 7

Explanation: One possibility is A=[5,7] and B=[3,6,2].     Another possibility is A=[6,7] and B=[2,3,5].         Since the sum of A is maximum in the second case, return the array [6,7].
The minimum number of moves to make all array elements equal.
The shortlisted students were called for the interview rounds the next day. The interviews were held on MS Teams. There were two rounds(Managerial and HR rounds) and the order of rounds can be different for each candidate.
Round 2 (HR Round):
I was asked to start with my introduction and then I was asked the standard HR questions and a few questions on my projects.
This was for around 30 minutes.
Round 3 (Managerial Round):
There were many questions like how I can be a good team player, etc and for each question, the interviewer expected me to support it with real-life instances. I was not prepared in advance about any of these questions but I answered them very genuinely. (It is advisable to be prepared well in advance for such questions but even if you’re not, be confident and answer them genuinely).
I was asked in detail about the projects that I had and the challenges I faced.
This round went on for more than 30 minutes.
Tips : 
Be confident during the interviews.
Refer to GFG interview experiences which will be super helpful if you are sitting for any interviews.
Be calm and even if you are rejected, learn from your mistakes, and most importantly, never give up.
Marketing
MathWorks
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scipy.fftshift() in Python

29 Aug, 2020
With the help of scipy.fftshift() method, we can shift the lower and upper half of vector by using fast fourier transformation and return the shifted vector by using this method.
Syntax : scipy.fft.fftshift(x)
Return : Return the transformed vector.
Example #1 :
In this example we can see that by using scipy.fftshift() method, we are able to shift the lower half and upper half of the vector by using fast fourier transformation and return the shifted vector.
Python3
# import scipy and numpyimport scipyimport numpy as np  x = np.arange(6)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x)  print(gfg)
Output :
[3 4 5 0 1 2]
Example #2 :
Python3
# import scipy and numpyimport scipyimport numpy as np  x = np.arange(11)# Using scipy.fftfreq() methodgfg = scipy.fft.fftshift(x)  print(gfg)
Output :
[ 6  7  8  9 10  0  1  2  3  4  5]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
Python | Get Unique values from list of dictionary

26 Jul, 2019
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using set() + values() + dictionary comprehensionThe combination of these methods can together help us achieve the task of getting the unique values. The values function helps us get the values of dictionary, set helps us to get the unique of them, and dictionary comprehension to iterate through the list.
# Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + dictionary comprehension  # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}]  # printing original listprint("The original list : " +  str(test_list))  # Using set() + values() + dictionary comprehension# Get Unique values from list of dictionaryres = list(set(val for dic in test_list for val in dic.values()))      # printing result print("The unique values in list are : " + str(res))
The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3]
 
Method #2 : Using set() + values() + from_iterable()The combination of above functions can be used to perform this particular task. It is just as the above method, but the iteration part is done by the from_iterable function.
# Python3 code to demonstrate working of# Get Unique values from list of dictionary# Using set() + values() + from_iterable()from itertools import chain  # Initialize list test_list = [{'gfg' : 1, 'is' : 2}, {'best' : 1, 'for' : 3}, {'CS' : 2}]  # printing original listprint("The original list : " +  str(test_list))  # Using set() + values() + from_iterable()# Get Unique values from list of dictionaryres = list(set(chain.from_iterable(sub.values() for sub in test_list)))      # printing result print("The unique values in list are : " + str(res))
The original list : [{‘gfg’: 1, ‘is’: 2}, {‘best’: 1, ‘for’: 3}, {‘CS’: 2}]The unique values in list are : [1, 2, 3]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | Split string into list of characters
Matplotlib.pyplot.xcorr() in Python

22 Apr, 2021
Matplotlib is built on NumPy and sideby framework that’s why it is fast and efficient. It is open-source and has huge community support. It possesses the ability to work well with many operating systems and graphic backends. To get what matplotlib.pyplot.xcorr() do we need to understand Cross-Correlation. 
The correlation coefficient is a statistical measure of the strength of the relationship between the relative movements of two variables.For example: Let us take two real valued functions f and g. g is at x is the difference along x axis. Now to calculate x ne use Cross Correlation.  
 
matplotlib.pyplot.xcorr() function plots cross correlation between two array lists.Parameters :
 
Return :
 
Example 1:  
Python3
# import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx=[11.37, 14.23, 16.3, 12.36,   6.54, 4.23, 19.11, 12.13,   19.91, 11.00] y=[15.21, 12.23, 4.76, 9.89,   8.96, 19.26, 12.24, 11.54,   13.39, 18.96] # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using# xcorr() functionax1.xcorr(x, y, usevlines=True,          maxlags=5, normed=True,          lw=2)# adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show()
Output :  
Example 2:  
Python3
# import matplotlib libraryimport matplotlib.pyplot as pltimport numpy as np # float lists for cross# correlationx, y = np.random.randn(2, 100) # Plot graphfig = plt.figure()ax1 = fig.add_subplot(211) # cross correlation using xcorr()# functionax1.xcorr(x, y, usevlines=True,          maxlags=50, normed=True,          lw=2) # adding grid to the graphax1.grid(True)ax1.axhline(0, color='blue', lw=2) # show final plotted graphplt.show()
Output :  
 
simmytarika5
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Pandas DataFrames

A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional 
array, or a table with rows and columns.
Create a simple Pandas DataFrame:

     calories  duration
  0       420        50
  1       380        40
  2       390        45


As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return  
one or more specified row(s)
Return row 0:

  calories    420
  duration     50
  Name: 0, dtype: int64


Note: This example returns a Pandas Series.
Return row 0 and 1:

     calories  duration
  0       420        50
  1       380        40


Note: When using [], the 
  result is a Pandas DataFrame.
With the index argument, you can name your own indexes.
Add a list of names to give each row a name:

        calories  duration
  day1       420        50
  day2       380        40
  day3       390        45



Use the named index in the loc attribute to return the specified row(s).

Return "day2":

  calories    380
  duration     40
  Name: 0, dtype: int64


If your data sets are stored in a file, Pandas can load them into a DataFrame.
Load a comma separated file (CSV file) into a DataFrame:
You will learn more about importing files in the next chapters.
Insert the correct Pandas method to create a DataFrame.
pd.(data)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Creating a Stack in Javascript

Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own Stack class. Our class will have the following functions −
push(element): Function to push elements on top of the stack.
pop(): Function that removes an element from the top and returns it.
peek(): Returns the element on top of the stack.
isFull(): Checks if we reached the element limit on the stack.
 isEmpty(): checks if the stack is empty.
clear(): Remove all elements.
display(): display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of the stack and a helper function display() that'll help us when we implement the other functions for this class. We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly.
The isEmpty function checks if a size of the container is 0.
These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Stack class.
class Stack {

   constructor(maxSize) {

      // Set default max size if not provided

      if (isNaN(maxSize)) {

         maxSize = 10;

      }

      this.maxSize = maxSize; // Init an array that'll contain the stack values.

      this.container = [];

   }



   // A method just to see the contents while we develop this class

   display() {

      console.log(this.container);

   }



   // Checking if the array is empty

   isEmpty() {

      return this.container.length === 0;

   }

   

   // Check if array is full

   isFull() {

      return this.container.length >= maxSize;

   }



   push(element) {

      // Check if stack is full

      if (this.isFull()) {

         console.log("Stack Overflow!");

         return;

      }

      this.container.push(element);

   }

}
Add leading Zeros to Python string

We may sometimes need to append zeros as string to various data elements in python. There may the reason for formatting and nice representation or there may be the reason for some calculations where these values will act as input. Below are the methods which we will use for this purpose.
Here we take a DataFrame and apply the format function to the column wher we need to append the zeros as strings. The lambda method is used to apply the function repeatedly.
 Live Demo
import pandas as pd
string = {'Column' : ['HOPE','FOR','THE','BEST']}
dataframe=pd.DataFrame(string)
print("given column is ")
print(dataframe)
dataframe['Column']=dataframe['Column'].apply(lambda i: '{0:0>10}'.format(i))
print("\n leading zeros is")
print(dataframe)
Running the above code gives us the following result −
given column is
Column
0 HOPE
1 FOR
2 THE
3 BEST

leading zeros is
Column
0 000000HOPE
1 0000000FOR
2 0000000THE
3 000000BEST
The right justify function helps us in making the given values right justified by using the parameter we supply to the rjust function. In this example, we add three zeros to a value using rjust function. The number of zeros to be added can be made dynamic.
 Live Demo
val = '98.6 is normal body temperature'
print("The given string is :\n " + str(val))
#Number of zeros to be added
i = 3
result = val.rjust(i + len(val), '0')
print("adding leading zeros to the string is :\n" + str(result))
Running the above code gives us the following result −
The given string is :
98.6 is normal body temperature
adding leading zeros to the string is :
00098.6 is normal body temperature
MATLAB - Determinant of a Matrix

Determinant of a matrix is calculated using the det function of MATLAB. Determinant of a matrix A is given by det(A).
Create a script file with the following code −
a = [ 1 2 3; 2 3 4; 1 2 5]
det(a)
When you run the file, it displays the following result −
a =
      1     2     3
      2     3     4
      1     2     5
ans = -2


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
How to perform drag and drop operation in Selenium with python?

We can perform drag and drop actions in Selenium with the help of Action
Chains class. These classes are generally used for automating interactions like
context menu click, mouse button actions, key press and mouse movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
drag_and_drop() - This method performs the action of holding the left mouse
button on the source element. Then moves to the target element and finally
releases the mouse button.
drag_and_drop(args1, args2)
Where, args1 is the element on which mouse down operation is done.
And args2 is the element on which mouse up operation is done.
#source
source = driver.find_element_by_link_text("Tutorialspoint")
#target
target = driver.find_element_by_link_text("Selenium")
#action chain object
action = ActionChains(driver)
# drag and drop operation
action.drag_and_drop(source, target)
Code Implementation for drag and drop operation.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://jqueryui.com/droppable/")
#to refresh the browser
driver.refresh()
# identifying the source and target elements
source= driver.find_element_by_id("draggable");
target= driver.find_element_by_id("droppable");
# action chain object creation
action = ActionChains(driver)
# drag and drop operation and the perform
action.drag_and_drop(source, target).perform()
driver.close()
Concatenate a string given number of times in C++ programming

A program to concatenate a string a given number of times will run the string concatenate method n number of times based on the value of n.
The result would be string repeated a number of times.
given string: “ I love Tutorials point”
n = 5
I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point
I love Tutorials point
After seeing the output, it is clear that what the function will do.
#include <iostream>
#include <string>
using namespace std;
string repeat(string s, int n) {
   string s1 = s;
   for (int i=1; i<n;i++)
      s += s1; // Concatinating strings
   return s;
}
// Driver code
int main() {
   string s = "I love tutorials point";
   int n = 4;
   string s1 = s;
   for (int i=1; i<n;i++)
   s += s1;
   cout << s << endl;;
   return 0;
}
I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point
Java Program to create a TreeSet with custom Comparator

To create a TreeSet with custom comparator, let us first create a an Integer array and set it to TreeSet
Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
Above, we have used the Comparator with reverseOrder(), which returns a comparator that imposes the
reverse of the natural ordering.
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class Demo {
   public static void main(String args[]) throws Exception {
      Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
      Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
      for (int i = 0, n = arr.length; i < n; i++) {
         set.add(arr[i]);
      }
      System.out.println("TreeSet = "+set);
      System.out.println(((TreeSet<Integer>) set).comparator());
   }
}
TreeSet = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
java.util.Collections$ReverseComparator@6276ae34
Convert list of tuples into list in Python

We may come across a lists whose elements are tuples. But for further data processing we may need to convert the tuples to the normal elements of a list. In this article we will see the approaches to achieve this.
In this approach we design nested for loops to iterate through each tuple and produce the final list of elements.
 Live Demo
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = [item for t in listA for item in t]
# Result
print("Final list: \n",res)
Running the above code gives us the following result −
Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']
We can also use the itertools.chain method along with * operator which will fetch each element in the list of tuples and then combine them as a series of elements for the list.
 Live Demo
import itertools
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = list(itertools.chain(*listA))
# Result
print("Final list: \n",res)
Running the above code gives us the following result −
Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']
The reduce function in used to apply the concat function to each of the list elements which finally produces a list of all elements from the original list.
 Live Demo
import operator
from functools import reduce
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = (list(reduce(operator.concat, listA)))
# Result
print("Final list: \n",res)
Running the above code gives us the following result −
Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']
How to add Icon to JButton in Java?

To add icon to a button, use the Icon class, which will allow you to add an image to the button.
We are creating a button wherein we are adding an icon with Icon class −
Icon icon = new ImageIcon("E:\\editicon.PNG");
JButton button7 = new JButton(icon);
Above, we have set icon for button 7.
The following is an example to add icon to JButton−
package my;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JButton button1 = new JButton("One");
      JButton button2 = new JButton("Two");
      JButton button3 = new JButton("Three");
      JButton button4 = new JButton("Four");
      JButton button5 = new JButton("Five");
      JButton button6 = new JButton("Six");
      Icon icon = new ImageIcon("E:\\editicon.PNG");
      JButton button7 = new JButton(icon);
      Box box = Box.createVerticalBox();
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(button5);
      box.add(button6);
      box.add(button7);
      JFrame frame = new JFrame();
      frame.add(box);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationByPlatform(true);
      frame.setSize(500, 300);
      frame.setVisible(true);
   }
}
HTML - <title> Tag

The HTML <title> tag is used for indicating the title of the HTML document. The body title is placed between the <head> and the </head> tags.
HTML document title is visible via browser’s title bar.
<!DOCTYPE html>
<html>

   <head>
      <title>Title comes here</title>
   </head>

   <body>
      <p>title tag is used for indicating the title of the HTML document. HTML document
         title is visible via browser’s title bar.</p>
   </body>

</html>
This will produce the following result −
title tag is used for indicating the title of the HTML document. HTML document title is visible via browser’s title bar.
This tag supports all the global attributes described in − HTML Attribute Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
B+ tree Insertion in Data Structure

Here we will see, how to perform the insertion into a B+ Tree. Suppose we have a B+ Tree like below −
Example of B+ Tree −
To insert an element, the idea is very similar to the B-Tree, if one element is inserted, that will be stored at the leaf node. If that is present in some internal node, then it will also be there, at the leaf as right child of itself.
Suppose we want to insert 65 into the tree. So that is greater than 60, and less than 75. Then it will be inserted into the middle sub-tree. Now, 65, will be inserted into node after 63, then that node will be divided into two parts, 65 will go up, and 65 will also be there at the right node of it.
B+ Tree after inserting 65.
BPlusTreeInsert(root, key) −
Input − The root of the tree, and key to insert
We will assume, that the key is not present into the list
Start from root node, perform exact match for key as ‘key’ till a leaf node. Let the search path
be x1, x2, ... , xh. The x1 is first node so root, then xh is leaf node. Each node xi is parent of xi+1
Insert the new object where key is ‘key’, and value is v into xh.
i := h
while xi overflows, do
   divide xi into two nodes, by moving the larger half of the keys into a new node p.
   if xi is leaf node, link p into the linked list among leaf nodes.
   identify a key k, to be inserted into the parent level along with child pointer pointing p.
   The choice of k depends on the type of the node xi. If xi is leaf node, we will perform
   copy up. So smallest key in p, is copied as k to the parent level. On the other hand, if xi is
   non-leaf node, then we will perform push up. So smallest key in p, will be copied into k,
   in the parent node.
   if i = 0, then
      create a new index node as the new root. In the new root store node with key k,
      and two child xi and p.
      return
   else
      insert a key k and a child pointer pointing to p, into node xi-1.
      i := i – 1
   end if
done
What is the difference between abstract class and a concrete class in Java?

Following are the notable differences between an abstract class and concrete class.
Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
You cannot instantiate an abstract class.
An abstract class may contain abstract methods.
You need to inherit an abstract class to use it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
public abstract class AbstractExample {
   public abstract int add(int a, int b);
   public abstract int subtract();
   
   public void display(){
      System.out.println("Hello how are you");
   }
}
You can instantiate a concrete class.
A concrete class doesn’t have any abstract methods.
It is not mandatory to inherit a concrete class to use it.
 Live Demo
public class ConcreteClassExample {
   public int add(int a, int b){
      int c = a + b;
      return c;
   }
   public int subtract(int a, int b){
      int c = a - b;
      return c;
   }
   public void display(){
      System.out.println("Hi welcome to Tutorialspoint");
   }
   public static void main(String args[]){
      ConcreteClassExample obj = new ConcreteClassExample();
      System.out.println(obj.add(25, 347));
      System.out.println(obj.subtract(500, 456));
      
      obj.display();
   }
}
372
44
Hi welcome to Tutorialspoint
Java Guava | Lists.partition() method with Examples - GeeksforGeeks

04 Feb, 2019
The Lists.partition() method in Guava Library is used to divide the original list into sublists of the same size. The method accepts two parameters.
For example: If the original list passed as parameter is [a, b, c, d, e] and the partition size is 3, then the sublists yield are as [[a, b, c], [d, e]].
Syntax:
public static <T> List<List<T>> partition(List<T> list, int size)
Parameters: The method accepts two parameters:
list: The list which is to be divided into sublists based on the partition size.
size: The desired size of each sublist. The size of the last sublist may be smaller.
Return Value: The method returns the list of consecutive sublists. Each sublist(except possibly the last one) has the size equal to the partition size.
Exception: The method Lists.partition() throws IllegalArgumentException if partition size is non-positive.
Below examples illustrate the implementation of above method:
Example 1:
// Java code to show implementation of// Guava's Lists.partition() method  import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List;  class GFG {      // Driver's code    public static void main(String[] args)    {        // Creating a List of Integers        List<Integer> myList            = Arrays.asList(1, 2, 3, 4, 5);          // Using Lists.partition() method to divide        // the original list into sublists of the same        // size, which are just views of the original list.        // The final list may be smaller.        List<List<Integer> > lists            = Lists.partition(myList, 2);          // Displaying the sublists        for (List<Integer> sublist: lists)            System.out.println(sublist);    }}
[1, 2]
[3, 4]
[5]

Example 2:
// Java code to show implementation of// Guava's Lists.partition() method  import com.google.common.collect.Lists;import java.util.Arrays;import java.util.List;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating a List of Characters        List<Character> myList            = Arrays.asList('H', 'E', 'L', 'L', 'O',                            'G', 'E', 'E', 'K', 'S');          // Using Lists.partition() method to divide        // the original list into sublists of the same        // size, which are just views of the original list.        // The final list may be smaller.        List<List<Character> > lists            = Lists.partition(myList, 3);          // Displaying the sublists        for (List<Character> sublist: lists)            System.out.println(sublist);    }}
[H, E, L]
[L, O, G]
[E, E, K]
[S]

Reference: https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-
Guava-Functions
Guava-Lists
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
Queue Interface In Java
How to Send and Receive JSON Data to and from the Server

JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server.
You can use fetch to GET JSON data in the following way −
const URL = 'https://jsonplaceholder.typicode.com/todos/1'
// Send a GET request without any data to the server
fetch(URL, {method: "GET"})
// Get the JSON data from the raw response
   .then(res => res.json())
// Print the result
   .then(console.log)
This will give the output −
{
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
}
You can also POST data to the server using fetch. For example, to create
a new todo on the above server, you can post your own data −
const URL = 'https://jsonplaceholder.typicode.com/todos'
const data = {
   "userId": 1,
   "title": "delectus aut autem",
   "completed": false
};
// Send a post request
fetch(URL, {
   method: "POST",
   body: JSON.stringify(data),
   headers: {
      "Content-type": "application/json; charset=UTF-8"
   }
})
This will create a todo on the placeholder API.
Python | Numpy numpy.transpose() - GeeksforGeeks

07 Mar, 2022
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. 
Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but it’s not all required. But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.Returns: ndarray  
Example #1 : In this example we can see that it’s really easy to transpose an array with just one line. 
Python3
# importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2, 3],                [4, 5, 6],                [7, 8, 9]]) # before transposeprint(gfg, end ='\n\n') # after transposeprint(gfg.transpose())
[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 4 7]
 [2 5 8]
 [3 6 9]]
 
Example #2 : In this example we demonstrate the use of tuples in numpy.transpose(). 
Python3
# importing python module named numpyimport numpy as np # making a 3x3 arraygfg = np.array([[1, 2],                [4, 5],                [7, 8]]) # before transposeprint(gfg, end ='\n\n') # after transposeprint(gfg.transpose(1, 0))
[[1 2]
 [4 5]
 [7 8]]

[[1 4 7]
 [2 5 8]]
 
Method 2: Using  Numpy ndarray.T object.
Python3
# importing python module named numpyimport numpy as np   # making a 3x3 arraygfg = np.array([[1, 2, 3],                [4, 5, 6],                [7, 8, 9]])   # before transposeprint(gfg, end ='\n\n')   # after transposeprint(gfg.T)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 4 7]
 [2 5 8]
 [3 6 9]]
pulamolusaimohan
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
How to fetch data from MongoDB using Python? - GeeksforGeeks

31 Aug, 2021
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
Pymongo provides various methods for fetching the data from mongodb. Let’s see them one by one.
1) Find One: This method is used to fetch data from collection in mongoDB. It returns first first occurrence. Syntax :
find_one()
Example:
Sample Database:
Python3
import pymongo  client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] x = col.find_one() print(x)
Output :
2) Find All: For all occurrences in the selection use find() method. It works like Select * query  of SQL. Syntax : 
find()
Example :
Python3
import pymongo  client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] x = col.find() for data in x:    print(data)
Output: 
3) Fetching only specific fields: If you want to fetch only some fields then in the find method pass the first parameter as {} and second parameter as 1 for those field that you want to fetch and 0 for those you don’t want to fetch. Syntax: 
find({},{field_data:bool})
Example: 
Python3
import pymongo  client = pymongo.MongoClient("mongodb://localhost:27017/") # Database Namedb = client["database"] # Collection Namecol = db["GeeksForGeeks"] # Fields with values as 1 will# only appear in the resultx = col.find({},{'_id': 0, 'appliance': 1,                 'rating': 1, 'company': 1}) for data in x:    print(data)
Output: 
kalrap615
Python-mongoDB
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
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Check whether right angled triangle is valid or not for large sides in Python

Suppose we have three sides in a list. We have to check whether these three sides are forming a right angled triangle or not.
So, if the input is like sides = [8, 10, 6], then the output will be True as (8^2 + 6^2) = 10^2.
To solve this, we will follow these steps −
sort the list sides
if (sides[0]^2 + sides[1]^2) is same as sides[2]^2, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
Live Demo
def solve(sides):
   sides.sort()
   if (sides[0]*sides[0]) + (sides[1]*sides[1]) == (sides[2]*sides[2]):
      return True
   return False
   
sides = [8, 10, 6]
print(solve(sides))
[8, 10, 6]

True
Java Methods

A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use 
it many times.
A method must be declared within a class. It is defined 
with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:
Create a method inside Main:
public class Main {
  static void myMethod() {
    // code to be executed
  }
}
 

myMethod() is the name of the method
static means that the method belongs to the 
Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
void means that this method does not have a 
return value. You will learn more about return values later in this chapter
To call a method in Java, write the method's name followed by two 
parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Inside main, call the 
myMethod() method:
public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// Outputs "I just got executed!"
 


Try it Yourself »

A method can also be called multiple times:
public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

// I just got executed!
// I just got executed!
// I just got executed!
 
 
 


Try it Yourself »

In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method.
Insert the missing part to call myMethod from main.
static void myMethod() {
  System.out.println("I just got executed!");
}

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

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Downloading with chrome headless and selenium.

We can download Chrome in headless mode in Selenium. The headless execution is one of the ways saving resources by not utilizing the complete graphical interface.
After the version 59, Chrome can be used in headless mode. The ChromeOptions class is used to modify the default character of the browser. The parameter headless is passed as a parameter to the addArgument method for headless execution.
ChromeOptions o = new ChromeOptions();
o.addArguments("headless");
WebDriver driver = new ChromeDriver(o);
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class HeadlessChrome{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      //ChromeOptions object creation
      ChromeOptions o = new ChromeOptions();
      //headless argument added
      o.addArguments("headless");
      // add options parameter to Chrome driver
      WebDriver driver = new ChromeDriver(o);
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/questions/index.php");
      // get page title
      System.out.println("Page title: " + driver.getTitle());
   }
}
GATE | GATE CS 2008 | Question 39 - GeeksforGeeks

28 Jun, 2021
Consider the following functions:
f(n) = 2n
g(n) = n!
h(n) = nlogn
Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true?
(A) f(n) = O(g(n)); g(n) = O(h(n))
(B) f(n) = (g(n)); g(n) = O(h(n))
(C) g(n) = O(f(n)); h(n) = O(f(n))
(D) h(n) = O(f(n)); g(n) = (f(n)) 
(A) A(B) B(C) C(D) DAnswer: (D)Explanation: According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) )We can easily see above order by taking logs of the given 3 functions
   lognlogn < n < log(n!)  (logs of the given f(n), g(n) and h(n)).
Note that log(n!) = (nlogn)Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
How to print the first character of each word in a String in Java?

A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created.
We can print the first character of each word in a string by using the below program
public class FirstCharacterPrintTest {
   public static void main(String[] args) {
      String str = "Welcome To Tutorials Point";
      char c[] = str.toCharArray();
      System.out.println("The first character of each word: ");
      for (int i=0; i < c.length; i++) {
         // Logic to implement first character of each word in a string
         if(c[i] != ' ' && (i == 0 || c[i-1] == ' ')) {
            System.out.println(c[i]);
         }
      }
   }
}
The first character of each word:
W
T
T
P
How to make a jQuery function call after “X” seconds?

To make a jQuery function call after “X” seconds, use the siteTimeout() method.
On button click, set the following and fade out the element. Here, we have also set the milliseconds. This is the delay that would occur before fading an element:
$("#button1").bind("click",function() {
   setTimeout(function() {
      $('#list').fadeOut();}, 4000);
});
You can try to run the following code to learn how to work with setTimeout() method in jQuery:
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("#button1").bind("click",function() {
            setTimeout(function() {
               $('#list').fadeOut();}, 4000);
            });
         });
   </script>
</head>
<body>

<input type="button" id="button1" value="Fade Out" />
<br/>
<br/>
<div id="list">
   <ul>
      <li>India</li>
      <li>US</li>
      <li>UK</li>
   </ul>
</div>
<p>The above data will fade out after 4 seconds</p>
</body>
</html>