code-rag-bench/online-tutorials huggingface dataset:
Unix Socket - Structures

Various structures are used in Unix Socket Programming to hold information about the address and port, and other information. Most socket functions require a pointer to a socket address structure as an argument. Structures defined in this chapter are related to Internet Protocol Family.
The first structure is sockaddr that holds the socket information −
struct sockaddr {
   unsigned short   sa_family;
   char             sa_data[14];
};
This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields −
AF_INET
AF_UNIX
AF_NS
AF_IMPLINK
The second structure that helps you to reference to the socket's elements is as follows −
struct sockaddr_in {
   short int            sin_family;
   unsigned short int   sin_port;
   struct in_addr       sin_addr;
   unsigned char        sin_zero[8];
};
Here is the description of the member fields −
AF_INET
AF_UNIX
AF_NS
AF_IMPLINK
This structure is used only in the above structure as a structure field and holds 32 bit netid/hostid.
struct in_addr {
   unsigned long s_addr;
};
Here is the description of the member fields −
This structure is used to keep information related to host.
struct hostent {
   char *h_name; 
   char **h_aliases; 
   int h_addrtype;  
   int h_length;    
   char **h_addr_list
	
#define h_addr  h_addr_list[0]
};
Here is the description of the member fields −
NOTE − h_addr is defined as h_addr_list[0] to keep backward compatibility.
This particular structure is used to keep information related to service and associated ports.
struct servent {
   char  *s_name; 
   char  **s_aliases; 
   int   s_port;  
   char  *s_proto;
};
Here is the description of the member fields −
TCP
UDP
Socket address structures are an integral part of every network program. We allocate them, fill them in, and pass pointers to them to various socket functions. Sometimes we pass a pointer to one of these structures to a socket function and it fills in the contents.
We always pass these structures by reference (i.e., we pass a pointer to the structure, not the structure itself), and we always pass the size of the structure as another argument.
When a socket function fills in a structure, the length is also passed by reference, so that its value can be updated by the function. We call these value-result arguments.
Always, set the structure variables to NULL (i.e., '\0') by using memset() for bzero() functions, otherwise it may get unexpected junk values in your structure.
PHP | strrev() Function

11 Aug, 2021
Reversing a string is one of the most basic string operations and is used very frequently by developers and programmers. PHP comes with a built-in function to reverse strings.
The strrev() function is a built-in function in PHP and is used to reverse a string. This function does not make any change in the original string passed to it as a parameter. 
Syntax: 
string strrev($inpString)
Parameter: This function accepts a single parameter $inpString. This parameter is a string and it specifies the string which we want to reverse. If a number is passed to it instead of a string, it will also reverse that number. 
Return Value: The strrev() function returns the reversed string or the number. It does not make any change to the original string or number passed in the parameter. 
Examples:  
Input : $string = "geeks" 
Output : skeeg 

Input : $string = 143 
Output : 341 
Below programs illustrate the strrev() function in PHP:
Program 1: PHP program to demonstrate the strrev() function when a string is passed.  
PHP
<?php// PHP program to demonstrate the// strrev() function when a string is passed $str = "geeks"; // prints the reversed stringecho strrev($str);?>
Output: 
skeeg
Program 2: PHP program to demonstrate the strrev() function when a number is passed.  
PHP
<?php// PHP program to demonstrate the// strrev() function when a number is passed // passing number instead of string$num = 134; // prints the reversed numberecho strrev($num);?>
Output: 
431
Reference: http://php.net/manual/en/function.strrev.php 
sumitgumber28
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7 - Show Java

static void Main(string[] args)
    {
      string firstName = "John ";
      string lastName = "Doe";
      string name = string.Concat(firstName, lastName);
How to change the color of points in a scatterplot using ggplot2 in R?

To color the points in a scatterplot using ggplot2, we can use colour argument inside geom_point with aes. The color can be passed in multiple ways, one such way is to name the particular color and the other way is to giving a range or using a variable. If range or a variable will be used then the color of the points will be in different shades.
 Live Demo
Consider the below data frame −
x<−rnorm(20,5,2)
y<−rnorm(20,5,1.25)
df<−data.frame(x,y)
df
      x       y
1 6.3184535 5.548867
2 3.4643698 6.247067
3 7.8930528 2.259042
4 7.6517535 4.606704
5 1.7838941 3.605288
6 0.3985215 6.183794
7 5.2738435 3.857376
8 4.7734419 3.389663
9 3.9727197 5.662962
10 3.3976335 5.172815
11 4.1068840 4.379264
12 6.7723590 5.914132
13 3.0944360 4.184177
14 7.0857100 5.266121
15 2.6391362 4.433864
16 5.2571231 4.144391
17 5.8119542 4.725406
18 5.3608015 4.828909
19 9.7308286 6.489042
20 2.3823201 6.916862
Loading ggplot2 package and creating a scatterplot −
library(ggplot2)
ggplot(df,aes(x,y,col=x))+geom_point()
Creating the scatterplot by using the variable x −
ggplot(df,aes(x,y))+geom_point(aes(colour=x))
How to get a list of all the keys from a Python dictionary?

To get a list of all keys from a dictionary, you can simply use the dict.keys() function. 
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
key_list = list(my_dict.keys())
print(key_list)
This will give the output −
['name', 'time', 'location']
You can also get a list of all keys in a dictionary using a list comprehension. 
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
key_list = [key for key in my_dict]
print(key_list)
This will give the output −
['name', 'time', 'location']
Byte Class in Java

The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.
Following are some of the methods of the Byte class −
Let us now see an example−
 Live Demo
import java.lang.*;
public class Demo {
   public static void main(String[] args){
      Byte b1, b2;
      int i1, i2;
      b1 = new Byte("1");
      b2 = new Byte("-1");
      i1 = b1.intValue();
      i2 = b2.intValue();
      String str1 = "int value of Byte " + b1 + " is " + i1;
      String str2 = "int value of Byte " + b2 + " is " + i2;
      System.out.println( str1 );
      System.out.println( str2 );
   }
}
int value of Byte 1 is 1
int value of Byte -1 is -1
Let us now see another example −
 Live Demo
import java.lang.*;
public class Demo {
   public static void main(String[] args){
      Byte b1, b2;
      String s1, s2;
      b1 = new Byte("-123");
      b2 = new Byte("0");
      s1 = b1.toString();
      s2 = b2.toString();
      String str1 = "String value of Byte " + b1 + " is " + s1;
      String str2 = "String value of Byte " + b2 + " is " + s2;
      System.out.println( str1 );
      System.out.println( str2 );
   }
}
String value of Byte -123 is -123
String value of Byte 0 is 0
Material - Action Icons

This chapter explains the usage of Google's (Material) Action Icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
		
      <style>
         i.custom {font-size: 2em; color: green;}
      </style>
		
   </head>
	
   <body>
      <i class = "material-icons custom">accessibility</i>
   </body>
	
</html>
The following table contains the usage and results of Google's (Material) Action Icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Kotlin Break and Continue

The break statement is used to jump out of a 
loop.
This example jumps out of the loop when i is equal to 4:
var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
var i = 0
while (i < 10) {
  if (i == 4) {
    i++
    continue
  }
  println(i)
  i++}
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.
BFS for Disconnected Graph in C++

Disconnected graph is a Graph in which one or more nodes are not the endpoints of the graph i.e. they are not connected.
A disconnected graph...
Now, the Simple BFS is applicable only when the graph is connected i.e. all vertices of the graph are accessible from one node of the graph. in the above disconnected graph technique is not possible as a few laws are not accessible so the following changed program would be better for performing breadth first search in a disconnected graph.
#include<bits/stdc++.h>
using namespace std;
void insertnode(vector<int> adj[], int u, int v) {
   adj[u].push_back(v);
}
void breathFirstSearch(int u, vector<int> adj[], vector<bool> &visited) {
   list<int> q;
   visited[u] = true;
   q.push_back(u);
   while(!q.empty()) {
      u = q.front();
      cout << u << " ";
      q.pop_front();
      for (int i = 0; i != adj[u].size(); ++i) {
         if (!visited[adj[u][i]]) {
            visited[adj[u][i]] = true;
            q.push_back(adj[u][i]);
         }
      }
   }
}
void BFSdisc(vector<int> adj[], int V) {
   vector<bool> visited(V, false);
   for (int u=0; u<V; u++)
   if (visited[u] == false)
   breathFirstSearch(u, adj, visited);
}
int main() {
   int V = 5;
   vector<int> adj[V];
   insertnode(adj, 0, 23);
   insertnode(adj, 0, 4);
   insertnode(adj, 1, 2);
   insertnode(adj, 1, 3);
   insertnode(adj, 1, 4);
   insertnode(adj, 2, 3);
   insertnode(adj, 3, 4);
   BFSdisc(adj, V);
   return 0;
}
0 4 1 2 3
How to write "Hello World" in C#?

To print “Hello World” in C#, use the Console.WriteLine.
Let us see a basic C# program to display a text −
 Live Demo
using System;
using System.Collections.Generic;
using System.Text;

namespace Program {
   class MyApplication {
      static void Main(string[] args) {
         Console.WriteLine("Hello World");
         Console.Read();
      }
   }
}
Hello World
Above, we displayed the text “Hello World” using the WriteLine() method. The output is displayed using the Console −
Console.WriteLine("Hello World");
HTML <input type=”radio”>

15 Dec, 2021
The HTML <input type=”radio”> is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”.
Syntax:
<input type="radio">
Example: In this example, we simply select the correct option from the given options using the radio button.
HTML
<!DOCTYPE html><html>  <body>    <h2>Welcome To GeeksforGeeks</h2>  <p>Select a Technology Brand:</p>    <div>    <input type="radio" id="Netflix" name="brand" value="Netflix">    <label for="Netflix">Netflix</label>  </div>    <div>    <input type="radio" id="Audi" name="brand" value="Audi">    <label for="Audi">Audi</label>  </div>    <div>    <input type="radio" id="Microsoft" name="brand" value="Microsoft" checked>    <label for="Microsoft">Microsoft</label>  </div>  </body>  </html>
Output:
<input type=”radio”>
Example: This example explains the HTML input type as radio button by specifying its value as true.
HTML
<!DOCTYPE html><html>  <head>    <title> HTML input type radio </title>    <style>    body {        text-align: center;    }          h1 {        color: green;    }    </style></head>  <body>    <h1>        GeeksforGeeks    </h1>    <h2>        HTML <Input type= "radio">  </h2>     Radio Button:    <input type="radio"            checked=true            id="radioID"            value="Geeks_radio"            name="Geek_radio"> </body>  </html>
Output:
<input type=”radio”>
Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Microsoft Edge 12 and above
shubhamyadav4
bhaskargeeksforgeeks
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
MySQL query to convert a single digit number to two-digit

For this, you can use LPAD() and pad a value on the left.
Let us first create a table −
mysql> create table DemoTable767 (Value varchar(100));
Query OK, 0 rows affected (1.40 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable767 values('4');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable767 values('5');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable767 values('6');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable767 values('1');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable767;
This will produce the following output -
+-------+
| Value |
+-------+
| 4     |
| 5     |
| 6     |
| 1     |
+-------+
4 rows in set (0.00 sec)
Following is the query to convert a single digit number to two-digit by padding values −
mysql> select lpad(Value,2,'0') from DemoTable767;
This will produce the following output -
+-------------------+
| lpad(Value,2,'0') |
+-------------------+
| 04                |
| 05                |
| 06                |
| 01                |
+-------------------+
4 rows in set (0.00 sec)
PyQt5 – How to add image in window ?

03 Aug, 2021
In this article, we will see how to add image to a window. The basic idea of doing this is first of all loading the image using QPixmap and adding the loaded image to the Label then resizing the label according to the dimensions of the image, although the resizing part is optional.
In order to use Qpixmap and other stuff we have to import following libraries: 
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys
For loading image : Syntax : 
pixmap = QPixmap('image.png')
Argument : Image name if image is in same folder else file path.   For adding image to label : Syntax : 
label.setPixmap(pixmap)
Argument : It takes QPixmap object as argument.
Code :  
Python3
# importing the required libraries from PyQt5.QtWidgets import *from PyQt5.QtGui import QPixmapimport sys  class Window(QMainWindow):    def __init__(self):        super().__init__()         self.acceptDrops()        # set the title        self.setWindowTitle("Image")         # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)         # creating label        self.label = QLabel(self)                 # loading image        self.pixmap = QPixmap('image.png')         # adding image to label        self.label.setPixmap(self.pixmap)         # Optional, resize label to image size        self.label.resize(self.pixmap.width(),                          self.pixmap.height())         # show all the widgets        self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output : 
 
arorakashish0911
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Limitation of Distributed System

31 Jan, 2020
Distributed System is a collection of self-governing computer systems efficient of transmission and cooperation among each other by the means of interconnections between their hardware and software. It is a collection of loosely coupled processor that appears to its users a single systematic system. Distributed systems has various limitations such as in distributed system there is not any presence of a global state. This differentiates distributed system computing from databases in which a steady global state is maintained.
Distributed system limitations has the impact on both design and implementation of distributed systems. There are mainly two limitations of the distributed system which are as following:
1. Absence of a Global Clock
2. Absence of Shared Memory
The above two limitations of the distributed system are explained as following below:
1. Absence of a Global Clock:In a distributed system there are a lot of systems and each system has its own clock. Each clock on each system is running at a different rate or granularity leading to them asynchronous. In starting the clocks are regulated to keep them consistent, but only after one local clock cycle they are out of the synchronization and no clock has the exact time.Time is known for a certain precision because it is used for the following in distributed system:
Temporal ordering of events
Collecting up-to-date information on the state of the integrated system
Scheduling of processes
There are restrictions on the precision of time by which processes in a distributed system can synchronize their clocks due to asynchronous message passing. Every clock in distributed system is synchronize with a more reliable clock, but due to transmission and execution time lapses the clocks becomes different. Absence of global clock make more difficult the algorithm for designing and debugging of distributed system.
2. Absence of Shared Memory:Distributed systems have not any physically shared memory, all computers in the distributed system have their own specific physical memory. As computer in the distributed system do not share the common memory, it is impossible for any one system to know the global state of the full distributed system. Process in the distributed system obtains coherent view of the system but in actual that view is partial view of the system.As in distributed system there is an absence of a global state, it is challenging to recognize any global property of the system. The global state in distributed system is divided by many number of computers into smaller entities.
Distributed System
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
Differences between IPv4 and IPv6
GSM in Wireless Communication
Wireless Application Protocol
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
GUI to Shutdown, Restart and Logout from the PC using Python

21 Oct, 2021
In this article, we are going to write a python script to shut down or Restart or Logout your system and bind it with GUI Application. 
The OS module in Python provides functions for interacting with the operating system. OS is an inbuilt library python.
Syntax :
For shutdown your system : os.system(“shutdown /s /t 1”)
For restart your system : os.system(“shutdown /r /t 1”)
For Logout your system : os.system(“shutdown -l”)
Implementation GUI Application using Tkinter:
Python3
# import modulesfrom tkinter import *import os  # user define functiondef shutdown():    return os.system("shutdown /s /t 1") def restart():    return os.system("shutdown /r /t 1") def logout():    return os.system("shutdown -l")  # tkinter objectmaster = Tk() # background set to greymaster.configure(bg='light grey') # creating a button using the widget# Buttons that will call the submit functionButton(master, text="Shutdown", command=shutdown).grid(row=0)Button(master, text="Restart", command=restart).grid(row=1)Button(master, text="Log out", command=logout).grid(row=2) mainloop()
Output:
Note: Please ensure that you save and close all the programs before running this code on the IDLE, as this program will immediately shutdown and restart your computer.
saurabh1990aror
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
SQL - CHECK Constraint

The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered the table.
For example, the following program creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18 years.
CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL CHECK (AGE >= 18),
   ADDRESS  CHAR (25) ,
   SALARY   DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);
If the CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement like the one given below.
ALTER TABLE CUSTOMERS
   MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );
You can also use the following syntax, which supports naming the constraint in multiple columns as well −
ALTER TABLE CUSTOMERS
   ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);
To drop a CHECK constraint, use the following SQL syntax. This syntax does not work with MySQL.
ALTER TABLE CUSTOMERS
   DROP CONSTRAINT myCheckConstraint;
How to Create a Table With Multiple Foreign Keys in SQL?

26 Sep, 2021
When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple foreign keys based on the requirement.
In this article let us see how to create a table with multiple foreign keys in MSSQL.
 Syntax:
column_name(non_prime) data_type REFERENCES table_name(column_name(prime)
Step 1: Creating a Database
We use the below command to create a database named GeeksforGeeks:
Query:
CREATE DATABASE GeeksforGeeks
Step 2: Using the Database
To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks
Step 3: Creating 3 tables. The table student_details contains two foreign keys that reference the tables student_branch_details and student_address.
Query:
CREATE TABLE student_details(
  stu_id VARCHAR(8) NOT NULL PRIMARY KEY,
  stu_name VARCHAR(20),
  stu_branch VARCHAR(20) FOREIGN KEY REFERENCES student_branch_details(stu_branch),
  stu_pin_code VARCHAR(6) FOREIGN KEY REFERENCES student_address(stu_pin_code)
  );
CREATE TABLE student_branch_details(
  stu_branch VARCHAR(20) PRIMARY KEY,
  subjects INT,
  credits INT
);
CREATE TABLE student_address(
  stu_pin_code VARCHAR(6) PRIMARY KEY,
  stu_state VARCHAR(20),
  student_city VARCHAR(20)
);
Output:
The number and type of keys can be checked in the tables section of object explorer on the left side of the UI.
Step 4: Inserting data into the Table  
Inserting rows into student_branch_details and student_address tables using the following SQL query:
Query:
INSERT INTO student_branch_details VALUES
  ('E.C.E',46,170),
  ('E.E.E',47,178),
  ('C.S.E',44,160)

INSERT INTO student_address VALUES
  ('555555', 'xyz','abc'),
  ('666666', 'yyy','aaa'),
  ('777777','zzz','bbb'),
  ('888888','www','ccc'),
  ('999999','vvv','ddd')
Inserting rows into student_details
Query:
INSERT INTO student_details VALUES
('1940001','PRATHAM','E.C.E','555555'),
('1940002','ASHOK','C.S.E','666666'),
('1940003','PAVAN KUMAR','C.S.E','777777'),
('1940004','SANTHOSH','E.C.E','888888'),
('1940005','THAMAN','E.C.E','999999'),
('1940006','HARSH','E.E.E','888888')
Step 5: Verifying the inserted data 
Viewing the tables student_details,student_branch_details,student_address after inserting rows by using the following SQL query:
Query:
SELECT * FROM student_details
SELECT * FROM student_branch_details
SELECT * FROM student_address
Output:
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Difference Between Local Storage, Session Storage And Cookies
Data Mining - Cluster Analysis
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
Matplotlib.figure.Figure.add_gridspec() in Python

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The add_gridspec() method figure module of matplotlib library is used to get the GridSpec that has this figure as a parent.
Syntax: add_gridspec(self, nrows, ncols, **kwargs)
Parameters: This accept the following parameters that are described below:
nrows : This parameter is the number of rows in grid.
ncols : This parameter is the number or columns in grid.
Returns: This method return the GridSpec.
Below examples illustrate the matplotlib.figure.Figure.add_gridspec() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec    fig = plt.figure(constrained_layout = True)gs = fig.add_gridspec(3, 3)ax = fig.add_subplot(gs[0, :])ax.set_title('gs[0, :]')ax2 = fig.add_subplot(gs[1, :-1])ax2.set_title('gs[1, :-1]')    fig.suptitle('matplotlib.figure.Figure.add_gridspec() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec    fig = plt.figure()gs = fig.add_gridspec(2, 2)ax1 = fig.add_subplot(gs[0, 0])ax2 = fig.add_subplot(gs[1, 0])ax3 = fig.add_subplot(gs[:, 1])    fig.suptitle('matplotlib.figure.Figure.add_gridspec()\ function Example\n\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Accessing Values of Tuples in Python

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.
 Live Demo
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Insertion sort using C++ STL

In this tutorial, we will be discussing a program to understand the insertion sort using C++ STL.
In this we use std::upper_bound to find the element at the wrong position, then rotate the unsorted part of the array to make it sorted.
 Live Demo
#include <bits/stdc++.h>
//function to perform insertion sort
void insertionSort(std::vector<int> &vec){
   for (auto it = vec.begin(); it != vec.end(); it++){
      auto const insertion_point =
      std::upper_bound(vec.begin(), it, *it);
      std::rotate(insertion_point, it, it+1);
   }
}
//printing the array
void print(std::vector<int> vec){
   for( int x : vec)
   std::cout << x << " ";
   std::cout << '\n';
}
int main(){
   std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6};
   insertionSort(arr);
   print(arr);
   return 0;
}
1 2 3 4 5 5 6 7
How to set a cookie to a specific domain in selenium webdriver with Python?

We can set a cookie to a specific domain in Selenium webdriver with Python. A cookie is used to hold information sent by the browser. A key−value pair format is utilized and it is like a message provided to the browser by the server.
For cookie addition, the method add_cookie is used. The key and value are passed as parameters to the method. To get back all the cookies, get_cookies method is used. To get a specific cookie, the method get_cookie is used.
To delete cookies, the method delete_all_cookies is used.
driver.add_cookie({"Automation": "QA"});
c= driver.get_cookies();
driver.get_cookie({"Automation");
driver.delete_all_cookies();
from selenium import webdriver
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#add cookie
c = {'name' : "Automation", 'value' : 'QA'}
driver.add_cookie(c);
#count total cookies
print(len(driver.get_cookies()))
#obtain cookie with name
print(driver.get_cookie("Automation"))
#delete cookies
driver.delete_all_cookies();
#check cookies after delete
d = driver.get_cookies()
print("Cookie count after all deletion")
print(len(d))
#close browser
driver.quit()
List isEmpty() method in Java with Examples - GeeksforGeeks

23 Aug, 2020
The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.
Syntax:
boolean isEmpty()
Parameter: It does not accepts any parameter.
Returns: It returns True if the list has no elements else it returns false. The return type is of datatype boolean.
Error and Exceptions: This method has no error or exceptions.
Program to demonstrate working of isEmpty() in Java:
// Java code to demonstrate the working of// isEmpty() method in List interface  import java.util.*;  public class GFG {    public static void main(String[] args)    {        // creating an Empty Integer List        List<Integer> arr = new ArrayList<Integer>(10);          // check if the list is empty or not        // using isEmpty() function        boolean ans = arr.isEmpty();        if (ans == true)            System.out.println("The List is empty");        else            System.out.println("The List is not empty");          // addition of a element to        // the List        arr.add(1);          // check if the list is empty or not        // after adding an element        ans = arr.isEmpty();        if (ans == true)            System.out.println("The List is empty");        else            System.out.println("The List is not empty");    }}
Output:
The List is empty
The List is not empty

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#isEmpty()
Akanksha_Rai
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
How to Set Git Username and Password in GitBash? - GeeksforGeeks

03 Jan, 2022
Git is an open-source version control system. Git is software that helps to track updates in any folder. It is a DevOps resource used mostly for source code planning. It’s typically used to promote collaboration between coders who are relying on source code together during software development. Speed, the integrity of data, including support for dispersed, non-linear workflows are among the aims.
A terminal Git environment is handled by Git Bash (Bash, an acronym for Borne Again Shell).  Git Bash replicates a bash terminal on Windows. It allows you to use all git tools or most other typical Unix commands from the command line. If you’re used to Linux and want to preserve your routines, this is a great alternative.
Git is usually bundled as one of the elevated GUI applications in Windows settings. Bash is a popular Linux and Mac OS default shell. On a Windows operating system, Git Bash is a package that installs Bash, some standard bash utilities, and Git.  The fundamental version control system primitives may be abstracted and hidden by Git GUI s. Git Bash is a Microsoft Windows software that functions as an abstraction shell for the Git command-line experience. A shell is a console application that allows you to interact with your operating system by command prompt.
Now let us discuss how to set Git Username and Password in Git Bash
Step 1: After the successful installation of Git on your system, you have to right-click wherever you want to open the Git tab. Click on the Git Bash Here icon. Now here we will see the location of where the program is opened when the window opens.
Git Bash opened on Desktop.
Step 2: In the Git Bash window, type the below command and press enter. This will configure your Username in Git Bash.
$ git config --global user.name "GeeksforGeeks"
Step 3: After that, you will have to configure your email. For that, type
$git config --global user.email "GFGexample@gmail.orgg"
Step 4: To set your password, type the below command as depicted:
$git config --global user.password "1234321"
Step 5: To save the credentials forever, type the below command as depicted:
$ git config --global credential.helper store
This is how you set git username and password in git bash.
To check the inputs, type the below command as depicted:
git config --list --show-origin
Picked
Git
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Git Push Origin and Git Push Origin Master
Git - Difference Between Git Fetch and Git Pull
How to Push Git Branch to Remote?
How to Export Eclipse projects to GitHub?
Merge Conflicts and How to handle them
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to Align Text in HTML?
How to install Jupyter Notebook on Windows?
How to filter object array based on attributes?
Uninitialized primitive data types in C/C++ - GeeksforGeeks

10 Feb, 2022
What do you think happens when you use an uninitialized primitive data type? Well you may assume that the compiler should assign your primitive type variable with meaningful values like 0 for int, 0.0 for float. What about char data type?Let’s find the answer to that by running the code in the IDE. 
CPP
#include <iostream> using namespace std; int main(){    // The following primitive data type variables will not    // be initialized with any default values    char ch;    float f;    int i;    double d;    long l;     cout << ch << endl;    cout << f << endl;    cout << i << endl;    cout << d << endl;    cout << l << endl;     return 0;}
Output in GFGs IDE:  
5.88052e-39
0
6.9529e-310
0
Output in Codechef IDE:  
0
0
0
0
Output on my machine:  
1.4013e-045
0
2.96439e-323
0
Why C/C++ compiler does not initialize variables with default values? “One of the things that has kept C++ viable is the zero-overhead rule: What you don’t use, you don’t pay for.” -Stroustrup. The overhead of initializing a stack variable is costly as it hampers the speed of execution, therefore these variables can contain indeterminate values or garbage values as memory space is provided when we define a data type. It is considered a best practice to initialize a primitive data type variable before using it in code. 
abhijeetsinhasmith
C-Data Types
cpp-data-types
cpp-puzzle
C Language
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
LocalDate minusMonths() method in Java with Examples - GeeksforGeeks

24 Jul, 2019
The minusMonths() method of LocalDate class in Java is used to subtract the number of specified months from this LocalDate and return a copy of LocalDate.This method subtracts the months field in the following steps:
subtract the months from the month-of-year field.
Check if the date after subtracting months is valid or not.
If date is invalid then method adjust the day-of-month to the last valid day.
For example, 2018-07-31 minus one month gives date 2018-06-31 but this is invalid result, so the last valid day of the month, 2018-06-30, is returned.This instance is immutable and unaffected by this method call.
Syntax:
public LocalDate minusMonths(long monthsToSubtract)

Parameters: This method accepts a single parameter monthsToSubtract which represents the months to subtract, may be negative.
Return value: This method returns a LocalDate based on this date with the months subtracted, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the minusMonths() method:Program 1:
// Java program to demonstrate// LocalDate.minusMonths() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2018-11-13");          // print instance        System.out.println("LocalDate before"                           + " subtracting months: " + date);          // subtract 15 months        LocalDate returnvalue            = date.minusMonths(15);          // print result        System.out.println("LocalDate after "                           + " subtracting months: " + returnvalue);    }}
LocalDate before subtracting months: 2018-11-13
LocalDate after  subtracting months: 2017-08-13

Program 2:
// Java program to demonstrate// LocalDate.minusMonths() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2018-12-31");          // print instance        System.out.println("LocalDate before"                           + " subtracting months: " + date);          // subtract 3 months        LocalDate returnvalue            = date.minusMonths(3);          // print result        System.out.println("LocalDate after "                           + " subtracting months: " + returnvalue);    }}
LocalDate before subtracting months: 2018-12-31
LocalDate after  subtracting months: 2018-09-30

References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusMonths(long)
shubham_singh
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java
numpy.ndarray.copy() in Python - GeeksforGeeks

28 Dec, 2018
numpy.ndarray.copy() returns a copy of the array.
Syntax : numpy.ndarray.copy(order=’C’)
Parameters:order : Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
Code #1:
# Python program explaining  # numpy.ndarray.copy() function  import numpy as geek    x = geek.array([[0, 1, 2, 3], [4, 5, 6, 7]],                                 order ='F')print("x is: \n", x)  # copying x to yy = x.copy()print("y is :\n", y)print("\nx is copied to y")
x is: 
 [[0 1 2 3]
 [4 5 6 7]]
y is :
 [[0 1 2 3]
 [4 5 6 7]]

x is copied to y

 Code #2:
# Python program explaining  # numpy.ndarray.copy() function  import numpy as geek    x = geek.array([[0, 1, ], [2, 3]])print("x is:\n", x)  # copying x to yy = x.copy()  # filling x with 1'sx.fill(1)print("\n Now x is : \n", x)  print("\n y is: \n", y)
x is:
 [[0 1]
 [2 3]]

 Now x is : 
 [[1 1]
 [1 1]]

 y is: 
 [[0 1]
 [2 3]]

Python numpy-ndarray
Python-numpy
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
SQL Query to Copy, Duplicate or Backup Table - GeeksforGeeks

15 May, 2021
In relational databases, we often deal with different tables and perform various operations using this different database software like MYSQL, Oracle, PostgreSQL, etc. Sometimes, while performing these operations many of us want to keep a backup table which is beneficial and can be used as a reference or can be reused if needed. Similarly, many times we need to copy the same table again and create a duplicate version of itself. 
We can track changes of data using the backup table when we perform various modification operations. So, in this article, we are going to discuss how to copy as well as create a backup table in SQL.
Sample Input: Consider a schema “Student Information” which consists of data of Geeks who enrolled in our DSA course as shown below:
Syntax:
CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name;

Table_Name: The name of the backup table.
AS: Aliasing
In MYSQL, we can use the following command to check the number of tables created in the database before and after a backup. However, this command is not supported in PostgreSQL and in other versions of SQL.
SHOW TABLES;
Example 1: We can copy all the columns in the backup table.
Backup Table 1 Query
Output :
Output of Backup Table 1
Example 2: It is not mandatory to copy all the columns. We can take a few columns as well.
Syntax:
CREATE TABLE Table_Name AS SELECT col_1, col_2, ... FROM Source_Table_Name;

Table_Name: The name of the backup table.
AS: Aliasing
col: Required columns from source table
Backup Table 2 Query
Output :
Output of Backup Table 2
Till now we have seen how to create a  clone of the source table. In the above backup table, the data is also copied along with the table. However, we can also create a backup table without copying the data. So, to create a table without any data being copied we can use the help of the WHERE clause which needs to return a FALSE value. For example, we can use WHERE 2<2 or WHERE 1=2.
Syntax:
CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name
WHERE (RETURN FALSE);

Table_Name: The name of the backup table.
AS: Aliasing
FALSE: Any expression which returns FALSE. For example 4>5
Example 1: All the columns copied without any data.
Query For Backup Table
Output :
Backup Table Output
Example 2: It is not mandatory to copy all the columns. We can take a few columns as well.
Syntax:
CREATE TABLE Table_Name AS SELECT col1,col2,.... Source_Table_Name
WHERE (RETURN FALSE);

Table_Name: The name of the backup table.
AS: Aliasing
col: Required columns from source table
FALSE: Any expression which returns FALSE. For example 4>5
Query For Backup Table
Output :
Backup Table Output
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DDL and DML in DBMS
SQL | GROUP BY
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
D3.js scaleTime() Function - GeeksforGeeks

23 Aug, 2020
The d3.scaleTime() function is used to create and return a new time scale which have the particular domain and range. In this function the clamping is disabled by default.
Syntax:
d3.scaleTime([[domain, ]range]);
Parameter: This function accepts two parameters as mentioned above and described below.
Domain: It is an array of integers that defines the extent of domain values. If not specified then the default value is [2000-01-01, 2000-01-02].
Range: It is an array of integers or string. If not specified then the default value is [0, 1].
Return Value: This function returns a function.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0"/>    <script src="https://d3js.org/d3.v4.min.js">    </script>    <script src="https://d3js.org/d3-color.v1.min.js">    </script>    <script src=    "https://d3js.org/d3-interpolate.v1.min.js">    </script>    <script src=    "https://d3js.org/d3-scale-chromatic.v1.min.js">    </script></head>  <body>    <h2 style="color:green">Geeks for geeks</h2>    <p>d3.scaleTime() Function</p>    <script>        var time = d3.scaleTime()            .domain([1, 10])            .range([10, 5]);        document.write("<h3>Type of d3.scaleTime() is: "            + typeof (time) + "</h3>");                      document.write("<h3>time(10): "             + time(10) + "</h3>");    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width, initial-scale=1.0"/>    <script src="https://d3js.org/d3.v4.min.js">    </script>    <script src="https://d3js.org/d3-color.v1.min.js">    </script>    <script src=    "https://d3js.org/d3-interpolate.v1.min.js">    </script>    <script src=    "https://d3js.org/d3-scale-chromatic.v1.min.js">    </script></head>  <body>    <h2 style="color:green;">Geeks for geeks</h2>    <p>d3.scaleTime() Function </p>    <script>        var time = d3.scaleTime()            .domain([1, 10])            .range([1, 100])        document.write("<h3>time(1): " + time(1) + "</h3>")        document.write("<h3>time(2): " + time(2) + "</h3>")        document.write("<h3>time(3): " + time(3) + "</h3>")        document.write("<h3>time(4): " + time(4) + "</h3>")    </script></body>  </html>
Output:
D3.js
JavaScript
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 Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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?