code-rag-bench/online-tutorials huggingface dataset:
Python | Working with the Image Data Type in pillow

26 Jul, 2019
In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow.
Image we will be working on :
size() method – It helps to get the dimensions of an image.
IMG = Image.open(Image_path)croppedIm = IMG.size
# import Image modulefrom PIL import Image  # open the imagecatIm = Image.open('D:/cat.jpg')  # Display the dimensions of the imageprint(catIm.size)
Output :
(400, 533)
Getting height and width separately – It helps us to get the height and width of the image.
# import Image modulefrom PIL import Image  # Open the imagecatIm = Image.open('D:/cat.jpg')  # Create two different variables # The first one will contain width and # the second one will contain heightwidth, height = catIm.size  # Display height and widthprint(height)print(width)
Output :
400
533
 filename() method – It helps us to get the filename of the image.
IMG = Image.open(Image_path)croppedIm = IMG.filename
# import the Image modulefrom PIL import Image  # Open the imagecatIm = Image.open('D:/cat.jpg')  # print the filenameprint(catIm.filename)
Output :
D:/cat.jpg
 format() method – It helps us to get the format the image is in.
IMG = Image.open(Image_path)croppedIm = IMG.format
# import the imagefrom PIL import Image  # open the imagecatIm = Image.open('D:/cat.jpg')  # print the format of the imageprint(catIm.format)
Output :
JPEG
 format_description() method – It helps us to get the format description of the image.
IMG = Image.open(Image_path)croppedIm = IMG.format_description
# import the imagefrom PIL import Image  # open the imagecatIm = Image.open('D:/cat.jpg')  # print the format description of the imageprint(catIm.format_description)
Output :
JPEG (ISO 10918)
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Interchange Any Two Rows in the Matrix

11 Mar, 2022
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required.
Examples
Input 1: K = 1, L = 2,

          mat[][] = {{2, 1, 4},
                     {1, 2, 3},  
                     {3, 6, 2}}
                     
Output: 
          mat[][] = {{1, 2, 3},
                     {2, 1, 4},  
                     {3, 6, 2}}
                    

Input 2: K = 1, L = 1,
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}} 
                              
Output: 
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}}   
                                   
Input 3: K = 2, L = 3,
          mat[][] =  {{2, 1},
                      {1, 2},  
                      {3, 6}}
                     
Output: 
          mat[][] =  {{2, 1},
                     {3, 6},  
                     {1, 2}}
Approach
If First and Second are same, then print the matrix as it is.
Else Loop over the Kth and Lth row of the matrix.
Swap the elements ith index of both the rows while traversal.
Now after the loop gets over, print the matrix.
Below is the code implementation for the above approach:
Java
// Java program to interchange// two row in a Matriximport java.io.*; class GFG {       public static void printMatrix(int[][] matrix)    {        for (int i = 0; i < matrix.length; i++) {            for (int j = 0; j < matrix[0].length; j++)                System.out.print(matrix[i][j] + " ");            System.out.println();        }    }    public static void exchangeAnyTwoRows(int[][] matrix,                                          int K, int L)    {                 int[] temp = matrix[K - 1];        matrix[K - 1]= matrix[L - 1];        matrix[L - 1] = temp;               // Print matrix        printMatrix(matrix);    }       public static void main(String[] args)    {        int K = 2, L = 3;        int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };         // calling the exchange row function        exchangeAnyTwoRows(mat, K, L);    }}
  
2 1 4 
3 6 2 
1 2 3 
 
Time Complexity: 0(n), Where n is the length of the row.
 
Space Complexity: 0(1)
 
sagartomar9927
smrmngkmru
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Overloading of function-call operator in C++

19 Apr, 2021
In this article, we will discuss the Overloading of the function-call operators in C++.
The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object.
When the function call operator is overloaded, an operator function is created that can be used to pass parameters.
It modifies that how the operator is fetched by the object.
In Object-Oriented Languages, operator() can be treated as a normal operator, and objects of a class type can call function (named operator()) like making a function call to any other overloaded operator.
When the function call operator is overloaded, a new way to call a function is not created rather an operator() function is created that can be passed an arbitrary number of parameters.
Program:
Below is the program of taking input in a matrix using friend functions first to overload insertion operator and extraction operator and then overloading operator() for taking input for the ith row and the jth column of the matrix and displaying value at the ith row and the jth column stored in the matrix:
C++
// C++ program to illustrate the// above concepts#include <bits/stdc++.h>#include <iostream>using namespace std;#define N 3#define M 3  // Matrix Classclass Matrix {private:    int arr[N][M];  public:    // Overloading of input stream    friend istream& operator>>(        istream&, Matrix&);      // Overloading of output stream    friend ostream& operator<<(        ostream&, Matrix&);    int& operator()(int, int);};  // Function to overload the input// ">>" operatoristream& operator>>(istream& cin,                    Matrix& m){    int x;    for (int i = 0; i < N; i++) {        for (int j = 0; j < M; j++) {            // Overloading operator()            // to take input            cin >> m(i, j);        }    }    return cin;}  // Function to overload the output// "<<" operatorostream& operator<<(ostream& cout,                    Matrix& m){    for (int i = 0; i < N; i++) {        for (int j = 0; j < M; j++) {              // Overloading operator() to            // take input m.operator()(i, j);            cout << m(i, j) << " ";        }        cout << endl;    }    return cout;}  // Function to call the operator// function to overload the operatorsint& Matrix::operator()(int i, int j){    return arr[i][j];}  // Driver Codeint main(){    Matrix m;      printf("Input the matrix:\n");      // Compiler calls operator >> and    // passes object cin and object m    // as parameter operator>>(cin, m);    cin >> m;      printf("The matrix is:\n");    // Compiler calls operator << and    // passes object cout and object m    // as parameter operator<<(cin, m);    cout << m;      return 0;}
Output:
C++-Operator Overloading
cpp-operator
cpp-operator-overloading
C++
C++ Programs
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for Difference between sums of odd and even digits

05 Dec, 2018
Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit).
Examples:
Input : 1212112
Output : Yes
Explanation:-
the odd position element is 2+2+1=5
the even position element is 1+1+1+2=5
the difference is 5-5=0.so print yes.

Input :12345
Output : No
Explanation:-
the odd position element is 1+3+5=9
the even position element is 2+4=6
the difference is 9-6=3 not  equal
to zero. So print no.

Method 1: One by one traverse digits and find the two sums. If difference between two sums is 0, print yes, else no.
Method 2 : This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not.
// Java program to check if difference between sum of// odd digits and sum of even digits is 0 or not  import java.io.*;import java.util.*;  class GFG {    public static boolean isDiff(int n)    {        return (n % 11 == 0);    }    public static void main(String[] args)    {        int n = 1243;        if (isDiff(n))            System.out.print("Yes");        else            System.out.print("No");    }}
Yes

Please refer complete article on Difference between sums of odd and even digits for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Java Program to Read a File to String
Comparing two ArrayList In Java
Java Program to Convert File to a Byte Array
SHA-1 Hash
Java Program to Find Sum of Array Elements
How to get elements of specific class inside a div ?

09 Apr, 2021
In this article, we will find how to get all elements of a specific class inside an HTML div tag.
To do this we will use HTML DOM querySelectorAll()method. This method of HTML DOM (document object model) returns all elements in the document that matches a specified CSS selector(s). The syntax to use this method is as follows.
Syntax:
document.querySelectorAll(CSS-selectors)
Example: The CSS selectors would be class, ids, or any HTML tags. Let us learn how to use this method to select elements of a specific class inside an HTML div tag.
HTML
<!DOCTYPE html><html>  <head>    <style>      #tag {        border: 4px solid black;        margin: 5px;      }    </style>  </head>  <body>    <div id="tag">      <p class="example1">HTML</p>        <p class="example1">CSS</p>        <p class="example1">Javascript</p>        <p class="example2">C</p>    </div>    <br />      <button onclick="changecolor()">      click to Apply change    </button>    <script>      function changecolor() {        var x = document.getElementById("tag")                .querySelectorAll(".example1");        for (i = 0; i < x.length; i++) {          x[i].style.backgroundColor = "blue";        }      }    </script>  </body></html>
Output:After clicking the “click to Apply change” button, we get the following output. We can see that by selecting a div using getElementById() and then selecting all its elements inside the div using querySelectorAll(), we can apply changes to all its elements.
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to read all CSV files in a folder in Pandas?

21 Apr, 2021
In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content.
Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’Loop over the list of csv files, read that file using pandas.read_csv().Convert each csv file into a dataframe.Display its location, name, and content.
Import necessary python packages like pandas, glob, and os.
Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’
Loop over the list of csv files, read that file using pandas.read_csv().
Convert each csv file into a dataframe.
Display its location, name, and content.
Below is the implementation.
Python3
# import necessary librariesimport pandas as pdimport osimport glob    # use glob to get all the csv files # in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, "*.csv"))    # loop over the list of csv filesfor f in csv_files:          # read the csv file    df = pd.read_csv(f)          # print the location and filename    print('Location:', f)    print('File Name:', f.split("\\")[-1])          # print the content    print('Content:')    display(df)    print()
Output:
Note: The program reads all CSV files in the folder in which the program itself is present.
Picked
python-csv
Python-pandas
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
Check if Two Objects are Equal in R Programming – setequal() Function

15 Jun, 2020
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.
Syntax: setequal(x, y)
Parameters:x and y: Objects with sequence of items
Example 1:
# R program to illustrate # the use of setequal() function      # Vector 1 x1 <- c(1, 2, 3, 4, 5, 6)         # Vector 2  x2 <- c(1:6)      # Vector 3x3 <- c(2, 3, 4, 5, 6)      # Calling setequal() Function setequal(x1, x2)       setequal(x1, x3)       
Output:
[1] TRUE
[1] FALSE

Example 2:
# R program to illustrate  # the use of setequal() function     # Data frame 1 data_x <- data.frame(x1 = c(5, 6, 7),                          x2 = c(2, 2, 2))     # Data frame 2 data_y <- data.frame(y1 = c(5, 6, 7),                             y2 = c(2, 2, 2))     # Calling setequal() Functionsetequal(data_x, data_y)   
Output:
[1] TRUE

R Array-Functions
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Pandas – Groupby value counts on the DataFrame

15 Mar, 2021
Prerequisites: Pandas
Pandas can be employed to count the frequency of each value in the data frame separately. Let’s see how to Groupby values count on the pandas dataframe. To count Groupby values in the pandas dataframe we are going to use groupby() size() and unstack() method.
groupby(): groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names
Syntax: 
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)
Parameters :
by : mapping, function, str, or iterable
axis : int, default 0
level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels
as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output
sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group.
group_keys : When calling apply, add group keys to index to identify pieces
squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type
Returns : GroupBy object
size(): size method is used to get the integer representing the number of elements in object. The size method is return the number of rows times number of columns if DataFrame.
Syntax:
Dataframe.size()
unstack(): unstack method works with the MultiIndex objects in DataFrame, producing a reshaped DataFrame with a new inner-most level of column labels.
Syntax:
Dataframe.unstack()
Import module
Create or load data
Create data frame
Count value of occurrences of each value
Print resultant data frame
Example1:
Python
# import pandasimport pandas as pd  # create dataframedf = pd.DataFrame({    'Course': ['BBA', 'BCA', 'BBA', 'BCA', 'BCA'],    'Student Name': ['Rishabh', 'Rahul', 'Suraj', 'Mukul', 'Vinit'],    'Age': [21, 22, 23, 22, 23]})    # print original dataframeprint("original dataframe")display(df)  # counts Groupby valuedf = df.groupby(['Course', 'Student Name', 'Age']).size().unstack(fill_value=0)  # print dataframeprint("Result :")display(df)
Output:
Example 2:
Python
# import pandasimport pandas as pd  # create dataframedf = pd.DataFrame({    'City': ['Saharanpur', 'Meerut', 'Saharanpur', 'Saharanpur', 'Meerut'],    'Employes Name': ['Robin', 'Tushar', 'Rohan', 'Mukul', 'Manoj'],    'Salary': [21000, 22000, 21000, 22000, 22000]})    # print original dataframeprint("original dataframe: ")display(df)  # counts Groupby valuedf = df.groupby(['City', 'Employes Name', 'Salary']                ).size().unstack(fill_value=0)  # print dataframeprint("result: ")display(df)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Templates in C++ - GeeksQuiz

23 Oct, 2020
x = 1 count = 0

x = 1 count = 1

x = 1.1 count = 0
x = 1 count = 0

x = 1 count = 0

x = 1.1 count = 0
x = 1 count = 0

x = 1 count = 1

x = 1.1 count = 2
7
7.0
7.0
0
0
1
1
2
1
1
0
6
12
2
8
8
8
16
24
8
16
20
28
10
1
10000
256
1
1
#include <iostream>
using namespace std;

template < class T, int N >
 T fun (T arr[], int size)
{
    if (size > N)
      cout << "Not possible";
    T max = arr[0];
   for (int i = 1; i < size; i++)
      if (max < arr[i])
          max = arr[i];
   return max;
}

int main ()
{
    int arr[] = {12, 3, 14};
    cout << fun  (arr, 3);
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Matplotlib - Subplots() Function

Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call.
Plt.subplots(nrows, ncols)

The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot.
import matplotlib.pyplot as plt
fig,a =  plt.subplots(2,2)
import numpy as np
x = np.arange(1,5)
a[0][0].plot(x,x*x)
a[0][0].set_title('square')
a[0][1].plot(x,np.sqrt(x))
a[0][1].set_title('square root')
a[1][0].plot(x,np.exp(x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log10(x))
a[1][1].set_title('log')
plt.show()
The above line of code generates the following output −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Koa.js - Routing

Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command.
npm install --save koa-router

Now that we have Koa-router installed, let’s look at a simple GET route example.
var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();              //Instantiate the router
_.get('/hello', getMessage);   // Define routes

function *getMessage() {
   this.body = "Hello world!";
};

app.use(_.routes());           //Use the routes defined using the router
app.listen(3000);
If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello". Our Koa app executes the callback function attached to this route and sends "Hello World!" as the response.
We can also have multiple different methods at the same route. For example,
var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router(); //Instantiate the router

_.get('/hello', getMessage);
_.post('/hello', postMessage);

function *getMessage() {
	this.body = "Hello world!";
};
function *postMessage() {
   this.body = "You just called the post method at '/hello'!\n";
};
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);
To test this request, open your terminal and use cURL to execute the following request
curl -X POST "https://localhost:3000/hello"

A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following −
_.all('/test', allMessage);

function *allMessage(){
   this.body = "All HTTP calls regardless of the verb will get this response";
};
 Print
 Add Notes
 Bookmark this page
D3.js | d3.values() Function - GeeksforGeeks

28 Jun, 2019
The d3.values() function in D3.js is used to return an array containing the property values of the specified object or an associative array.
Syntax:
d3.values(object)
Parameters: This function accepts single parameter object which contains the key, value pairs.
Return Value: It returns the values of the given object.
Below programs illustrate the d3.values() function in D3.js:
Example 1:
<!DOCTYPE html><html>  <head>    <title>        d3.values() function    </title>          <script src = "https://d3js.org/d3.v4.min.js"></script></head>  <body>    <script>              // Initialising an object        var month = {            "January": 1,            "February": 2,            "March": 3,            "April": 4        };                    // Calling the d3.values() function        A = d3.values(month);                // Getting the values of the given object        document.write(A);    </script></body>  </html>                    
Output:
1, 2, 3, 4

Example 2:
<!DOCTYPE html><html>  <head>    <title>        d3.values() function    </title>          <script src = "https://d3js.org/d3.v4.min.js"></script></head>  <body>    <script>              // Initialising an object        var month = {            "GeeksforGeeks": 0,            "Geeks": 2,            "Geek": 3,            "gfg": 4        };                    // Calling the d3.values() function        A = d3.values(month);                // Getting the values of the given object        document.write(A);    </script></body>  </html>                     
Output:
0, 2, 3, 4

Reference: https://devdocs.io/d3~5/d3-collection#values
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
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?
JavaScript Union of two objects

We have one object like this −
const obj1 = { name: " ", email: " " };
and another like this −
const obj2 = { name: ['x'], email: ['y']};
We are required to write a JavaScript function that takes in two such objects. and want the output to be the union like this −
const output = { name: {" ", [x]}, email: {" ", [y]} };
The code for this will be −
const obj1 = { name: " ", email: " " };
const obj2 = { name: ['x'], email: ['y']};
const objectUnion = (obj1 = {}, obj2 = {}) => {
   const obj3 = {
      name:[],
      email:[]
   };
   for(let i in obj1) {
      obj3[i].push(obj1[i]);
   }
   for(let i in obj2) {
      obj3[i].push(obj2[i]);
   }
   return obj3;
};
console.log(objectUnion(obj1, obj2));
And the output in the console will be −
{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }
How to disable future dates in JavaScript Datepicker?

In order to disable future dates, you need to use maxDate and set the current date. Following is the JavaScript code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>The selected date is as follows: <input type="text" class="disableFuturedate"></p>
<script>
   $(document).ready(function () {
      var currentDate = new Date();
      $('.disableFuturedate').datepicker({
      format: 'dd/mm/yyyy',
      autoclose:true,
      endDate: "currentDate",
      maxDate: currentDate
      }).on('changeDate', function (ev) {
         $(this).datepicker('hide');
      });
      $('.disableFuturedate').keyup(function () {
         if (this.value.match(/[^0-9]/g)) {
            this.value = this.value.replace(/[^0-9^-]/g, '');
         }
      });
   });
</script>
</body>
</html>
In order to run the above program, I have saved this file with the name index.html. Right click on this file and select option open with live server.
This will run in any modern web browser automatically −
After that, click the mouse on text box, that will display the date picker as in the below
screenshot −
Accepting date strings (MM-dd-yyyy format) using Java regex?

The following is the regular expression to match the date in the dd-MM-yyyy format.
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
To match a date in a string in that format.
Compile the above expression of the compile() method of the Pattern class.
Compile the above expression of the compile() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data.
The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingDate {
   public static void main(String[] args) {
      String date = "01/12/2019";
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(date);
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
   }
}
Date is valid
The matches() method of the String class accepts a regular expression and matches the current string with it and returns true in case of a match and else returns false. Therefore, to verify if the given date (in string format) is in the required format −
Get the date string.
Invoke the matches() method on it by passing the above regular expression as a parameter to it.
import java.util.Scanner;
public class Just {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your Date of birth: ");
      String dob = sc.nextLine();
      //Regular expression to accept date in MM-DD-YYY format
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      boolean result = dob.matches(regex);
      if(result) {
         System.out.println("Given date of birth is valid");
      } else {
         System.out.println("Given date of birth is not valid");
      }
   }
}
Enter your name:
Janaki
Enter your Date of birth:
26/09/1989
Given date of birth is not valid
Enter your name:
Janaki
Enter your Date of birth:
09/26/1989
Given date of birth is valid
What is the difference between Microtask Queue and Callback Queue in asynchronous JavaScript ? - GeeksforGeeks

27 Jan, 2022
To know the difference between Microtask Queue and Callback Queue, we need to have a clear idea of how does asynchronous JavaScript gets executed and what are the roles that Microtask Queue and Callback Queue play.
Functions or operations running parallel with the other functions or operations are called asynchronous functions or operations in JavaScript. Asynchronous JavaScript code requires Callback functions that get executed later after the desired time. 
Example: Below code illustrates the use of setTimeout() function in JavaScript.
Javascript
<script>  setTimeout(function greet() {    console.log("Welcome to GeeksforGeeks!");  }, 2000);</script>
Now, after this desired time, the code needs to be passed to the Call Stack, but this Call Stack doesn’t provide a timer by which we can delay the execution of the code. So, it uses the help of a web API setTimeout() which is available in the window global object in the browser. After a certain time period, Call Stack gets the code through Event Loop which fetches the Callback functions to Call Stack. But, Callback functions can’t directly go to the Event loop.
So, here comes the role of Microtask Queue and Callback Queue. These Queues work as a mediator, once the timer gets expired the callback functions are put inside these queues serially. And whenever the Call stack is empty, the event loop fetches them to Call Stack in FIFO order. 
But, we need Microtask Queue and Callback Queue for different purposes. Let’s see the comparison between them.
Callback Queue: After the timer gets expired, the callback function is put inside the Callback Queue, and the Event Loop checks if the Call Stack is empty and if empty, pushes the callback function from Callback Queue to Call Stack and the callback function gets removed from the Callback Queue. Then the Call Stack creates an Execution Context and executes it.  
Microtask Queue: Microtask Queue is like the Callback Queue, but Microtask Queue has higher priority. All the callback functions coming through Promises and Mutation Observer will go inside the Microtask Queue. For example, in the case of .fetch(), the callback function gets to the Microtask Queue. Promise handling always has higher priority so the JavaScript engine executes all the tasks from Microtask Queue and then moves to the Callback Queue.
bitwa
lexjs
javascript-basics
JavaScript-ES
JavaScript-Questions
JavaScript
Web Technologies
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 PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Bootstrap Form CheckBox

Use checkbox class if you want the user to select any number of options from a list. Use .checkbox-inline class to a series of checkboxes for controls appear on the same line.
You can try to run the following code to implement Bootstrap form checkbox
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Try v1.2 Bootstrap Online</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>
      <label for = "name"></label>Favourite Live Streaming</label>
      <div class = "checkbox">
         <label>
            <input type = "checkbox" value = "">Amazon Prime
         </label>
      </div>
      <div class = "checkbox">
         <label>
            <input type = "checkbox" value = "">Hotstar
         </label>
      </div>
   </body>
</html>
What do you mean by a dynamic initialization of variables?

Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to be provided during run time. Dynamic initialization can be achieved using
constructors and passing parameters values to the constructors. This type of initialization is required to initialize the class variables during run time.
Why we need the dynamic initialization?
Dynamic initialization of objects is needed as
It utilizes memory efficiently.
It utilizes memory efficiently.
Various initialization formats can be provided using overloaded constructors.
Various initialization formats can be provided using overloaded constructors.
It has the flexibility of using different formats of data at run time considering the situation.
It has the flexibility of using different formats of data at run time considering the situation.
#include <iostream>
using namespace std;
class simple_interest {
   float principle , time, rate ,interest;
   public:
      simple_interest (float a, float b, float c) {
         principle = a;
         time =b;
         rate = c;
      }
      void display ( ) {
         interest =(principle* rate* time)/100;
         cout<<"interest ="<<interest ;
      }
};
int main() {
   float p,r,t;
   cout<<"principle amount, time and rate"<<endl;
   cout<<"2000 7.5 2"<<endl;
   simple_interest s1(2000,7.5,2);//dynamic initialization
   s1.display();
   return 1;
}
Enter principle amount ,rate and time
2000 7.5 2
Interest =300
How to dismiss the Alert with click on outside of the alert in iOS?

Understanding and implementing UIAlert can be tricky especially if you’re new to iOS Development, In this post, we will be seeing how we can dismiss the alert when the user taps outside the alert box.
For this demo, we will be using UIAlert class, to configure alerts and action sheets with the message that you want to display and the actions from which to choose. After configuring the alert controller with the actions and style you want, present it using the present(_:animated: completion:) method. UIKit displays alerts and action sheets modally over your app's content.
You can read more about it: https://developer.apple.com/documentation/uikit/uialertcontroller
So let’s get started,
Step 1 − Open Xcode and create a single view application and name it UIAlertSample.
Step 2 − In Main. storyboard add one button, and create @IBAction and name it showAlert,
@IBAction func showAlert(_ sender: Any) { }
So basically, when we tap on the button an alert will be displayed, when the user taps outside the alert the alert will be dismissing.
Step 3 − Inside button action showAlert, First create UIAlert object as below
let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)
Step 4 − Present the alert and on its completion add a selector as shown below,
self.present(uialert, animated: true, completion:{
   uialert.view.superview?.isUserInteractionEnabled = true
   uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
})
Step 5 − Add selector function,
@objc func dismissOnTapOutside(){
   self.dismiss(animated: true, completion: nil)
}
Step 6 − Run the application,
import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
   }
   @IBAction func showAlert(_ sender: Any) {
      let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)
      self.present(uialert, animated: true, completion:{
      uialert.view.superview?.isUserInteractionEnabled = true
      uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
      })
   }
   @objc func dismissOnTapOutside(){
      self.dismiss(animated: true, completion: nil)
   }
}
C Program to Check Armstrong Number?

A number is called an Armstrong number if the sum of cubes of digits of the number is equal to the number itself. It is a mathematical concept usually used in programming to build basic logic of the programmer
Input:370
Output:370 is an Armstrong Number
370 = 3*3*3 + 7*7*7 + 0*0*0
= 27 + 343 + 0
= 370
include <iostream>
using namespace std;
int main() {
   int n, num, rem, sum = 0;
   cin >> n;
   num = n;
   while(num != 0) {
      digit = num % 10;
      sum += digit * digit * digit;
      num /= 10;
   }
   if(sum == n)
      printf("%d is an Armstrong number.", n );
   else
      printf("%d is not an Armstrong number.",n);
   return 0;
}
React Native - Text

In this chapter, we will talk about Text component in React Native.
This component can be nested and it can inherit properties from parent to child. This can be useful in many ways. We will show you example of capitalizing the first letter, styling words or parts of the text, etc.
The file we are going to create is text_example.js
In this step, we will just create a simple container.
import React, { Component } from 'react'
import TextExample from './text_example.js'

const App = () => {
   return (
      <TextExample/>
   )
}
export default App
In this step, we will use the inheritance pattern. styles.text will be applied to all Text components.
You can also notice how we set other styling properties to some parts of the text. It is important to know that all child elements have parent styles passed to them.
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native'

const TextExample = () => {
   return (
      <View style = {styles.container}>
         <Text style = {styles.text}>
            <Text style = {styles.capitalLetter}>
               L
            </Text>
            
            <Text>
               orem ipsum dolor sit amet, sed do eiusmod.
            </Text>
            
            <Text>
               Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam,
               quis aliquip ex ea commodo consequat.
            </Text>
            
            <Text style = {styles.italicText}>
               Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.
            </Text>
            
            <Text style = {styles.textShadow}>
               Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
               deserunt mollit anim id est laborum.
            </Text>
         </Text>
      
      </View>
   )
}
export default TextExample

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
      marginTop: 100,
      padding: 20
   },
   text: {
      color: '#41cdf4',
   },
   capitalLetter: {
      color: 'red',
      fontSize: 20
   },
   wordBold: {
      fontWeight: 'bold',
      color: 'black'
   },
   italicText: {
      color: '#37859b',
      fontStyle: 'italic'
   },
   textShadow: {
      textShadowColor: 'red',
      textShadowOffset: { width: 2, height: 2 },
      textShadowRadius : 5
   }
})
You will receive the following output −

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to set style display of an html element in a selenium test?

We can set the style display of an html element with Selenium webdriver. The DOM interacts with the elements on the page with the help of Javascript. Selenium executes the Javascript commands by taking the help of the executeScript method. The commands to be executed are passed as arguments to the method.
Some operations like setting the style display be performed by Javascript Executor. The getElementById method can be used to locate the element. Then we have to apply the style.display method on the webelement and set the display type.
executor.executeScript
("document.getElementById('gsc-i-id1').style.display='block';");
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ElementStyleSet{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // set the display with style.display method
      j.executeScript ("document.getElementById('gsc-i-id1').style.display='block';");
      driver.close()
   }
}
How to use ReadKey() method of Console class in C#?

Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.
A common use of the ReadKey() method is that you can halt the program execution. This could be done until a key is pressed by the user.
Let us see an example −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      DateTime date = DateTime.Now;
      TimeZoneInfo timeZone = TimeZoneInfo.Local;
      Console.WriteLine("Time Zone = {0}\n", timeZone.IsDaylightSavingTime(date) ? timeZone.DaylightName : timeZone.StandardName);
      Console.Write(" to exit... ");
      while (Console.ReadKey().Key != ConsoleKey.Enter) {}
   }
}
Time Zone = UTC
<Enter> to exit...
Mean and Mode in SQL Server

28 Mar, 2018
Mean is the average of the given data set calculated by dividing the total sum by the number of values in data set.
Example:
Input:  1, 2, 3, 4, 5 
Output: 3
Explanation: 
sum = 1 + 2 + 3 + 4 + 5 = 15
number of values = 5
mean = 15 / 5 = 3

Query to find mean in the table
SELECT Avg(Column_Name) 
FROM  Table_Name

Example:
Creating Table:
Table Content:
Query to find Mean:
Mode of a data set is the value that appears most frequently in a series of data.
Example:
Input:  1, 2, 2, 3, 4, 4, 4, 5, 5, 6
Output: 4
Explanation:
2 occurs 2 times, 5 occurs 2 times
4 occurs 3 times and rest other 
occurs 1 time
So, 4 occurs most frequently and 
is thus the output.

Query to find mode in the table
SELECT TOP 1 Column_Name
FROM   Table_name
GROUP  BY [Column_Name]
ORDER  BY COUNT(*) DESC

Example:
Creating Table:
Table Content:
Query to find Mode:
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
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
SQL Correlated Subqueries
Window functions in SQL
How to Take Input from the User in Golang?

10 May, 2020
Scanln function can be used to take the input from the user in the Golang. Below is the example of taking input from the user:
// Golang program to show how// to take input from the userpackage main  import "fmt"  // main functionfunc main() {      // Println function is used to    // display output in the next line    fmt.Println("Enter Your First Name: ")      // var then variable name then variable type    var first string      // Taking input from user    fmt.Scanln(&first)    fmt.Println("Enter Second Last Name: ")    var second string    fmt.Scanln(&second)      // Print function is used to    // display output in the same line    fmt.Print("Your Full Name is: ")      // Addition of two string    fmt.Print(first + " " + second)}
Now save this file and execute as shown in the below screenshot:
Description About the Program:
main Package: When we build reusable pieces of code, we will develop a package as a shared library. But when we develop an executable program, we will use the package “main” for making the package as an executable program. The package “main” tells the Golang compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program. Remember when we build shared libraries, we will not have any main package and main function in the package.
fmt.Println is the print function which is used to print the output in the next line. While fmt.Print is used to display output in the same line. Whatever needs to be printed has to be written in inverted commas ” “.
var first string is the declaration of the variable first which is of string type. To declare variables following syntax needs to be followed: var var_name data_type 
 var var_name data_type 
fmt.Scanln(&first) is used to take input from user in the next line. While fmt.Scan is used to take input from user in the same line. Ampersand is necessary to give the reference as to in which variable we have to store the variable.
The Last line will simply add the two string of First Name and Last Name and will output the Full Name.
Golang-Program
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java