code-rag-bench/online-tutorials huggingface dataset:
HTML | DOM Select multiple Property - GeeksforGeeks

14 Dec, 2021
The Select multiple property in HTML DOM is used to set or return whether more than one option can be selected from a drop-down list or not. It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Syntax:  
It returns the select multiple property.  
selectObject.multiple
It is used to set select multiple property.  
selectObject.multiple = true|false
Property Values: It contains two values either true or false which is used to specify whether multiple selection in the drop-down list is enabled or not. It is false by default.
Return Values: It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Below program illustrates the Select multiple property in HTML DOM:Example: This example uses Select multiple property to allow multiple selection in a drop-down list.  
html
<!DOCTYPE html><html>      <head>     <title>        HTML DOM Select multiple Property    </title> </head>  <body style="text-align:center;">      <h1 style="color:green;">        GeeksforGeeks    </h1>           <h2 style="font-family: Impact;">        Select multiple Property    </h2><br>          Select your preferred course from the drop-down list:<br>          <select id="myCourses" size="4">        <option value="C++">c++</option>        <option value="Placement">Placement</option>        <option value="Java">Java</option>        <option value="Python">Python</option>    </select>            <p>        To enable multiple selection, double-click the        "Enable Multiple Selection" button.    </p>            <button ondblclick="myGeeks()">        Enable Multiple Selection    </button>          <p id="GFG"></p>            <script>        function myGeeks() {            document.getElementById("myCourses").multiple                    = true;            document.getElementById("GFG").innerHTML                     = "Multiple options can be selected now"                    + " from the drop down list.";        }    </script></body>  </html>                                                    
Output: Before Clicking the button:  
After Clicking the button:  
Supported Browsers: The browser supported by DOM Select multiple Property are listed below:  
Apple Safari
Internet Explorer
Firefox
Google Chrome
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
chhabradhanvi
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
Express.js express.Router() Function
Installation of Node.js on Linux
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
C++ Program to Check Armstrong Number

An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number. Some examples of Armstrong numbers are as follows.
3 = 3^1
153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371
407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407
A program that checks whether a number is an Armstrong number or not is as follows.
 Live Demo
#include <iostream>
#include <cmath<
using namespace std;
int main() {
   int num = 153, digitSum, temp, remainderNum, digitNum ;
   temp = num;
   digitNum = 0;
   while (temp != 0) {
      digitNum++;
      temp = temp/10;
   }
   temp = num;
   digitSum = 0;
   while (temp != 0) {
      remainderNum = temp%10;
      digitSum = digitSum + pow(remainderNum, digitNum);
      temp = temp/10;
   }
   if (num == digitSum)
   cout<<num<<" is an Armstrong number";
   else
   cout<<num<<" is not an Armstrong number";
   return 0;
}
153 is an Armstrong number
In the above program, it is determined if the given number is an Armstrong number or not. This is done using multiple steps. First the number of digits in the number are found. This is done by adding one to digitNum for each digit.
This is demonstrated by the following code snippet −
temp = num;
digitNum = 0;
while (temp != 0) {
   digitNum++;
   temp = temp/10;
}
After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits. This can be seen in the following code snippet.
temp = num;
digitSum = 0;
while (temp != 0) {
   remainderNum = temp%10;
   digitSum = digitSum + pow(remainderNum, digitNum);
   temp = temp/10;
}
If the number is equal to the digitSum, then that number is an Armstrong number and that is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet.
if (num == digitSum)
cout<<num<<" is an Armstrong number";
else
cout<<num<<" is not an Armstrong number";
MATLAB - Trapezoidal numerical integration without using trapz - GeeksforGeeks

04 Jul, 2021
Trapezoidal rule is utilized to discover the approximation of a definite integral. The main idea in the Trapezoidal rule is to accept the region under the graph of the given function to be a trapezoid rather than a rectangle shape and calculate its region.
The formula for numerical integration using trapezoidal rule is:
where h = (b-a)/n
Now we take an example for calculating the area under the curve using 10 subintervals.
Example:
Matlab
% MATLAB program for calculate the % area under the curve ∫_0^11/(1+x^2) dx % using 10 subintervals specify the variable% x as symbolic ones The syms function creates % a variable dynamically and automatically assigns% to a MATLAB variable with the same namesyms x  % Lower Limita=0;    % Upper Limitb=1;     % Number of segmentsn=10;   % Declare the functionf1=1/(1+x^2);  % inline creates a function of% string containing in f1f=inline(f1);   % h is the segment sizeh=(b - a)/n;  % X stores the summation of first% and last segmentX=f(a)+f(b);  % variable R stores the summation of% all the terms from 1 to n-1R=0;for i = 1:1:n-1    xi=a+(i*h);    R=R+f(xi);end  % Formula to calculate numerical integration% using Trapezoidal RuleI=(h/2)*(X+2*R);  % Display the outputdisp('Area under the curve 1/(1+x^2) = ');disp(I);
Output:
Let’s take another example for calculating the area under the curve  using 4 subintervals.
Example:
Matlab
% MATLAB program for calculate% the area under the curve∫_0^1x^2 dx    % using 4 subintervals.% specify the variable x as symbolic ones  syms x  % Lower Limita=0;   % Upper Limitb=1;   % Number of segmentsn=4;    % Declare the functionf1=x^2;  % inline creates a function of% string containing in f1f=inline(f1);   % h is the segment sizeh=(b - a)/n;X=f(a)+f(b);  % variable R stores the summation % of all the terms from 1 to n-1R=0;for i = 1:1:n-1    xi=a+(i*h);    R=R+f(xi);end  % Formula to calculate numerical% integration using Trapezoidal RuleI=(h/2)*(X+2*R);  % Display the outputdisp('Area under the curve x^2 = ');disp(I);
Output:
MATLAB-Maths
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Double Integral in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
What are different types of denoising filters in MATLAB?
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Python - Install Paramiko on Windows and Linux - GeeksforGeeks

28 Jan, 2022
The high-level python API starts with the creation of a secure connection object. To have more direct control and pass a socket to transport to start remote access. As a client, it’s authenticating using a user credential or private key, and checking the server’s host key. 
Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement of SSL to make a secure connection between two devices. It also supports the SFTP client and server model.
To install Paramiko on Windows using pip run bellow command on cmd.
pip install paramiko
Output:
To check the installed paramiko run the following:
pip list
Output:
Install paramiko using .whl file offline. To download .whl file https://pypi.org/project/paramiko/#files
pip install paramiko-2.7.2-py2.py3-none-any.whl
Output :
Python paramiko can be installed on Linux in many ways, using pip is one of them.
pip install paramiko
Output :
To check the installed paramiko:
pip list --format=json
Output:
saurabh1990aror
how-to-install
python-modules
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install and Run Apache Kafka on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Taking input in Python
Automata Theory | Set 5 - GeeksforGeeks

27 Mar, 2017
Following questions have been asked in GATE CS 2009 exam.
1) S –> aSa| bSb| a| b ;The language generated by the above grammar over the alphabet {a,b} is the set of(A) All palindromes.(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromes.
Answer (B)The strings accepted by language are {a, b, aaa, bbb, aba, bab, ..}. All of these strings are odd length palindromes.
2) Which one of the following languages over the alphabet {0,1} is described by the regular expression: (0+1)*0(0+1)*0(0+1)*?(A) The set of all strings containing the substring 00.(B) The set of all strings containing at most two 0’s.(C) The set of all strings containing at least two 0’s.(D) The set of all strings that begin and end with either 0 or 1.
Answer (C)The regular expression has two 0’s surrounded by (0+1)* which means accepted strings must have at least 2 0’s.
3) Which one of the following is FALSE?(A) There is unique minimal DFA for every regular language(B) Every NFA can be converted to an equivalent PDA.(C) Complement of every context-free language is recursive.(D) Every nondeterministic PDA can be converted to an equivalent deterministic PDA.
Answer (D)Deterministic PDA cannot handle languages or grammars with ambiguity, but NDPDA can handle languages with ambiguity and any context-free grammar. So every nondeterministic PDA can not be converted to an equivalent deterministic PDA.
4) Match all items in Group 1 with correct options from those given in Group 2.
Group 1                          Group 2
P. Regular expression        1. Syntax analysis
Q. Pushdown automata         2. Code generation
R. Dataflow analysis         3. Lexical analysis
S. Register allocation       4. Code optimization
(A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3
Answer (B)
5) . Let L = L1 ∩ L2, where L1 and L2 are languages as defined below:L1 = {ambmcanbn | m, n >= 0 }L2 = {aibjck | i, j, k >= 0 }Then L is(A) Not recursive(B) Regular(C) Context free but not regular(D) Recursively enumerable but not context free.
Answer (C)The language L1 accept strings {c, abc, abcab, aabbcab, aabbcaabb, ...} and L2 accept strings {a, b, c, ab, abc, aabc, aabbc, ... }. Intersection of these two languages is L1 ∩L2 = {akbkc | k >= 0} which is context free, but not regular.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
AT
GATE-CS-2009
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Data Structures and Algorithms | Set 25
Operating Systems | Set 1
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 2
Computer Networks | Set 1
Difference between Pipes and Message Queues - GeeksforGeeks

16 Mar, 2020
Pipes:Unix system uses pipes, to establish inter process communication. A pipe provides an unidirectional flow of data. A pipe is created using the pipe() function.
Syntax:
#include int pipe(int fd);  
A pipe ()function returns two file descriptors, fd[O] and fd[1]. The fd[0] is open for reading from and fd[1] is open for writing to the pipe. The data flows from one end of the pipe to the other end. The pipe function returns ‘0’ on success or -1 on error.
Message Queues:A Message Queues, allow one or more processes to write message to be read by other processes. A message queue is implemented as a linked list of messages, and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system.
Difference between Pipes and Message Queues:
system-programming
Difference Between
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Get the index of minimum value in DataFrame column - GeeksforGeeks

18 Dec, 2018
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns).
Let’s see how can we get the index of minimum value in DataFrame column.
Observe this dataset first. We’ll use ‘Weight’ and ‘Salary’ columns of this data in order to get the index of minimum values from a particular column in Pandas DataFrame.
# importing pandas module import pandas as pd     # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   df.head(10)
Code #1: Check the index at which minimum weight value is present.
# importing pandas module import pandas as pd     # making data frame df = pd.read_csv("nba.csv")  # Returns index of minimum weightdf[['Weight']].idxmin()
Output:
We can verify whether the minimum value is present in index or not.
     # importing pandas module import pandas as pd     # making data frame df = pd.read_csv("nba.csv")  # from index 140 to 154df.iloc[140:155]
Output:
 Code #2: Let’s insert a new row at index 0, having minimum salary and then print the minimum salary.
# importing pandas module import pandas as pd      # making data frame df = pd.read_csv("nba.csv")   new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3,                        'Position':'PG', 'Age':33, 'Height':'6-2',                        'Weight':189, 'College':'MIT', 'Salary':99}                         , index=[0])   df = pd.concat([new_row, df]).reset_index(drop=True)df.head(5)
Output:
Now, let’s check if the minimum salary is present at index 0 or not.
# Returns index of minimum salarydf[['Salary']].idxmin()
Output:
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
How to implement an instance method reference using a class name in Java?

Method reference is a simplified form of the lambda expression. It can specify a class name or instance name followed by the method name. The "::" symbol can separate a method name from the name of an object or class.
An instance method reference refers to an instance method of any class. In the below example, we can implement an instance methods reference using the class name.
<Class-Name>::<Instance-Method-Name>
import java.util.*;;
import java.util.function.*;

public class ClassNameRefInstanceMethodTest {
   public static void main(String args[]) {
      List<Employee> empList = Arrays.asList(
         new Employee("Raja", 15000),
         new Employee("Adithya", 12000),
         new Employee("Jai", 9000),
         new Employee("Ravi", 19000),
         new Employee("Surya", 8500),
         new Employee("Chaitanya", 7500),
         new Employee("Vamsi", 14000)
      );
      Function<Employee, String> getEmployeeNameFunction = new Function<Employee, String>() {
         @Override
         public String apply(Employee e) {
            return e.getName();
         }
      };
      System.out.println("The list of employees whose salary greater than 10000:");
      empList.stream()
      .filter(e -> e.getSalary() > 10000)
      .map(Employee::getName)  // instance method reference "getName" using class name "Employee"
      .forEach(e -> System.out.println(e));
   }
}

// Employee class
class Employee {
   private String name;
   private int salary;
   public Employee(String name, int salary){
      this.name = name;
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public int getSalary() {
      return salary;
   }
}
The list of employees whose salary greater than 10000:
Raja
Adithya
Ravi
Vamsi
Retrieve data from a MongoDB collection?

To return a single document from a collection, use findOne() in MongoDB. Let us create a collection with documents −
> db.demo463.insertOne({"StudentName":"Chris
Brown","StudentAge":21,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ec8cb66ccba22cc9dcf")
}
> db.demo463.insertOne({"StudentName":"David
Miller","StudentAge":23,"StudentCountryName":"UK"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ed5cb66ccba22cc9dd0")
}
> db.demo463.insertOne({"StudentName":"John
Doe","StudentAge":22,"StudentCountryName":"AUS"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ee1cb66ccba22cc9dd1")
}
> db.demo463.insertOne({"StudentName":"John
Smith","StudentAge":24,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7eefcb66ccba22cc9dd2")
}
Display all documents from a collection with the help of find() method −
> db.demo463.find();
This will produce the following output −
{ "_id" : ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName" : "Chris Brown",
"StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName" : "David Miller",
"StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" :
22, "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName" : "John Smith", "StudentAge"
: 24, "StudentCountryName" : "US" }
Following is the query to retrieve data from MongoDB −
> db.demo463.findOne({"StudentName":"John Doe"});
This will produce the following output −
{
   "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
   "StudentName" : "John Doe",
   "StudentAge" : 22,
   "StudentCountryName" : "AUS"
}
Distribute Candies in C++

Suppose we have an array with even length, here different numbers in this array will represent different kinds of candies. Now each number means one candy of the corresponding kind. we have to distribute candies equally in number to brother and sister. We have to find the maximum number of kinds of candies the sister could receive.
So, if the input is like [1,1,2,3], then the output will be 2 as if we consider the sister has candies [2,3] and the brother has candies [1,1]. Now the sister has two different kinds of candies, the brother has only one kind of candies.
To solve this, we will follow these steps −
Define one set s
Define one set s
for initialize i := 0, when i < size of candies, update (increase i by 1), do −insert candies[i] into s
for initialize i := 0, when i < size of candies, update (increase i by 1), do −
insert candies[i] into s
insert candies[i] into s
return a minimum of size of s and size of candies / 2
return a minimum of size of s and size of candies / 2
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int distributeCandies(vector<int>& candies){
      unordered_set<int> s;
      for (int i = 0; i < candies.size(); i++)
         s.insert(candies[i]);
      return min(s.size(), candies.size() / 2);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,2,3};
   cout << (ob.distributeCandies(v));
}
{1,1,2,3}
2
Sort an array of strings lexicographically based on prefix

31 Aug, 2021
Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order.
Examples:
Input: arr[] = {“sun”, “moon”, “mock”} Output: mock moon sun Explanation: The lexicographical sorting is mock, moon, and sun.
Input: arr[] = {“geeks”, “geeksfor”, “geeksforgeeks”} Output: geeksforgeeks geeksfor geeks  
Approach: The idea is to sort the given array of strings using the inbuilt sort function using the below comparator function. The comparator function used to check if any string occurs as a substring in another string using compare() function in C++ then, it should arrange them in decreasing order of their length.
C++
bool my_compare(string a, string b){    // If any string is a substring then    // return the size with greater length    if (a.compare(0, b.size(), b) == 0        || b.compare(0, a.size(), a) == 0)        return a.size() & gt;    b.size();     // Else return lexicographically    // smallest string    else return a & lt;    b;}
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the vectorvoid Print(vector<string> v){    for (auto i : v)        cout << i << endl;} // Comparator function to sort the// array of string wrt given conditionsbool my_compare(string a, string b){    // Check if a string is present as    // prefix in another string, then    // compare the size of the string    // and return the larger size    if (a.compare(0, b.size(), b) == 0        || b.compare(0, a.size(), a) == 0)         return a.size() > b.size();     // Else return lexicographically    // smallest string    else        return a < b;} // Driver Codeint main(){    // GIven vector of strings    vector<string> v = { "batman", "bat", "apple" };     // Calling Sort STL with my_compare    // function passed as third parameter    sort(v.begin(), v.end(), my_compare);     // Function call to print the vector    Print(v);    return 0;}
apple
batman
bat
 
Time Complexity: O(N*log N)Auxiliary Space: O(1)
 
shashanksdev
lexicographic-ordering
prefix
Arrays
Sorting
Strings
Arrays
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set state with a dynamic key name in ReactJS ?

27 Oct, 2021
React.js introduces the concept of state. The states are used to store data for specific components. These states can be updated accordingly using setState function. Updation of state leads to rerendering of UI. You can assign meaningful names to states. There can be a requirement to create a state with a dynamic key name. We can do this in React. 
Let us create a React project and then we will create a state with a dynamic key name. 
Creating React Project:
Step 1: Create a react application by typing the following command in the terminal.
npx create-react-app project_name
 
Step 2: Now, go to the project folder i.e project_name by running the following command.
cd project_name
Project Structure: It will look like the following:
Project Structure
Example: Let us create an input field that takes the state name as input and state value as another input. Now a button is added which has an onclick function. It creates the state with a dynamic key name enclosing value inside this ‘[ ]’ on a user click.  Users can click on the button to create a new state and it will display the newly created state in the UI. 
Filename: App.js
Javascript
import React, { Component } from "react";  class App extends Component {  constructor() {    super();    this.state = {      name: "",      value: " ",    };  }    render() {    return (      <div>        <p>Enter State Name:</p>        <input          onChange={(e) => {            this.setState({ name: e.target.value });          }}          type="text"        ></input>        <p>Enter State Value:</p>        <input          onChange={(e) => {            this.setState({ value: e.target.value });          }}          type="text"        ></input>        <br />        <br />        <button          onClick={() => {            this.setState({              [this.state.name]: this.state.value,            });          }}        >          Create a dynamic state        </button>        {this.state[this.state.name] ? (          <p>            {this.state.name}:{this.state[this.state.name]}          </p>        ) : null}      </div>    );  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.UI checks if the state exists and then displays the value.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | date_diff() Function

12 Feb, 2019
The date_diff() is an inbuilt function in PHP which is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
Syntax:
date_diff($datetime1, $datetime2);

Parameters: The date_diff() function accepts two parameters as mentioned above and described below:
$datetime1: It is a mandatory parameter which specifies the first DateTime object.
$datetime2: It is a mandatory parameter which specifies the second DateTime object.
Return Value: It returns the difference between two DateTime objects otherwise, FALSE on failure.
Below programs illustrate the date_diff() function:Program 1:
<?php// PHP program to illustrate // date_diff() function  // creates DateTime objects$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28');  // calculates the difference between DateTime objects$interval = date_diff($datetime1, $datetime2);  // printing result in days formatecho $interval->format('%R%a days');?>
+365 days

Program 2:
<?php// PHP program to illustrate // date_diff() function  // difference only in  year$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28');  $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n";  // Difference only in months$datetime1 = date_create('2018-04-28');$datetime2 = date_create('2018-06-28');  $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n";  // Difference in year, month, days$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-04-05');  $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n";  ?>
+365 days
+61 days
+281 days

Reference:http://php.net/manual/en/function.date-diff.php
AndroGarcia
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optional empty() method in Java with examples

30 Jul, 2019
The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value.
Syntax:
public static <T> 
  Optional<T> empty()

Parameters: This method accepts nothing.
Return value: This method returns an empty instance of this Optional class.
Below programs illustrate empty() method:Program 1:
// Java program to demonstrate// Optional.empty() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);    }}
Optional: Optional.empty

Program 2:
// Java program to demonstrate// Optional.empty() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<String> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);    }}
Optional: Optional.empty

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#empty–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
HashSet in Java
Abstraction in Java
How to call some function before main() function in C++?

03 Jun, 2020
Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++.
How to call some function before main() function?To call some function before main() method in C++,
Create a classCreate a function in this class to be called.Create the constructor of this class and call the above method in this constructorNow declare an object of this class as a global variable.Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
Create a class
Create a function in this class to be called.
Create the constructor of this class and call the above method in this constructor
Now declare an object of this class as a global variable.
Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
Below is the implementation of the above approach:
// C++ program to call some function// before main() function  #include <iostream>using namespace std;  // Classclass GFG {  public:    // Constructor of the class    GFG()    {          // Call the other function        func();    }      // Function to get executed before main()    void func()    {        cout << "Inside the other function"             << endl;    }};  // Global variable to declare// the object of class GFGGFG obj;  // Driver codeint main(){    cout << "Inside main method" << endl;    return 0;}
Inside the other function
Inside main method

How will this get executed?Now when the program will get executed, the global variable will get created before calling the main() method. Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method.
Hence we can easily call the function before the main().
pawan_joshi
CPP-Functions
cpp-main
main
Technical Scripter 2019
C++ Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is DVM(Dalvik Virtual Machine)?

22 May, 2020
Dalvik Virtual Machine is a Register-Based virtual machine. It was designed and written by Dan Bornstein with contributions of other Google engineers as part of the Android mobile phone platform. The Dalvik virtual machine was named after Bornstein after the fishing village “Dalvík” in Eyjafjörður, Iceland, where some of his ancestors used to live.
The Java Compiler(javac) converts the Java Source Code into Java Byte-Code(.class). Then DEX Compiler converts this (.class) file into in Dalvik Byte Code i.e. “.dex” file.
For Android, a new Virtual machine was developed by Google as stated above. It uses registers of the CPU to store the operands. So no requirement of any pushing and popping of instructions. Hence making execution faster. The instructions operate on virtual registers, being those virtual registers memory positions in the host device. Register-based models are good at optimizing and running on low memory. They can store common sub-expression results which can be used again in the future. This is not possible in a Stack-based model at all. Dalvik Virtual Machine uses its own byte-code and runs “.dex”(Dalvik Executable File) file.
DVM supports the Android operating system only.
In DVM executable is APK.
Execution is faster.
From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler.
DVM has been designed so that a device can run multiple instances of the Virtual Machine effectively.
Applications are given their own instances.
DVM supports only Android Operating System.
For DVM very few Re-Tools are available.
Requires more instructions than register machines to implement the same high-level code.
App Installation takes more time due to dex.
More internal storage is required.
Picked
Computer Organization & Architecture
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to move a text in HTML ?

21 Jun, 2021
Some content of a website is like an alert or notification/information that has to be shown to each and every person who is using the website. It has to be placed at some point where everyone can see it.
In this article, we will learn how to create moving content on your website using HTML <marquee> tag. The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top.
Syntax:
<marquee> Contents... </marquee>
Approach:
Create a simple HTML file in any text editor.
 Add the text you want to move inside the <marquee> tag.
Example:
HTML
<!DOCTYPE html><html>  <body>    <h2>Welcome To GFG</h2>    <marquee> Lets Move this text.</marquee>    <marquee direction="right"         behavior="alternate"         style="border:BLACK 2px SOLID">        Geeks for Geeks    </marquee></body>  </html>
Output:
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find N largest elements from a list

24 Apr, 2020
Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N.
Examples :
Input : [4, 5, 1, 2, 9] 
        N = 2
Output :  [9, 5]

Input : [81, 52, 45, 10, 3, 2, 96] 
        N = 3
Output : [81, 96, 52]

A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation :
# Python program to find N largest# element from given list of integers  # Function returns N largest elementsdef Nmaxelements(list1, N):    final_list = []      for i in range(0, N):         max1 = 0                  for j in range(len(list1)):                 if list1[j] > max1:                max1 = list1[j];                          list1.remove(max1);        final_list.append(max1)              print(final_list)  # Driver codelist1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]N = 2  # Calling the functionNmaxelements(list1, N)
Output :
[85, 41]
Time Complexity : O(N * size) where size is size of the given list.Method 2:
# Python program to find N largest# element from given list of integers  l = [1000,298,3579,100,200,-45,900]n = 4  l.sort()print(l[-n:])
Output:
[-45, 100, 200, 298, 900, 1000, 3579]
Find the N largest element: 4
[298, 900, 1000, 3579]

Please refer k largest(or smallest) elements in an array for more efficient solutions of this problem.
shyampopz0
Python list-programs
python-list
Python
Python Programs
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hello World program in Kotlin

03 Jun, 2022
Hello, World! is the first basic program in any programming language. Let’s write the first program in Kotlin programming language. 
The “Hello, World!” program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. 
// Kotlin Hello World Program
fun main(args: Array<String>) {
    println("Hello, World!")
}
You can compile the program in the command-line compiler. 
$ kotlinc firstapp.kt
Now, Run the program to see the output in a command-line compiler. 
$kotlin firstapp.kt
Hello, World!
Note: You can run the program in Intellij IDEA as shown in the Setting up the environment article. 
Line #1: First line is a comment which is ignored by the compiler. Comments are added to the program with the purpose to make the source code easy to read and understand by the readers.
Kotlin supports two types of comments as follows: 
1. Single line comment
// single line comment
2. Multiple line comment
/*   This is
     multi line
     comment
*/
Line #2: The second line defines the main function 
 fun main(args: Array<String>) {
    // ...
}
The main() function is the entry point of every program. All functions in kotlin start fun keyword followed by the name of function(here main is the name), a list of parameters, an optional return type, and the body of the function ( { ....... } ). In this case, main function contains the argument – an array of strings and return units. Unit type corresponds to void in java means the function does not return any value.  
Line #3: The third line is a statement and it prints “Hello, World!” to print the output of the program. 
println("Hello, World!")
Semicolons are optional in Kotlin, just like other modern programming languages. 
simranarora5sos
singhankitasingh066
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to plot a normal distribution with Matplotlib in Python ?

03 Jan, 2021
Prerequisites:
Matplotlib
Numpy
Scipy
Statistics
Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a die, and many more. 
The probability density function of normal or Gaussian distribution is given by:
Probability Density Function
Where, x is the variable, mu is the mean, and sigma standard deviation
Matplotlib is python’s data visualization library which is widely used for the purpose of data visualization.
Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.
Scipy is a python library that is useful in solving many mathematical equations and algorithms.
Statistics module provides functions for calculating mathematical statistics of numeric data.
To calculate mean of the data
Syntax:
mean(data)
To calculate standard deviation of the data
Syntax:
stdev(data)
To calculate normal probability density of the data norm.pdf is used, it refers to the normal probability density function which is a module in scipy library that uses the above probability density function to calculate the value.
Syntax:
norm.pdf(Data, loc, scale)
Here, loc parameter is also known as the mean and the scale parameter is also known as standard deviation.
Import module
Create data
Calculate mean and deviation
Calculate normal probability density
Plot using above calculated values
Display plot
Below is the implementation.
Python3
import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normimport statistics  # Plot between -10 and 10 with .001 steps.x_axis = np.arange(-20, 20, 0.01)  # Calculating mean and standard deviationmean = statistics.mean(x_axis)sd = statistics.stdev(x_axis)  plt.plot(x_axis, norm.pdf(x_axis, mean, sd))plt.show()
Output:
The output of above code
Picked
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
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OpenCV | cv2.ellipse() method

28 Aug, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.ellipse() method is used to draw a ellipse on any image.
Syntax: cv2.ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color [, thickness[, lineType[, shift]]])
Parameters:image: It is the image on which ellipse is to be drawn.centerCoordinates: It is the center coordinates of ellipse. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).axesLength: It contains tuple of two variables containing major and minor axis of ellipse (major axis length, minor axis length).angle: Ellipse rotation angle in degrees.startAngle: Starting angle of the elliptic arc in degrees.endAngle: Ending angle of the elliptic arc in degrees.color: It is the color of border line of shape to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.thickness: It is the thickness of the shape border line in px. Thickness of -1 px will fill the shape by the specified color.lineType: This is an optional parameter.It gives the type of the ellipse boundary.shift: This is an optional parameter. It denotes the number of fractional bits in the coordinates of the center and values of axes.
Return Value: It returns an image.
Image used for all the below examples:
Example #1:
# Python program to explain cv2.ellipse() method     # importing cv2 import cv2     # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'    # Reading an image in default modeimage = cv2.imread(path)    # Window name in which image is displayedwindow_name = 'Image'   center_coordinates = (120, 100)  axesLength = (100, 50)  angle = 0  startAngle = 0  endAngle = 360   # Red color in BGRcolor = (0, 0, 255)   # Line thickness of 5 pxthickness = 5   # Using cv2.ellipse() method# Draw a ellipse with red line borders of thickness of 5 pximage = cv2.ellipse(image, center_coordinates, axesLength,           angle, startAngle, endAngle, color, thickness)   # Displaying the image cv2.imshow(window_name, image) 
Output:
Example #2:Using thickness of -1 px and rotation of 30 degrees.
# Python program to explain cv2.ellipse() method    # importing cv2import cv2    # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'    # Reading an image in default modeimage = cv2.imread(path)    # Window name in which image is displayedwindow_name = 'Image'   center_coordinates = (120, 100)  axesLength = (100, 50)  angle = 30  startAngle = 0  endAngle = 360   # Blue color in BGRcolor = (255, 0, 0)   # Line thickness of -1 pxthickness = -1   # Using cv2.ellipse() method# Draw a ellipse with blue line borders of thickness of -1 pximage = cv2.ellipse(image, center_coordinates, axesLength, angle,                          startAngle, endAngle, color, thickness)   # Displaying the imagecv2.imshow(window_name, image) 
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ program to overload addition operator to add two matrices

Suppose we have two matrices mat1 and mat2. We shall have to add these two matrices and form the third matrix. We shall have to do this by overloading the addition operator.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
Overload the addition operator, this will take another matrix mat as second argument
Overload the addition operator, this will take another matrix mat as second argument
define one blank 2d array vv
define one blank 2d array vv
Define one 2D array vv and load current matrix elements into it
Define one 2D array vv and load current matrix elements into it
for initialize i := 0, when i < size of vv, update (increase i by 1), do:for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j]
for initialize i := 0, when i < size of vv, update (increase i by 1), do:
for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j]
for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:
vv[i, j] := vv[i, j] + mat.a[i, j]
return a new matrix using vv
Let us see the following implementation to get better understanding −
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
  public:
    Matrix() {}
    Matrix(const Matrix& x) : a(x.a) {}
    Matrix(const vector<vector<int>>& v) : a(v) {}
    Matrix operator+(const Matrix&);
    vector<vector<int>> a;
    void display(){
        for(int i = 0; i<a.size(); i++){
            for(int j = 0; j<a[i].size(); j++){
                cout << a[i][j] << " ";
            }    
            cout << endl;
        }
    }
};
Matrix Matrix::operator+(const Matrix& m){
    vector<vector<int>> vv = a;
    for (int i=0; i<vv.size(); i++){
        for (int j=0; j<vv[0].size(); j++){
            vv[i][j] += m.a[i][j];
        }
    }
    return Matrix(vv);
}
int main(){
   vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}};
   vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}};
   int r = mat1.size();
   int c = mat1[0].size();
   Matrix m1(mat1), m2(mat2), res;
   res = m1 + m2;
   res.display();
}

{{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}}
13 11
13 13
13 12
How does del operator work on list in Python?

The del operator removes a specific index from given list. For example, if you want to remove the element on index 1 from list a, you'd use:
a = [3, "Hello", 2, 1]
del a[1]
print(a)
This will give the output −
[3, 2, 1]
Note that del removes the elements in place, ie, it doesn't create a new list.
Difference Between Vector and List - GeeksforGeeks

28 May, 2020
Vector: Vector is a type of dynamic array which has the ability to resize automatically after insertion or deletion of elements. The elements in vector are placed in contiguous storage so that they can be accessed and traversed using iterators. Element is inserted at the end of the vector.Example:
vector v;
v.insert(5);
v.delete();

List: List is a double linked sequence that supports both forward and backward traversal. The time taken in the insertion and deletion in the beginning, end and middle is constant. It has the non-contiguous memory and there is no pre-allocated memory.Example:
list  l;
l.insert_begin(5);
l.delete_end();

Below is a table of differences between Vector and List:
Difference Between
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
GET and POST requests using Python