code-rag-bench/online-tutorials huggingface dataset:
What is JSON wire protocol in selenium?

To understand we need to first have a fair idea of what JSON actually is, JSON stands for Java Script Object Notation. Now let's have a look at what a sample JSON input looks like −
{
   "name": "Tutorials Point",
   "topic": "Selenium",
   "Address": "India"
}
JSON today is one of the most widely used and accepted method for communication of heterogeneous system. JSON is used a lot in web services in REST and has been a strong competition to XML.
Let’s understand how Web driver uses it when testing the web applications −
WebDriver uses JSON as a medium to communicate between client libraries (Java, C#, Python and so on) and drivers (Firefox Driver, IE Driver, Chrome Driver). The request is to in the form an HTTP request which accepts input in the form of JSON. The operations are performed and the response of execution is shared back to the client in the form of JSON. Similarly, the RemoteWebDriver client and the RemoteWebDriver server use the JSON wire protocol to communicate among themselves.
To sum up, lets see how it works in a step by step manner −
In a server-client architecture it is necessary that the client and server should be in sync and are able to receive and send the request and response.
In a server-client architecture it is necessary that the client and server should be in sync and are able to receive and send the request and response.
As the name suggests JSON(JavaScript Object Notation) is used to represent objects with complex data structures. JSON wire protocol acts as a mediator between client libraries and WebDrivers. It sends transfers data between the client and the server on the web.
As the name suggests JSON(JavaScript Object Notation) is used to represent objects with complex data structures. JSON wire protocol acts as a mediator between client libraries and WebDrivers. It sends transfers data between the client and the server on the web.
The server doesn’t understand the programming language in which the program is created, it just understands the protocol, and here comes the role of JSON wire Protocol.
The server doesn’t understand the programming language in which the program is created, it just understands the protocol, and here comes the role of JSON wire Protocol.
It uses the process of serialization(convert Object’s data to JSON Format) and de-serialization(convert JSON format to object) just like REST web services.
It uses the process of serialization(convert Object’s data to JSON Format) and de-serialization(convert JSON format to object) just like REST web services.
Note − JSON Wire Protocol is obsolete now and no longer used.
Find GCD of two numbers

In mathematics, Greatest Common Divisor (GCD) is the largest possible integer, that divides both of the integers. The condition is that the numbers must be non-zero.
We will follow the Euclidean Algorithm to find the GCD of two numbers.
Input:
Two numbers 51 and 34
Output:
The GCD is: 17
findGCD(a, b)
Input: Two numbers a and b.
Output: GCD of a and b.
Begin
   if a = 0 OR b = 0, then
      return 0
   if a = b, then
      return b
   if a > b, then
      return findGCD(a-b, b)
   else
      return findGCD(a, b-a)
End
#include<iostream>
using namespace std;

int findGCD(int a, int b) {    //assume a is greater than b
   if(a == 0 || b == 0)
      return 0;    //as a and b are 0, the greatest divisior is also 0
   if(a==b)
      return b;    //when both numbers are same
   if(a>b)
      return findGCD(a-b, b);
   else
      return findGCD(a, b-a);
}

int main() {
   int a, b;
   cout << "Enter Two numbers to find GCD: "; cin >> a >> b;
   cout << "The GCD is: " << findGCD(a,b);
}
Enter Two numbers to find GCD: 51 34
The GCD is: 17
How to link pages using relative URL in HTML?

To link pages using relative URL in HTML, use the <a> tag with href attribute. Relative URL is used to add a link to a page on the website. For example, /contact, /about_team, etc.
Everything inside <a>...</a> tag becomes a hyperlink. Some of the attributes of <a> tag are listed below,
You can try to run the following code to link pages using relative URL in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Relative URLs</title>
   </head>
   <body>
     <p>
        Our <a href="/about/about_team.htm">Team</a> comprises of programmers,
           writers, and analysts.
     </p>
   </body>
</html>
Check if a PHP cookie exists and if not set its value

Based on the PHP manual, the existence of a cookie can’t be found.
A reference from the manual: “Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.”
The reason being cookies are response headers to the browser and the browser needs to then send them back along with the next request. This is the reason they are available on the second page load only.
But here is a work around for the same: The $_COOKIE can be set when the setcookie function is called −
if(!isset($_COOKIE['lg'])) {
   setcookie('lg', 'ro');
   $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Why do we use DOCTYPES in HTML document?

The HTML <doctype> tag is used for specifying which version of HTML the document is using. This is referred to as the document type declaration (DTD).
The <!DOCTYPE> declaration is the first thing you can see in the HTML document. It gets added before the <html> tag. The <!DOCTYPE> tag does not have an end tag!.
HTML 4.01 had 3 possible doctypes − HTML 4 Strict, HTML 4 Transitional, and HTML 4 Frameset. Every HTML document you create should have one of these three DTDs.
This document type includes all HTML elements except those that have been deprecated and those that appear in frameset documents.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
This document type includes all HTML elements including those that have been deprecated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">;
This document type includes all HTML elements in the transitional DTD as well as those in a framed document.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
In HTML5 there is only one declaration i.e.
<!DOCTYPE html>
LinkedList in C#

System.Collections.Generic namespace is available in C# for LinkedList. The LinkedList<T> class allows insertion and deletion of elements from the list at a fast pace.
C# LinkedList<T> class uses the concept of linked list. It allows us to insert and delete elements fastly. It can have duplicate elements. It is found in System.Collections.Generic namespace.
Here is an example −
 Live Demo
using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      LinkedList < string > l = new LinkedList < string > ();

      l.AddLast("one");
      l.AddLast("two");
      l.AddLast("three");

      foreach(var ele in l) {
         Console.WriteLine(ele);
      }
   }
}
one
two
three
Difference between Boxing and Unboxing in C#

Boxing convert value type to an object type whereas unboxing converts object type to the value type.
Let us see the difference between Boxing and Unboxing in C#.
In boxing, the value stored on the stack is copied to the object stored on heap memory, whereas unboxing is the opposite.
In Unboxing, the object's value stored on the heap memory is copied to the value type stored on stack.
Unboxing has explicit conversion whereas boxing has implicit conversion.
int a = 10;
object obj = a;  // boxing
int b = (int) ob; // unboxing
Elementwise Matrix Multiplication in R

26 Mar, 2021
In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. In this article, we are going to perform element-wise matrix multiplication in R programming.
Approach
Create a matrix
Multiply two matrices
Verify the result.
Element-wise multiplication using “*” operator:
Syntax: matrix1*matrix*2.....matrix n
Example 1:
This code shows the element-wise multiplication of two matrices data1 and data2, Data comprises 5 rows and 2 columns:
R
# Creating matrices 10 elements each using# range operator ":"data1 <- matrix(1:10, nrow = 5) print(data1)  data2 <- matrix(11:20, nrow = 5) print(data2)  # perform element wise multiplicationprint(data1*data2)
Output:
Example 2:
This code for multiplication of multiple matrices data1,data2,data3. All data comprises 5 rows created using the range operator.
R
# Creating matrices 10 elements each # using range operator ":"data1 <- matrix(1:10, nrow = 5) print(data1)  data2 <- matrix(11:20, nrow = 5) print(data2)  data3 <- matrix(21:30, nrow = 5)  # perform element wise multiplicationprint(data1*data2*data3)
Output:
Example 3:
This code shows the matrix is created using vectors. And matrix multiplication is done.
R
# vector aa = c(3, 4, 5, 6, 7, 8)  # vector bb=c(1, 3, 0, 7, 8, 5)  # Creating matrices using vectordata1 <- matrix(a, nrow = 3) print(data1)  data2 <- matrix(b, nrow = 3) print(data2)  print(data1*data2)
Output:
Example 4:
An example that shows multiplication column arrangement and matrices data1 and data2 and multiplied. Column wise we are going to perform matrix multiplication data1 and data2 comprises 3 columns and elements are created using vector.
R
# vector aa = c(3, 4, 5, 6, 7, 8)  # vector bb = c(1, 3, 0, 7, 8, 5)  # Creating matrices using vectordata1 <- matrix(a, ncol = 3) print(data1)  data2 <- matrix(b, ncol = 3) print(data2)  print(data1*data2)
Output:
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Lambda with if but without else in Python

06 Oct, 2021
In Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value.
Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.
Let’s understand this with a simple example of lambda function to square a number only if it is greater than 0 using if but without else.
Example #1:
Python3
# Lambda function with if but without else.square = lambda x : x*x if(x > 0) print(square(6))
Output:
File "/home/2c8c59351e1635b6b026fb3c7fc17c8f.py", line 2
    square = lambda x : x*x if(x > 0)
                                    ^
SyntaxError: invalid syntax
The above code on execution shows SyntaxError, as we know that a lambda function must return a value and this function returns x*x if x > 0 and it does not specify what will be returned if the value of x is less than or equal to 0.
To correct it, we need to specify what will be returned if the if-condition will be false i.e. we must have to specify its else part.
Let’s see the above code with its else part.
Code:
Python3
# Lambda function with if-elsesquare = lambda x : x*x if(x > 0) else None print(square(4))
Output:
16
Example #2: The first code is with if but without else then second is with if-else.
Python3
# Example of lambda function using if without elsemod = lambda x : x if(x >= 0) print(mod(-1))
Output:
File "/home/20b09bdd29e24dfe24c185cd99dfcdfa.py", line 2
    mod = lambda x : x if(x >= 0)
                                ^
SyntaxError: invalid syntax
Now, let’s see it using if-else.
Python3
# Example of lambda function using if-elsemod = lambda x : x if(x >= 0) else -x print(mod(-1))
Output:
1
Example #3: The first code is with if but without else then second is with if-else.
Python3
# Example of lambda function using if without elsemax = lambda a, b : x if(a > b) print(max(1, 2))
Output:
File "/home/8cf3856fc13d0ce75edfdd76793bdde4.py", line 2
    max = lambda a, b : x if(a > b)
                                  ^
SyntaxError: invalid syntax
Now, let’s see it using if-else.
Python3
# Example of lambda function using if-elsemax = lambda a, b : a if(a > b) else b print(max(1, 2))print(max(10, 2))
Output:
2
10
piyushtiwari515
surinderdawra388
marciojr
Picked
python-lambda
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
SQL - INSERT Query

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)  
VALUES (value1, value2, value3,...valueN);

Here, column1, column2, column3,...columnN are the names of the columns in the table into which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in the CUSTOMERS table by using the second syntax as shown below.
INSERT INTO CUSTOMERS 
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

All the above statements would produce the following records in the CUSTOMERS table as shown below.
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
You can populate the data into a table through the select statement over another table; provided the other table has a set of fields, which are required to populate the first table.
Here is the syntax −
INSERT INTO first_table_name [(column1, column2, ... columnN)] 
   SELECT column1, column2, ...columnN
Convert String to UTF-8 bytes in Java

Before converting a String to UTF-8-bytes, let us have a look at UTF-8.
UTF-8 is a variable width character encoding. UTF-8 has ability to be as condense as ASCII but can also contain any unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4.
In order to convert a String into UTF-8, we use the getBytes() method in Java. The getBytes() method encodes a String into a sequence of bytes and returns a byte array.
Declaration − The getBytes() method is declared as follows −
public byte[] getBytes(String charsetName)
where charsetName is the specific charset by which the String is encoded into an array of bytes.
Let us see a program to convert a String into UTF-8 bytes in Java.
 Live Demo
public class Example {
   public static void main(String args[]) throws Exception {
      String s = "Hello World";
      byte arr[] = s.getBytes("UTF8");
      for (byte x: arr) {
         System.out.print(x+" ");
      }
   }
}
72 101 108 108 111 32 87 111 114 108 100
Let us understand the above program. We have created a String s −
String s = "Hello World";
String s is assigned the value Hello World.
To convert it into UTF-8, we use the getBytes(“UTF-8”) method. This gives us an array of bytes as follows −
byte[] arr = s.getBytes("UTF-8");
Then to print the byte array, we use an enhanced for loop as follows −
for (byte x: arr) {
   System.out.print(x+" ");
}
Virtual Circuit in Computer Network

14 May, 2020
Virtual Circuit is the computer network providing connection-oriented service. It is a connection-oriented network. In virtual circuit resource are reserve for the time interval of data transmission between two nodes. This network is a highly reliable medium of transfer. Virtual circuits are costly to implement.
Working of Virtual Circuit:
In the first step a medium is set up between the two end nodes.
Resources are reserved for the transmission of packets.
Then a signal is sent to sender to tell the medium is set up and transmission can be started.
It ensures the transmission of all packets.
A global header is used in the first packet of the connection.
Whenever data is to be transmitted a new connection is set up.
Congestion Control in Virtual Circuit:Once the congestion is detected in virtual circuit network, closed-loop techniques is used. There are different approaches in this technique:
No new connection –No new connections are established when the congestion is detected. This approach is used in telephone networks where no new calls are established when the exchange is overloaded.
Participation of congested router invalid –Another approach to control congestion is allow all new connections but route these new connections in such a way that congested router is not part of this route.
Negotiation –To negotiate different parameters between sender and receiver of the network, when the connection is established. During the set up time, host specifies the shape and volume of the traffic, quality of service and other parameters.
Advantages of Virtual Circuit:
Packets are delivered to the receiver in the same order sent by the sender.Virtual circuit is a reliable network circuit.There is no need for overhead in each packet.Single global packet overhead is used in virtual circuit.
Packets are delivered to the receiver in the same order sent by the sender.
Virtual circuit is a reliable network circuit.
There is no need for overhead in each packet.
Single global packet overhead is used in virtual circuit.
Disadvantages of Virtual Circuit:
Virtual circuit is costly to implement.It provides only connection-oriented service.Always a new connection set up is required for transmission.
Virtual circuit is costly to implement.
It provides only connection-oriented service.
Always a new connection set up is required for transmission.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Introduction of Mobile Ad hoc Network (MANET)
Difference between MANET and VANET
Difference between FDMA, TDMA and CDMA
Cryptography and its Types
Dynamic Host Configuration Protocol (DHCP)
Ruby Integer to_f function with example

07 Jan, 2020
The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity.
Syntax: number.to_f
Parameter: The function takes the integer which is to be converted to float.
Return Value: The function returns the float value of the number.
Example #1:
# Ruby program for to_f function    # Initializing the numbernum1 = 5num2 = 10num3 = 1678 num4 = 1897.90   # Prints the int as floatputs num1.to_fputs num2.to_fputs num3.to_fputs num4.to_f
Output:
5.0
10.0
1678.0
1897.9

Example #2:
# Ruby program for to_f function    # Initializing the numbernum1 = 51num2 = 10.78num3 = 1690num4 = 183    # Prints the int as floatputs num1.to_fputs num2.to_fputs num3.to_fputs num4.to_f
Output:
51.0
10.78
1690.0
183.0

Ruby Integer-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | Array class find_index() operation
Convert Vector to ArrayList in Java - GeeksforGeeks

11 Dec, 2020
There are multiple ways to convert vector to ArrayList, using passing the Vector in ArrayList constructor and by using simple vector traversal and adding values to ArrayList.
Approach 1:
Create a Vector.Add some values in Vector.Create new ArrayList.Traverse vector from the left side to the right side.Start adding each element in ArrayList.
Create a Vector.
Add some values in Vector.
Create new ArrayList.
Traverse vector from the left side to the right side.
Start adding each element in ArrayList.
Below is the implementation of the above approach:
Java
// Convert Vector to ArrayList in Javaimport java.util.Vector;import java.util.ArrayList;  public class GFG {      public static void main(String[] args)    {          // Create a Vector that contain strings          Vector<String> v = new Vector<String>();          // add values in vector          v.add("a");        v.add("b");        v.add("c");        v.add("d");        v.add("e");          // Display the Vector          System.out.println(" Vector :  " + v);          ArrayList<String> Arrlist = new ArrayList<String>();          // Convert Vector to ArrayList        for (int i = 0; i < v.size(); i++)            Arrlist.add(v.get(i));        // Display ArrayList        System.out.println("\n ArrayList : " + Arrlist);    }}
Time Complexity: O(n)
Approach 2:
Create a Vector.
Add some values in Vector.
Create an ArrayList and pass the Vector in ArrayList Constructor.
Syntax:
ArrayList<String> ArrList = new ArrayList<String>(vector);
Below is the implementation of the above approach:
Java
// Convert Vector to ArrayList in Javaimport java.util.Vector;import java.util.ArrayList;  public class GFG {      public static void main(String[] args)    {          // Create a Vector that contain strings          Vector<String> v = new Vector<String>();          // add values in vector          v.add("a");        v.add("b");        v.add("c");        v.add("d");        v.add("e");          // Display the Vector          System.out.println(" Vector :  " + v);          // Convert Vector to ArrayList        ArrayList<String> Arrlist            = new ArrayList<String>(v);          // Display ArrayList        System.out.println("\n ArrayList : " + Arrlist);    }}
 Vector :  [a, b, c, d, e]

 ArrayList : [a, b, c, d, e]
Time Complexity: O(n)
Java-ArrayList
Java-Collections
Java-Vector
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
How to split a Java String into tokens with StringTokenizer?

The hasMoreTokens() method is used to test if there are more tokens available from this tokenizer's string.
Live Demo
import java.util.*;
public class StringTokenizerDemo {
   public static void main(String[] args) {
      // creating string tokenizer
      StringTokenizer st = new StringTokenizer("Come to learn");
      // checking elements
      while (st.hasMoreElements()) {
         System.out.println("Next element : " + st.nextElement());
      }
   }
}
Next element : Come
Next element : to
Next element : learn
Matplotlib.pyplot.broken_barh() in Python - GeeksforGeeks

21 Apr, 2020
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB.
The function broken_barh() is used to Plot a horizontal sequence of rectangles.A rectangle is drawn for each component of xranges which consists of a sequence of tuples. All rectangles have the same vertical position and estimate characterized by yrange.
Syntax: matplotlib.pyplot.broken_barh(xranges, yrange, *, data=None, **kwargs)
Parameters:
xranges : sequence of tuples (xmin, xwidth)Each tuples gives the position(xmin) of the rectangle and it’s horizontal extension(xwidth) from that position.
yranges : (ymin, ymax)In the above attribute, ymin gives the position of the rectangle and ymax gives the vertical extension from ymin.
Returns:
BrokenBarHCollection: A collection of horizontal bars spanning yrange with a sequence of xranges.
Examples to illustrate the matplotlib.pyplot.broken_barh() function are as follows:Example 1:
# importing moduleimport matplotlib.pyplot as plt    # Adding title to the plotplt.title('GEEKSFORGEEKS - EXAMPLE')  # adding x axis label to the plotplt.xlabel('x-label')  # label for y axis  for the plotplt.ylabel('y-label')  x_1 = [(1, 4), (10, 7)]y_1 = (2, 2)  # Plotting the chartplt.broken_barh(x_1, y_1, facecolors ='green')  x_2 = [(10, 1), (15, 4), (25, 6)]y_2 = (6, 2)  # Plotting the chartplt.broken_barh(x_2, y_2, facecolors ='cyan')  plt.show()
Output :
Example 2:
# importing moduleimport matplotlib.pyplot as plt    # Adding title to the plotplt.title('GEEKSFORGEEKS - EXAMPLE')  # adding x axis label to the plotplt.xlabel('Number of Cars')  # label for y axis  for the plotplt.ylabel('Average Speed')  x_1 = [(10, 3), (15, 4)]y_1 = (50, 10)  # Plotting the chartplt.broken_barh(x_1, y_1, facecolors ='cyan')  x_2 = [(1, 4), (10, 1), (15, 4), (25, 6)]y_2 = (70, 10)  # Plotting the chartplt.broken_barh(x_2, y_2, facecolors ='green')  x_3 = [(5, 3), (11, 2), (18, 5)]y_3 = (90, 10)  # Plotting the chartplt.broken_barh(x_3, y_3, facecolors ='blue')  plt.show()
Output :
Python-matplotlib
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How to change the scale of an existing table in Matplotlib?

To change scale of a table, we can use the scale() method. Steps −
Create a figure and a set of subplots, nrows=1 and ncols=1.
Create a figure and a set of subplots, nrows=1 and ncols=1.
Create a random data using numpy.
Create a random data using numpy.
Make columns value.
Make columns value.
Make the axis tight and off.
Make the axis tight and off.
Initialize a variable fontsize to change the fontsize.
Initialize a variable fontsize to change the fontsize.
To set the fontsize of the table and to scale the table, we can use 1.5 and 1.5.
To set the fontsize of the table and to scale the table, we can use 1.5 and 1.5.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axs = plt.subplots(1, 1)
data = np.random.random((10, 3))
columns = ("Column I", "Column II", "Column III")
axs.axis('tight')
axs.axis('off')
fontsize = 10
the_table = axs.table(cellText=data, colLabels=columns, loc='center')
the_table.set_fontsize(fontsize)
the_table.scale(1.5, 1.5)
plt.show()
Java Examples - Check port

How to check whether a port is being used or not ?
Following example shows how to check whether any port is being used as a server or not by creating a socket object.
import java.net.*;
import java.io.*;

public class Main {
   public static void main(String[] args) {
      Socket Skt;
      String host = "localhost";
      
      if (args.length > 0) {
         host = args[0];
      }
      for (int i = 0; i < 1024; i++) {
         try {
            System.out.println("Looking for "+ i);
            Skt = new Socket(host, i);
            System.out.println("There is a server on port " + i + " of " + host);
         } catch (UnknownHostException e) {
            System.out.println("Exception occured"+ e);
            break;
         } catch (IOException e) {}
      }
   }
}
The above code sample will produce the following result.
Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . . 

 Print
 Add Notes
 Bookmark this page
How to define a table caption using HTML ? - GeeksforGeeks

08 Jun, 2020
In this article, we define a table caption by using the <caption> tag element. The caption element is used to specify the caption of a table. This tag will be inserted just after the
Syntax:
<caption align="value"> </caption>
Example:
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Mahotas - Median filter - GeeksforGeeks

01 Dec, 2021
In this article we will see how we can apply median filter to the image in mahotas. The median filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Such noise reduction is a typical pre-processing step to improve the results of later processing (for example, edge detection on an image).In this tutorial we will use “lena” image, below is the command to load it. 
mahotas.demos.load('lena')
Below is the lena image 
In order to do this we will use mahotas.median_filter methodSyntax : mahotas.median_filter(img)Argument : It takes image object as argumentReturn : It returns image object  
Note : Input image should be filtered or should be loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this 
image = image[:, :, 0]
Below is the implementation 
Python3
# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as npimport matplotlib.pyplot as plt   # loading imageimg = mahotas.demos.load('lena')   # filtering imageimg = img.max(2) print("Image")   # showing imageimshow(img)show() # applying median filternew_img = mahotas.median_filter(img)   # showing imageprint("Median Filter")imshow(new_img)show()
Output :
Image
Median Filter
Another example 
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import gray, imshow, showimport osimport matplotlib.pyplot as plt  # loading imageimg = mahotas.imread('dog_image.png')  # filtering imageimg = img[:, :, 0]   print("Image")   # showing imageimshow(img)show() # applying median filternew_img = mahotas.median_filter(img)   # showing imageprint("Median Filter")imshow(new_img)show()
Output :
Image
Median Filter
arorakashish0911
sweetyty
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Combining multiple columns in Pandas groupby with dictionary - GeeksforGeeks

27 Oct, 2021
Let’ see how to combine multiple columns in Pandas using groupby with dictionary with the help of different examples.
Example #1:
# importing pandas as pd import pandas as pd   # Creating a dictionary d = {'id':['1', '2', '3'],     'Column 1.1':[14, 15, 16],     'Column 1.2':[10, 10, 10],     'Column 1.3':[1, 4, 5],     'Column 2.1':[1, 2, 3],     'Column 2.2':[10, 10, 10], }  # Converting dictionary into a data-frame df = pd.DataFrame(d)print(df)
Output:
# Creating the groupby dictionary groupby_dict = {'Column 1.1':'Column 1',                'Column 1.2':'Column 1',                'Column 1.3':'Column 1',                'Column 2.1':'Column 2',                'Column 2.2':'Column 2' }  # Set the index of df as Column 'id'df = df.set_index('id')  # Groupby the groupby_dict created above df = df.groupby(groupby_dict, axis = 1).min()print(df)
Output:
Explanation
Here we have grouped Column 1.1, Column 1.2 and Column 1.3 into Column 1 and Column 2.1, Column 2.2 into Column 2.
Notice that the output in each column is the min value of each row of the columns grouped together. i.e in Column 1, value of first row is the minimum value of Column 1.1 Row 1, Column 1.2 Row 1 and Column 1.3 Row 1.
 Example #2:
# importing pandas as pd import pandas as pd   # Create dictionary with data dict = {    "ID":[1, 2, 3],    "Movies":["The Godfather", "Fight Club", "Casablanca"],    "Week_1_Viewers":[30, 30, 40],    "Week_2_Viewers":[60, 40, 80],    "Week_3_Viewers":[40, 20, 20] };  # Convert dictionary to dataframedf = pd.DataFrame(dict);print(df)
Output:
# Create the groupby_dict groupby_dict = {"Week_1_Viewers":"Total_Viewers",           "Week_2_Viewers":"Total_Viewers",           "Week_3_Viewers":"Total_Viewers",           "Movies":"Movies" }  df = df.set_index('ID')df = df.groupby(groupby_dict, axis = 1).sum()print(df)
Output:
Explanation:
Here, notice that even though ‘Movies’ isn’t being merged into another column it still has to be present in the groupby_dict, else it won’t be in the final dataframe.
To calculate the Total_Viewers we have used the .sum() function which sums up all the values of the respective rows.
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Draw a snowman using turtle module in Python - GeeksforGeeks

01 Oct, 2020
Prerequisite: Turtle module, Drawing Shapes
There are many modules in python which depicts graphical illustrations, one of them is turtle, it is an in-built module in Python, which lets the user control a pen(turtle) to draw on screen(drawing board). It is mostly used to illustrate figures, shapes, designs etc.  In this article, we will learn how to draw a snowman using the turtle module. Snowman consists of circular shaped snowballs of various sizes. The body of the snowman is made up of three snowballs placed one over the other. Eyes, nose, and buttons are also circular.  
Below are the steps of the above approach:
Import turtle package. Set screen with dimensions and color. Create a turtle object with color. Create the Snowman by illustrating overlapping circles at particular positions.
Import turtle package. 
Set screen with dimensions and color. 
Create a turtle object with color. 
Create the Snowman by illustrating overlapping circles at particular positions.
Below is the Python program to illustrate a snowman using turtle module:
Python3
# Import required moduleimport turtle      # Create turtle objectt = turtle.Turtle()  # Create a screen screen =turtle.Screen()  # Set background colorscreen.bgcolor("sky blue")      # Function to draw body of snowmandef draw_circle(color, radius, x, y):    t.penup()    t.fillcolor (color)    t.goto (x, y)    t.pendown()    t.begin_fill()    t.circle (radius)    t.end_fill()          # Illustrating snowman # Drawing snowman bodydraw_circle ("#ffffff", 30, 0, -40)draw_circle ("#ffffff", 40, 0, -100)draw_circle ("#ffffff", 60, 0, -200)  # Drawing left eyedraw_circle ("#ffffff", 2, -10, -10)   # Drawing right eyedraw_circle ("#ffffff", 2, 10, -10)   # Drawing nosedraw_circle ("#FF6600", 3, 0, -15)     # Drawing buttons ondraw_circle ("#ffffff", 2, 0, -35)draw_circle ("#ffffff", 2, 0, -45)draw_circle ("#ffffff", 2, 0, -55)      # Function to draw arms def create_line(x, y, length, angle):    t.penup()    t.goto(x, y)    t.setheading(angle)    t.pendown()    t.forward(length)    t.setheading(angle + 20)    t.forward(20)    t.penup()    t.back(20)    t.pendown()    t.setheading(angle - 20)    t.forward(20)    t.penup()    t.home()             # Drawing left armcreate_line(-70, -50, 50, 160)   # Drawing right armcreate_line(70, -50, 50, 20)       # Drawing hatt.penup()t.goto (-35, 8)t.color ("black")t.pensize (6)t.pendown()t.goto (35, 8)  t.goto (30, 8)t.fillcolor ("black")t.begin_fill()t.left (90)t.forward (15)t.left (90)t.forward (60)t.left (90)t.forward (15)t.end_fill()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert HashSet to array in Java - GeeksforGeeks

11 Dec, 2020
Java HashSet class is used to create a collection that uses a hash table for the storage of elements. It inherits AbstractSet class and implements Set Interface. 
The key points about HashSet are:
HashSet contains unique elements only.
HashSet allows null values.
The insertion of elements in a HashSet is based on a hashcode.
HashSet is best used for searching problems.
There are two ways of converting HashSet to the array:
Traverse through the HashSet and add every element to the array.To convert a HashSet into an array in java, we can use the function of toArray().
Traverse through the HashSet and add every element to the array.
To convert a HashSet into an array in java, we can use the function of toArray().
Method 1: By traversing the set add elements to the array
We can traverse the Set using a simple for loop and then add elements one by one to the array.
Java
// Java program to convert HashSet to array  import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        HashSet<String> set = new HashSet<String>();        set.add("1");        set.add("13");        set.add("27");        set.add("87");        set.add("19");          System.out.println("Hash Set Contains :" + set);        String arr[] = new String[set.size()];                  int i=0;                // iterating over the hashset        for(String ele:set){          arr[i++] = ele;        }          for (String n : arr)            System.out.println(n);    }}
Hash Set Contains :[1, 13, 27, 19, 87]
1
13
27
19
87
Method 2: Using toArray() method
Syntax:
public Object[] toArray()
           or
public <T> T[] toArray(T[] a)
Parameters: This method either accepts no parameters or it takes an array T[] a as a parameter which is the array into which the elements of the list are to be stored if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Return Value: The function returns an array containing all the elements in this list.
Java
// Java program to convert HashSet to array  import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        HashSet<String> set = new HashSet<String>();        set.add("1");        set.add("13");        set.add("27");        set.add("87");        set.add("19");          System.out.println("Hash Set Contains :" + set);        String arr[] = new String[set.size()];                // toArray() method converts the set to array        set.toArray(arr);          for (String n : arr)            System.out.println(n);    }}
Hash Set Contains :[1, 13, 27, 19, 87]
1
13
27
19
87
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Node.js Buffer.concat() Method - GeeksforGeeks

13 Oct, 2021
The Buffer.concat() method is used to concat all buffer objects in a given array into one buffer object. The return value of this method is also a buffer. If length of buffer is not provided then it is calculated from the Buffer instances in list.
Syntax:
Buffer.concat( list, length )
Parameters: This method accept two parameters as mentioned above and described below:
list: Contains the list of buffers to concat.
length: It defines the length of the concatenated buffer. This parameter is optional.
Example 1:
// Returns a new buffer with the// copy of the passed stringvar buf1 = Buffer.from("Geeks");  // Returns another buffer with// copy of the passed stringvar buf2 = Buffer.from("for");  var buf3 = Buffer.from("Geeks");  // Creates an array of buffersvar list = [buf1, buf2, buf3];  // Concatenates all buffer objects into one buffervar newbuff = Buffer.concat(list);  console.log("The concatenated buffer:");  // Displays the concatenated bufferconsole.log(newbuff); 
Output:
The concatenated buffer:
<Buffer 47 65 65 6b 73 66 6f 72 47 65 65 6b 73>
Example 2:
// Returns a new buffer with the// copy of the passed stringvar buf1 = Buffer.from("Good");  // Returns another buffer with// copy of the passed stringvar buf2 = Buffer.from("morning");  var buf3 = Buffer.from("everyone");  // Creates an array of buffersvar list = [buf1, buf2, buf3];  // Concatenates all buffer objects// into one buffervar newbuff = Buffer.concat(list);  console.log("The concatenated buffer:");  // Displays the concatenated bufferconsole.log(newbuff); 
Output:
The concatenated buffer:
<Buffer 47 6f 6f 64 6d 6f 72 6e 69 6e 67 65 76 65 72 79 6f 6e 65>

Note: The above program will compile and run by using the node index.js command.
Reference:https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
ReactJS Components Complete Reference - GeeksforGeeks

21 Mar, 2022
Components are bits of code that are freelance and reusable. They serve a similar purpose as JavaScript functions. However, work isolation and returns HTML via a render function.
A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier. You can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI.
Components in React basically return a piece of JSX code which tells what should be rendered on the screen. In React, we mainly have two types of components:
Functional Components: Functional components are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React:
Javascript
function Democomponent()  {     return <h1>Welcome Message!</h1>;  }
  
Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React.
 
Below example shows a valid class-based component in React:
 
Javascript
class Democomponent extends React.Component  {     render(){           return <h1>Welcome Message!</h1>;     }  }
Complete Reference:
ReactJS | Components
ReactJS | Components – Set 2
ReactJS Pure Components
ReactJS | Functional Components
ReactJS | Lifecycle of Components
Differences between Functional Components and Class Components in React
Presentational vs container components
react-js
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
Create a Responsive Navbar using ReactJS