code-rag-bench/online-tutorials huggingface dataset:
PHP | base64_encode() Function - GeeksforGeeks

14 Aug, 2018
The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.
Syntax:
string base64_encode( $data )
Parameters: This function accepts single parameter $data which is mandatory. It is used to specify the string encoding.
Return value: This function returns the encoded string in base64 on success or returns False in case of failure.
Below programs illustrate the base64_encode() function in PHP:
Program 1:
<?php  // Program to illustrate base64_encode()// function$str = 'GeeksforGeeks';  echo base64_encode($str);?>
R2Vla3Nmb3JHZWVrcw==

Program 2:
<?php  // Program to illustrate base64_encode()// function$str = 'GFG, A computer Science Portal For Geeks';echo base64_encode($str). "\n";  $str = '';echo base64_encode($str). "\n";  $str = 1;echo base64_encode($str). "\n";  $str = '@#$';echo base64_encode($str). "\n";?>
R0ZHLCBBIGNvbXB1dGVyIFNjaWVuY2UgUG9ydGFsIEZvciBHZWVrcw==

MQ==
QCMk

Reference: http://php.net/manual/en/function.base64-encode.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Comparing two dates in PHP
How to receive JSON POST with PHP ?
PHP | Converting string to Date and DateTime
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Big Data Analytics - K-Means Clustering

k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells.
Given a set of observations (x1, x2,  ..., xn), where each observation is a d-dimensional real vector, k-means clustering aims to partition the n observations into k groups G = {G1, G2, ..., Gk} so as to minimize the within-cluster sum of squares (WCSS) defined as follows −
argmin∑i=1k∑x∈Si∥x−μi∥2
The later formula shows the objective function that is minimized in order to find the optimal prototypes in k-means clustering. The intuition of the formula is that we would like to find groups that are different with each other and each member of each group should be similar with the other members of each cluster.
The following example demonstrates how to run the k-means clustering algorithm in R.
library(ggplot2)
# Prepare Data 
data = mtcars  

# We need to scale the data to have zero mean and unit variance 
data <- scale(data)  

# Determine number of clusters 
wss <- (nrow(data)-1)*sum(apply(data,2,var)) 
for (i in 2:dim(data)[2]) { 
   wss[i] <- sum(kmeans(data, centers = i)$withinss) 
}  

# Plot the clusters 
plot(1:dim(data)[2], wss, type = "b", xlab = "Number of Clusters", 
   ylab = "Within groups sum of squares")
In order to find a good value for K, we can plot the within groups sum of squares for different values of K. This metric normally decreases as more groups are added, we would like to find a point where the decrease in the within groups sum of squares starts decreasing slowly. In the plot, this value is best represented by K = 6.
Now that the value of K has been defined, it is needed to run the algorithm with that value.
# K-Means Cluster Analysis
fit <- kmeans(data, 5) # 5 cluster solution 

# get cluster means  
aggregate(data,by = list(fit$cluster),FUN = mean) 

# append cluster assignment 
data <- data.frame(data, fit$cluster) 


    65 Lectures 
     6 hours 

 Arnab Chakraborty

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava, Harshit Srivastava

    23 Lectures 
     2 hours 

 John Shea

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava

    46 Lectures 
     3.5 hours 

 Pranjal Srivastava

    37 Lectures 
     3.5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Differences between CSS and PHP - GeeksforGeeks

15 Sep, 2020
CSS: CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that will be displayed in the browsers as a web-page. By using CSS, the website which has been created by using HTML will look attractive. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of the web-page then the CSS will be the skin of the skeleton. The Internet media type (MIME type) of CSS is text/CSS.
Example: This example describes the use of simple CSS. CSS has been used with HTML inside the style tag.
HTML
<!DOCTYPE ><html>    <head>        <style>            h1 {                color: white;                background-color: red;            }            p {                color: blue;            }        </style>    </head>    <body>        <h1>Geeksforgeeks</h1>          <p>A computer science portal for geeks</p>      </body></html>
Output:
PHP: PHP stands for Hypertext Preprocessor. PHP is a server-side, scripting language (a script-based program) and is used to develop Web applications. It can be embedded in HTML, and it’s appropriate for the creation of dynamic web pages and database applications. It’s viewed as a benevolent language with capacities to effectively interface with MySQL, Oracle, and different databases. The primary objective of PHP is to allow web developers to create dynamically generated pages rapidly.
Example:
PHP
<?php   // Here echo command is// used to display contentecho "Welcome to GFG!"; ?> 
Output:
Welcome to GFG!

Differences between CSS and PHP :
CSS-Misc
PHP-Misc
CSS
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
JSP - Http Status Codes

In this chapter, we will discuss the Http Status Codes in JSP. The format of the HTTP request and the HTTP response messages are similar and will have the following structure −
An initial status line + CRLF (Carriage Return + Line Feed ie. New Line)
An initial status line + CRLF (Carriage Return + Line Feed ie. New Line)
Zero or more header lines + CRLF
Zero or more header lines + CRLF
A blank line ie. a CRLF
A blank line ie. a CRLF
An optional message body like file, query data or query output.
An optional message body like file, query data or query output.
For example, a server response header looks like the following −
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
   (Blank Line)
<!doctype ...>

<html>
   <head>...</head>
   
   <body>
      ...
   </body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example).
Following table lists out the HTTP status codes and associated messages that might be returned from the Web Server −
Following methods can be used to set the HTTP Status Code in your servlet program. These methods are available with the HttpServletResponse object.
public void setStatus ( int statusCode )
This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.
public void sendRedirect(String url)
This method generates a 302 response along with a Location header giving the URL of the new document.
public void sendError(int code, String message)
This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client.
Following example shows how a 407 error code is sent to the client browser. After this, the browser would show you "Need authentication!!!" message.
<html>
   <head>
      <title>Setting HTTP Status Code</title>
   </head>
   
   <body>
      <%
         // Set error code and reason.
         response.sendError(407, "Need authentication!!!" );
      %>
   </body>
</html>
You will receive the following output −
HTTP Status 407 - Need authentication!!!
type Status report
message Need authentication!!!
description The client must first authenticate itself with the proxy (Need authentication!!!).
Apache Tomcat/5.5.29

type Status report
message Need authentication!!!
description The client must first authenticate itself with the proxy (Need authentication!!!).
To become more comfortable with HTTP status codes, try to set different status codes and their description.

    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Order strings by length of characters IN mYsql?

You can order by length of characters with the help of CHAR_LENGTH() function from MySQL. The function returns the number of characters i.e. 4 for the following string −
AMIT
To order strings by length of characters, the following is the syntax −
select *from yourTableName order by CHAR_LENGTH(yourColumnName);
To understand the above concept, let us first create a table. The following is the query to create a table −
mysql> create table OrderByCharacterLength
   −> (
   −> BookName varchar(200)
   −> );
Query OK, 0 rows affected (1.97 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into OrderByCharacterLength values('Let us C');
Query OK, 1 row affected (0.31 sec)

mysql> insert into OrderByCharacterLength values('Introduction to C');
Query OK, 1 row affected (0.20 sec)

mysql> insert into OrderByCharacterLength values('Data Structure And Algorithm in Java ');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByCharacterLength values('C in Depth');
Query OK, 1 row affected (0.17 sec)

mysql> insert into OrderByCharacterLength values('Java Projects');
Query OK, 1 row affected (0.23 sec)
Let us display all records in a sequence as inserted in the table above. The query is as follows −
mysql> select *from OrderByCharacterLength;
The following is the output −
+---------------------------------------+
| BookName                              |
+---------------------------------------+
| Let us C                              |
| Introduction to C                     |
| Data Structure And Algorithm in Java  |
| C in Depth                            |
| Java Projects                         |
+---------------------------------------+
5 rows in set (0.00 sec)
Here is the query that display all records arranged according to the length of characters. If a column value has minimum length then it gets higher priority and will get displayed first.
The query is as follows −
mysql> select *from OrderByCharacterLength order by CHAR_LENGTH(BookName);
The following is the output −
+---------------------------------------+
| BookName                              |
+---------------------------------------+
| Let us C                              |
| C in Depth                            |
| Java Projects                         |
| Introduction to C                     |
| Data Structure And Algorithm in Java  |
+---------------------------------------+
5 rows in set (0.00 sec)
C++ Ostream Library - put

It is used to inserts character c into the stream.this function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning.
Following is the declaration for std::ostream::put.
ostream& put (char c);
c − Character to write.
It returns the ostream object (*this).
Basic guarantee − if an exception is thrown, the object is in a valid state.
Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio.
In below example explains about std::ostream::put.
#include <iostream>
#include <fstream>

int main () {
   std::ofstream outfile ("test.txt");
   char ch;

   std::cout << "Type some text (type a dot to finish):\n";
   do {
      ch = std::cin.get();
      outfile.put(ch);
   } while (ch!='.');

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Type some text (type a dot to finish):
tutorialspoint.

 Print
 Add Notes
 Bookmark this page
Multidimensional array in Java

Following is a simple example of a multi-dimensional array. 
Live Demo
public class Tester {
   public static void main(String[] args) {
      int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} };
     
      for(int i = 0 ; i < 3 ; i++){
         //row
         for(int j = 0 ; j < 2; j++){
            System.out.print(multidimensionalArray[i][j] + " ");
         }
         System.out.println();
      }
   }
}
1 2
2 3
3 4
How can we run Matplotlib in Tkinter?

Python Matplotlib library is helpful in many applications for visualizing the given data and information in terms of graphs and plots. It is possible to run matplotlib in a Tkinter application. Generally, importing any Python library explicitly in an application gives access to all its functions and modules in the library.
To create a GUI application that uses matplotlib and its functions, we have to import the library using the command from matplotlib.pyplot as plt. However, we also use Tkagg in the backend that uses the Tkinter user interface interactively.
In this example, we have imported Tkagg and matplotlib to visualize the given data points by plotting them inside a canvas widget.
# Import required libraries
from tkinter import *
from tkinter import ttk
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

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

# Set the window size
win.geometry("700x350")

# Use TkAgg
matplotlib.use("TkAgg")

# Create a figure of specific size
figure = Figure(figsize=(3, 3), dpi=100)

# Define the points for plotting the figure
plot = figure.add_subplot(1, 1, 1)
plot.plot(0.5, 0.3, color="blue", marker="o", linestyle="")

# Define Data points for x and y axis
x = [0.2,0.5,0.8,1.0 ]
y = [ 1.0, 1.2, 1.3,1.4]
plot.plot(x, y, color="red", marker="x", linestyle="")

# Add a canvas widget to associate the figure with canvas
canvas = FigureCanvasTkAgg(figure, win)
canvas.get_tk_widget().grid(row=0, column=0)

win.mainloop()
When we run the above code, a plot will appear in the window with some data points on the X and Y axis.
Add multiple number input fields with JOptionPane and display the sum in Console with Java

At first, set multiple number input fields −
JTextField text1 = new JTextField(10);
JTextField text2 = new JTextField(10);
JTextField text3 = new JTextField(10);
JTextField text4 = new JTextField(10);
JTextField text5 = new JTextField(10);
JTextField text6 = new JTextField(10);
JTextField text7 = new JTextField(10);
JTextField text8 = new JTextField(10);
panel.add(text1);
panel.add(text2);
panel.add(text3);
panel.add(text4);
panel.add(text5);
panel.add(text6);
panel.add(text7);
panel.add(text8);
Now, let us add the values of the multiple number input fields created above −
System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +
   Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+
   Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+
   Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));
Above, we have displayed the sum in the Console.
The following is an example to sum multiple number input fields with JOptionPane −
package my;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new GridLayout(5, 3));
      JTextField text1 = new JTextField(10);
      JTextField text2 = new JTextField(10);
      JTextField text3 = new JTextField(10);
      JTextField text4 = new JTextField(10);
      JTextField text5 = new JTextField(10);
      JTextField text6 = new JTextField(10);
      JTextField text7 = new JTextField(10);
      JTextField text8 = new JTextField(10);
      panel.add(text1);
      panel.add(text2);
      panel.add(text3);
      panel.add(text4);
      panel.add(text5);
      panel.add(text6);
      panel.add(text7);
      panel.add(text8);
      JOptionPane.showMessageDialog(null, panel);
      System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +
         Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+
         Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+
         Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));
   }
}
Now, enter the numbers in the TextField and click OK −
On pressing OK above, the result would be visible in the Console that is sum of all the numbers added above −
Remove default list-style in Bootstrap

To remove the list styles in Bootstrap, use the .list-unstyled class.
You can try to run the following code to implement the .list-unstyled class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Technologies</h2>
         <ul class = "list-inline">
            <li><a href = "#">Home</a></li>
            <li><a href = "#">PHP</a></li>
            <li><a href = "#">Java</a></li>
            <li><a href = "#">jQuery</a></li>
            <li><a href = "#">JavaScript</a></li>
            <li><a href = "#">Ruby</a></li>
         </ul>
      </div>
      <div class = "container">
         <h2>Technologies (Unstyled)</h2>
         <ul class = "list-unstyled">
            <li><a href = "#">Home</a></li>
            <li><a href = "#">PHP</a></li>
            <li><a href = "#">Java</a></li>
            <li><a href = "#">jQuery</a></li>
            <li><a href = "#">JavaScript</a></li>
            <li><a href = "#">Ruby</a></li>
         </ul>
      </div>
   </body>
</html>
How to clear a Tkinter ListBox?

To create a list of items with a scrollable widget, Tkinter provides the Listbox widget. With the Listbox widget, we can create a list that contains items called List items. Depending upon the configuration, the user can select one or multiple items from the list.
If we want to clear the items in the Listbox widget, we can use the delete(0, END) method. Besides deleting all the items in the Listbox, we can delete a single item as well by selecting an item from the Listbox, i.e., by using currselection() method to select an item and delete it using the delete() function.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x250")

# Create a Listbox widget
lb=Listbox(win, width=100, height=5, font=('TkMenuFont, 20'))
lb.pack()

# Once the list item is deleted, we can insert a new item in the listbox
def delete():
   lb.delete(0,END)
   Label(win, text="Nothing Found Here!",
      font=('TkheadingFont, 20')).pack()

# Add items in the Listbox
lb.insert("end","item1","item2","item3","item4","item5")

# Add a Button to Edit and Delete the Listbox Item
ttk.Button(win, text="Delete", command=delete).pack()

win.mainloop()
If we run the above code, it will display a list of items in the list box and a button to clear the Listbox.
Now, click the "Delete" button to clear the Listbox widget.
Bootstrap 4 card styled with bg-secondary class

Add less important stuff, using the card class with the bg-secondary contextual class in Bootstrap.
This class adds a gray background −
<div class="card bg-secondary text-white">
Inside that, add the card body −
<div class="card bg-secondary text-white">
  <div class="card-body">English</div>
</div>
You can try to run the following code to implement the card class with bg-secondary class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h3>Languages</h3>
    <div class="card bg-secondary text-white">
      <div class="card-body">English</div>
    </div><br>
    <div class="card bg-secondary text-white">
      <div class="card-body">French</div>
    </div><br>
    <div class="card bg-secondary text-white">
      <div class="card-body">Chinese</div>
    </div><br>
    <div class="card bg-secondary text-white">
       <div class="card-body">Russian</div>
    </div>
  </div>

</body>
</html>
How do I open Chrome in selenium WebDriver?

We can open Chrome browser in Selenium webdriver. We can launch Chrome by instantiating an object of the ChromeDriver class with the help of the below statement.
WebDriver driver = new ChromeDriver();
Next we have to download the chromedriver and configure it to our project by following the below step by step processes −
Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that.
Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that.
As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present.
As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present.
After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location.
After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location.
Let us discuss how to configure chromedriver with System properties within the Selenium code −
Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters.
Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters.
System.setProperty("webdriver.chrome.driver","<chromedriver path>");
Code Implementation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeBrw{
   public static void main(String[] args) {
      // creating object of ChromeDriver
      WebDriver driver = new ChromeDriver();
      // to configure the path of the chromedriver.exe
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
   }
}
Splunk - Lookups

In the result of a search query, we sometimes get values which may not clearly convey the meaning of the field. For example, we may get a field which lists the value of product id as a numeric result. These numbers will not give us any idea of what kind of product it is. But if we list the product name along with the product id, that gives us a good report where we understand the meaning of the search result.
Such linking of values of one field to a field with same name in another dataset using equal values from both the data sets is called a lookup process. The advantage is, we retrieve the related values from two different data sets.
In order to successfully create a lookup field in a dataset, we need to follow the below steps −
We consider the dataset with host as web_application, and look at the productid field. This field is just a number, but we want product names to be reflected in our query result set. We create a lookup file with the following details. Here, we have kept the name of the first field as productid which is same as the field we are going to use from the dataset.
productId,productdescription
WC-SH-G04,Tablets
DB-SG-G01,PCs
DC-SG-G02,MobilePhones
SC-MG-G10,Wearables 
WSC-MG-G10,Usb Light
GT-SC-G01,Battery
SF-BVS-G01,Hard Drive
Next, we add the lookup file to Splunk environment by using the Settings screens as shown below −
After selecting the Lookups, we are presented with a screen to create and configure lookup. We select lookup table files as shown below.
We browse to select the file productidvals.csv as our lookup file to be uploaded and select search as our destination app. We also keep the same destination file name.
On clicking the save button, the file gets saved to the Splunk repository as a lookup file.
For a search query to be able to lookup values from the Lookup file we just uploaded above, we need to create a lookup definition. We do this by again going to Settings → Lookups → Lookup Definition → Add New .
Next, we check the availability of the lookup definition we added by going to Settings → Lookups → Lookup Definition .
Next, we need to select the lookup field for our search query. This is done my going to  New search → All Fields . Then check the box for productid which will automatically add the productdescription field from the lookup file also.
Now we use the Lookup field in the search query as shown below. The visualization shows the result with productdescription field instead of productid.
 Print
 Add Notes
 Bookmark this page
Minimum Number of Platforms Problem

A list of arrival and departure time is given. Now the problem is to find the minimum number of platforms are required for the railway as no train waits.
By sorting all timings in sorted order, we can find the solution easily, it will be easy to track when the train has arrived but not left the station.
The time complexity of this problem is O(n Log n).
Input:
Lists of arrival time and departure time.
Arrival: {900, 940, 950, 1100, 1500, 1800}
Departure: {910, 1200, 1120, 1130, 1900, 2000}
Output:
Minimum Number of Platforms Required: 3
minPlatform(arrival, departure, int n)
Input − The list of arrival time and the departure times, and the number of items in the list
Output − The number of minimum platforms is needed to solve the problem.
Begin
   sort arrival time list, and departure time list
   platform := 1 and minPlatform := 1
   i := 1 and j := 0

   for elements in arrival list ‘i’ and departure list ‘j’ do
      if arrival[i] < departure[j] then
         platform := platform + 1
         i := i+1
         if platform > minPlatform then
            minPlatform := platform
      else
         platform := platform – 1
         j := j + 1
   done
   return minPlatform
End
#include<iostream>
#include<algorithm>
using namespace std;

int minPlatform(int arrival[], int departure[], int n) {
   sort(arrival, arrival+n);     //sort arrival and departure times
   sort(departure, departure+n);

   int platform = 1, minPlatform = 1;
   int i = 1, j = 0;

   while (i < n && j < n) {
      if (arrival[i] < departure[j]) {
         platform++;     //platform added
         i++;
         if (platform > minPlatform)    //if platform value is greater, update minPlatform
            minPlatform = platform;
      } else {
         platform--;      //delete platform
         j++;
      }
   }
   return minPlatform;
}

int main() {
   int arrival[] = {900, 940, 950, 1100, 1500, 1800};
   int departure[] = {910, 1200, 1120, 1130, 1900, 2000};
   int n = 6;
   cout << "Minimum Number of Platforms Required: " << minPlatform(arrival, departure, n);
}
Minimum Number of Platforms Required: 3
How I can create Python class from JSON object?

We can use python-jsonschema-objects which is built on top of jsonschema.The python-jsonschema-objects provide an automatic class-based binding to JSON schemas for use in Python.
We have a sample json schema as follows
schema = '''{     "title": "Example Schema",     "type": "object",     "properties": {         "firstName": {             "type": "string"         },         "lastName": {             "type": "string"         },         "age": {             "description": "Age in years",             "type": "integer",             "minimum": 0         },         "dogs": {             "type": "array",             "items": {"type": "string"},             "maxItems": 4         },         "gender": {             "type": "string",             "enum": ["male", "female"]         },         "deceased": {             "enum": ["yes", "no", 1, 0, "true", "false"]             }     },     "required": ["firstName", "lastName"] } '''
Converting the schema object to class
 import python_jsonschema_objects as pjs  
 builder = pjs.ObjectBuilder(schema)  
 ns = builder.build_classes()  
 Person = ns.ExampleSchema  
 jack = Person(firstName="Jack", lastName="Sparrow")  
 jack.lastName    
 example_schema lastName=Sparrow age=None firstName=Jack 
Validation −
jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
Check If the Rune is a Space Character or not in Golang - GeeksforGeeks

27 Sep, 2019
Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a space character or not defined by the Unicode’s White Space property, with the help of IsSymbol() function. This function returns true if the given rune is a space character, or return false if the given rune is not a space character. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program.
Syntax:
func IsSpace(r rune) bool
The return type of this function is boolean. Let us discuss this concept with the help of given examples:
Example 1:
// Go program to illustrate how to check// the given rune is a space character// or notpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating rune    rune_1 := 'g'    rune_2 := 'e'    rune_3 := '\t'    rune_4 := '\n'    rune_5 := 'S'      // Checking the given rune is    // a space character or not    // Using IsSpace () function    res_1 := unicode.IsSpace(rune_1)    res_2 := unicode.IsSpace(rune_2)    res_3 := unicode.IsSpace(rune_3)    res_4 := unicode.IsSpace(rune_4)    res_5 := unicode.IsSpace(rune_5)      // Displaying results    fmt.Println(res_1)    fmt.Println(res_2)    fmt.Println(res_3)    fmt.Println(res_4)    fmt.Println(res_5)  }
Output:
false
false
true
true
false

Example 2:
// Go program to illustrate how to check// the given rune is a space character// or notpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating a slice of rune    val := []rune{'g', '\f', '\v', '&', ' '}      // Checking the given rune is    // a space character or not    // Using IsSpace () function    for i := 0; i < len(val); i++ {          if unicode.IsSpace(val[i]) == true {              fmt.Println("It is a space character")                      } else {                      fmt.Println("It is not a space character")        }    }}
Output:
It is not a space character
It is a space character
It is a space character
It is not a space character
It is a space character

Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Check if the String ends with specified suffix in Golang
Rune in Golang
Anonymous function in Go Language
How to Parse JSON in Golang?
Class and Object in Golang
Loops in Go Language
Methods in Golang
Structures in Golang
Golang program that uses structs as map keys
fmt.print() Function in Golang With Examples
Basic calculator program using Python program

In this tutorial, we are going to build a basic calculator in Python. I think all of you have an idea about the basic calculators. We will give six options to the user from which they select one option, and we will perform the respective operation. Following are the arithmetic operations we
are going to perform.
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Try to implement it's on your own. Follow the below steps to write code for a simple calculator.
1. Initialise the two numbers.
2. Ask the user to enter an option by giving six options.
3. After getting the option from the user write if conditions for every operation based on the option.
4. Perform the respective operation.
5. Print the result.
Let's write the code.
## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")
If you run the above program, you will get the following output.
1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 3
Multiplication: 30
Let's execute the program once again
## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")
If you run the above program, you will get the following output.
1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 6
Modulo: 1
If you have any doubts regarding the tutorial, mention them in the comment section.
Java Program to generate n distinct random numbers

For distinct numbers, use Set, since all its implementations remove duplicates −
Set<Integer>set = new LinkedHashSet<Integer>();
Now, create a Random class object −
Random randNum = new Random();
Generate 10 distinct random numbers now with nextInt of the Random class −
while (set.size() < 10) {
   set.add(randNum.nextInt(10)+1);
}
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
public class Demo {
   public static void main(final String[] args) throws Exception {
      Random randNum = new Random();
      Set<Integer>set = new LinkedHashSet<Integer>();
      while (set.size() < 10) {
         set.add(randNum.nextInt(10)+1);
      }
      System.out.println("Distinct random numbers = "+set);
   }
}
Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]
How to Calculate Mean in Excel?

28 Jul, 2021
The mean (also called average) of the data set is calculated by adding all the numbers in the data set and then dividing it by the total number of values in the data set. In this article, we will find out how to calculate the mean in excel.
In this method, we are going to use the AVERAGE function which returns the mean of the arguments. For example, the =AVERAGE(A1:A10) returns the average of the numbers in the range of A1 to A10.
Syntax:
AVERAGE(number1,[number2],...)
Here,
number1 (Required): The first cell reference or number for which you want the average
number2 (optional): Additional cell references or numbers for which you want the average. The maximum limit is 255.
Notes:
arguments can either be numbers or names, ranges, or cell references that contain numbers.
If the argument contains text or logical values or empty cells then those values are ignored. However, if the cell contains the value zero then it is included.
if the argument contains error values or text that cannot be translated to numbers then it will cause errors.
AVERAGE: This function returns the average of cells with any data (logical values or text representation of numbers)
AVERAGEIF: This function is used to calculate the average of only the values that meet a single criterion.
AVERAGEIFS: This function is used to calculate the average based on multiple criteria.
Example:
Let us apply the above formula on some rough data as shown below:
In the above example, we have used 4 different functions.
=AVERAGE(c4:e12): Returns the average of the numbers in cells c4 to e12
=AVERAGE(c4:f6,6): Returns the average of the numbers in cells c4 to f6 and the number 6.
=AVERAGE(b4:b12, “sara”, c4:c12): Returns the average of the numbers in cells c4 to c12 by matching the name “sara” in the range b4 to b12.
=AVERAGE(d4:d12,b4:b12,”sara”,g4:g12,”b”): Returns the average of numbers from cells d4 to d12 by matching two conditions i.e., name “sara” in range b4 to b12 and grade “b” in range g4 to g12.
In this method first, you need to select the cells for which you have to calculate the average. Then select the INSERT function from the formulas tab, a dialog box will appear.
Select the AVERAGE function from the dialog and enter the cell range for your list of numbers in the number1 box. For example, if you need values from column A and from row 1 to row 10 then simply enter A1:A10. You can also simply drag and drop the selected cells and click OK. The result will be shown in the cell you have selected.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Create a Macro in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
SQL Server | STUFF() Function

09 Jul, 2021
There are situations when user want to change some portion of the data inserted. The reason may be because of human error or the change in data. For this purpose, stuff() function comes to action. 
STUFF() : In SQL Server, stuff() function is used to delete a sequence of given length of characters from the source string and inserting the given sequence of characters from the specified starting index. 
Syntax: 
STUFF (source_string, start, length, add_string)
Where:- 1. source_string: Original string to be modified. 2. start: The starting index from where the given length of characters will be deleted and new sequence of characters will be inserted. 3. length: The numbers of characters to be deleted from the starting index in the original string. 4. add_string: The new set of characters (string) to be inserted in place of deleted characters from the starting index. 
Note: It is not necessary to have the length of the new string and number of characters to be deleted the same. 
Example 1: 
Output:  
Example 2:  
Output:  
Example 3:  
Output:  
 
abhishek0719kadiyan
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
How to easily initialize a list of Tuples in C#?

Tuple can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it.
The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types.
Tuple<int, string, string> person =
new Tuple <int, string, string>(1, "Test", "Test1");
A tuple can only include a maximum of eight elements. It gives a compiler error when you try to include more than eight elements.
var tupleList = new List<(int, string)>
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};
var tupleArray = new(int, string)[]
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};
var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13));
Tuple as a Method Parameter
static void DisplayTuple(Tuple<int,string,string> person)
{
}
static Tuple<int, string, string> GetTest()
{
   return Tuple.Create(1, "Test1", "Test2");
}
Perl | Subroutines or Functions

13 Jul, 2018
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in some programming languages, these are considered different. The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier. One can avoid using the return statement.
Defining Subroutines: The general form of defining the subroutine in Perl is as follows-
sub subroutine_name
{
    # body of method or subroutine
}

Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows-
subroutine_name(aruguments_list);
The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because it bypasses the subroutine prototypes.
&subroutine_name(aruguments_list);
Example:
# Perl Program to demonstrate the # subroutine declaration and calling  #!/usr/bin/perl  # defining subroutinesub ask_user {   print "Hello Geeks!\n";}  # calling subroutine# you can also use# &ask_user();ask_user();
Output:
Hello Geeks!
Passing parameters to subroutines: This is used to pass the values as arguments.This is done using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so on.
Example:
# Perl Program to demonstrate the # Passing parameters to subroutines  #!/usr/bin/perl  # defining subroutinesub area {    # passing argument        $side = $_[0];          return ($side * $side);}  # calling function$totalArea = area(4);  # displaying resultprintf $totalArea;
Output:
16
Advantage of using subroutines:
It helps us to reuse the code and makes the process of finding error and debug easy.
It helps in organizing the code in structural format.Chunks of code is organized in sectional format.
It increases the code readability.
Perl-method
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 1996 | Question 39

01 Nov, 2017
A binary search tree is generated by inserting in order the following integers:
 50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24 
The number of nodes in the left subtree and right subtree of the root respectively is(A) (4, 7)(B) (7, 4)(C) (8, 3)(D) (3, 8)Answer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
matplotlib.pyplot.viridis() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The viridis() function in pyplot module of matplotlib library is used to set the colormap to “viridis”.
Syntax:
matplotlib.pyplot.viridis()
Parameters: This method does not accepts any parameter.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.viridis() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np     ang = 32rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad)     angles = np.linspace(0, 1.4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang     x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten()     triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                         < radm)     tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example',                                       fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm        dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y)     extent = np.min(x), np.max(x), np.min(y), np.max(y)          Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest',                               extent = extent, alpha = 1)     def geeks(x, y):    return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))     Z2 = geeks(X, Y)     plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear',                                      extent = extent)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example',                                      fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts