code-rag-bench/online-tutorials huggingface dataset:
Count of only repeated element in a sorted array of consecutive elements in C++

We are given an array of consecutive numbers of length n. The array has only one number which is repeated more than once. The goal is to get the number of times that element is repeated in the array. Or we can say find the length of a repeated element in the array.
We will traverse the array from i=0 to i<n. If any arr[i]==arr[i+1] increment count. At last increment count by 1 for last element. Count will have length of repeated element.
Let’s understand with examples.
Input − arr[]= { 0,1,2,3,3,3 }, N=6
Output − Count of only repeated element − 3
Explanation − 3 is repeated thrice here.
Input − arr[]= { 1,2,3,4,4,4,4,4,5,6 }, N=10
Output − Count of only repeated element − 5
Explanation − 4 is repeated 5 times here.
We take an integer array arr[] initialized with consecutive numbers where one number is repeated.
We take an integer array arr[] initialized with consecutive numbers where one number is repeated.
Variable len stores the length of the array.
Variable len stores the length of the array.
Function findRepeat(int arr[],int n) takes an array and its length as input and displays the repeated element value and length of repeated elements.
Function findRepeat(int arr[],int n) takes an array and its length as input and displays the repeated element value and length of repeated elements.
Take the initial count as 0.
Take the initial count as 0.
Starting from index i=0 to i<n. If arr[i]==arr[i+1]. Increment count. Store element in variable value.
Starting from index i=0 to i<n. If arr[i]==arr[i+1]. Increment count. Store element in variable value.
At the end of loop increment count by 1 for the last element.
At the end of loop increment count by 1 for the last element.
Display element which is repeated as value.
Display element which is repeated as value.
Display number of repetitions as count.
Display number of repetitions as count.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void findRepeat(int arr[],int n){
   int count=0; //count of repeated element
   int value=0; //to store repeated element
   for(int i=0;i<n;i++){
      if(arr[i]==arr[i+1]){
         count++;
         value=arr[i];
      }
   }
   count++; //for last element
   cout<<"Repeated Element: "<<value;
   cout<<endl<<"Number of occurrences: "<<count;
}
int main(){
   int Arr[]={ 2,3,4,5,5,5,6,7,8 };
   int len=sizeof(Arr)/sizeof(Arr[0]);
   findRepeat(Arr,len);
   return 0;
}
If we run the above code it will generate the following output −
Repeated Element: 5
Number of occurrences: 3
Convert Date to XMLGregorianCalendar in Java

30 Jun, 2021
XML Gregorian Calendar: The rules for specifying dates in XML format are defined in the XML Schema standard. The Java XMLGregorianCalendar class, introduced in Java 1.5, is a representation of the W3C XML Schema 1.0 date/time datatypes and is required to use the XML format. 
In this approach, we have first changed the standard date to Gregorian Calendar date format and then changed it to XML Gregorian Date using the DatatypeFactory(). newInstance method which creates new javax.xml.datatype Objects that map XML to/from Java Objects.
Code:
Java
// Java program to Convert Date to XMLGregorianCalendar // importing necessary packagesimport java.util.Date;import java.util.GregorianCalendar;import javax.xml.datatype.DatatypeFactory;import javax.xml.datatype.XMLGregorianCalendar; public class DateToXMLGregorianCalendar {     public static void main(String[] args)    {         // Create Date Object        Date current_date = new Date();         // current date time in standard format        System.out.println("Standard Format :- "                           + current_date);         XMLGregorianCalendar xmlDate = null;         // Gregorian Calendar object creation        GregorianCalendar gc = new GregorianCalendar();         // giving current date and time to gc        gc.setTime(current_date);         try {            xmlDate = DatatypeFactory.newInstance()                          .newXMLGregorianCalendar(gc);        }        catch (Exception e) {            e.printStackTrace();        }         // current date time in XMLGregorain Calendar format        System.out.println("XMLGregorianCalendar Format :- "                           + xmlDate);    }}
  
Standard Format :- Tue Feb 16 17:44:25 UTC 2021
XMLGregorianCalendar Format :- 2021-02-16T17:44:25.164Z
 
arorakashish0911
Java-Date-Time
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Empty String to None Conversion

30 Jan, 2020
Sometimes, while working with Machine Learning, we can encounter empty strings and we wish to convert to the None for data consistency. This and many other utilities can require the solution to this problem. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using lambdaThis task can be performed using the lambda function. In this we check for string for None or empty string using the or operator and replace the empty string with None.
# Python3 code to demonstrate working of# Empty String to None Conversion# Using lambda  # initializing list of stringstest_list = ["Geeks", '', "CS", '', '']  # printing original list print("The original list is : " + str(test_list))  # using lambda# Empty String to None Conversionconv = lambda i : i or Noneres = [conv(i) for i in test_list]  # printing result print("The list after conversion of Empty Strings : " + str(res))
The original list is : ['Geeks', '', 'CS', '', '']
The list after conversion of Empty Strings : ['Geeks', None, 'CS', None, None]

 
Method #2 : Using str()Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.
# Python3 code to demonstrate working of# Empty String to None Conversion# Using str()  # initializing list of stringstest_list = ["Geeks", '', "CS", '', '']  # printing original list print("The original list is : " + str(test_list))  # using str()# Empty String to None Conversionres = [str(i or None) for i in test_list]  # printing result print("The list after conversion of Empty Strings : " + str(res))
The original list is : ['Geeks', '', 'CS', '', '']
The list after conversion of Empty Strings : ['Geeks', None, 'CS', None, None]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Deque in Python
Python program to convert a list to string
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
How to select an element by its class name in AngularJS ?

14 Oct, 2020
Given an HTML document and the task is to select an element by its className using AngularJS.
Approach: The approach is to use the document.querySelector() method to get the element of a particular className. In the first example the element of className class1 is selected and its background color is changed to green. In the second example, 2 elements of same class are selected and some of the CSS is changed.
Example 1:
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.getClass = function () {                var el = angular.element(                    document.querySelector(".class1"));                el.css('background', 'green');            };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to select an element by        its class in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            <p class="class1">                This is GeeksForGeeks            </p>            <input type="button"                 value="click here"                 ng-click="getClass()">        </div>    </div></body>  </html>     
Output:
Example 2:
<!DOCTYPE HTML><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">    </script>      <script>        var myApp = angular.module("app", []);        myApp.controller("controller", function ($scope) {            $scope.getClass = function () {                var el = angular.element(                    document.querySelectorAll(".class1"));                  el.css({                     'background': 'green',                     'color': 'white'                 });            };        });    </script></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksForGeeks    </h1>    <p>        How to select an element by         its class in AngularJS    </p>    <div ng-app="app">        <div ng-controller="controller">            <p class="class1">                This is GeeksForGeeks            </p>            <p class="class1">                A computer science portal            </p>            <input type="button"                 value="click here"                 ng-click="getClass()">        </div>    </div></body>  </html>    
Output:
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
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
Moment.js isMoment() Function

29 Jul, 2020
It is used to check whether a variable is a particular moment or not in Moment.js using the isMoment() function that checks if a variable is a moment object, use moment.isMoment().
Syntax:
moment.isMoment(obj);
Parameter: Object
Returns: True or False
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
// Requiring moduleconst moment = require('moment');  var bool2 = moment.isMoment(new Date()); // falseconsole.log(bool2);  var bool3 = moment.isMoment(moment()); // trueconsole.log(bool3);
Steps to run the program:
The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false
true

The project structure will look like this:
Make sure you have installed moment module using the following command:npm install moment
npm install moment
Run index.js file using below command:node index.jsOutput:false
true

node index.js
Output:
false
true

Example 2: Filename: index.js
// Requiring moduleconst moment = require('moment');  function checkMoment(data){   return moment.isMoment(data);}  var bool = checkMoment(moment());console.log(bool);
Run index.js file using below command:
node index.js
Output:
true

Reference: https://momentjs.com/docs/#/query/is-a-moment/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
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 ?
Differences between Functional Components and Class Components in React
Stack setSize() method in Java with Example

24 Dec, 2018
The setSize() method of Java.util.Stack class changes the size of this Stack instance to the size passed as the parameter.
Syntax:
public void setSize(int size)
Parameters: This method takes the new size as a parameter.
Exception: This method throws ArrayIndexOutOfBoundsException if the new size is negative.
Below are the examples to illustrate the setSize() method.
Example 1:
// Java program to demonstrate// setSize() method for Integer value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)    {          try {              // Creating object of Stack<Integer>            Stack<Integer>                stack = new Stack<Integer>();              // adding element to stack            stack.add(10);            stack.add(20);            stack.add(30);            stack.add(40);              // Print the Stack            System.out.println("Stack: " + stack);              // Print the current size of Stack            System.out.println("Current size of Stack: "                               + stack.size());              // Change the size to 10            stack.setSize(10);              // Print the current size of Stack            System.out.println("New size of Stack: "                               + stack.size());        }          catch (Exception e) {            System.out.println("Exception thrown : " + e);        }    }}
Stack: [10, 20, 30, 40]
Current size of Stack: 4
New size of Stack: 10

Example 2:
// Java program to demonstrate// setSize() method for String value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)    {          try {              // Creating object of Stack<Integer>            Stack<String>                stack = new Stack<String>();              // adding element to stack            stack.add("A");            stack.add("B");            stack.add("C");            stack.add("D");              // Print the Stack            System.out.println("Stack: "                               + stack);              // Print the current size of Stack            System.out.println("Current size of Stack: "                               + stack.size());              // Change the size to -1            stack.setSize(-1);              // Print the current size of Stack            System.out.println("New size of Stack: "                               + stack.size());        }          catch (Exception e) {            System.out.println("Exception thrown : " + e);        }    }}
Stack: [A, B, C, D]
Current size of Stack: 4
Exception thrown : java.lang.ArrayIndexOutOfBoundsException: -1

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Python program to find the sum of Characters ascii values in String List

11 Dec, 2020
Given the string list, the task is to write a Python program to compute the summation value of each character’s ASCII value.
Examples:
Input : test_list = [“geeksforgeeks”, “teaches”, “discipline”] Output : [133, 61, 100] Explanation : Positional character summed to get required values.
Input : test_list = [“geeksforgeeks”, “discipline”] Output : [133, 100] Explanation : Positional character summed to get required values. 
Method 1 : Using ord() + loop
In this, we iterate each character in each string and keep on adding positional values to get its sum. The summed value is appended back to the result in a list.
Python3
# Python3 code to demonstrate working of # Characters Positions Summation in String List# Using ord() + loop  # initializing listtest_list = ["geeksforgeeks",             "teaches", "us", "discipline"]  # printing original listprint("The original list is : " + str(test_list))  res = []for sub in test_list:    ascii_sum = 0          # getting ascii value sum     for ele in sub :        ascii_sum += (ord(ele) - 96)              res.append(ascii_sum)  # printing result print("Position Summation List : " + str(res))
Output:
The original list is : [‘geeksforgeeks’, ‘teaches’, ‘us’, ‘discipline’]Position Summation List : [133, 61, 40, 100]
Method 2 : Using list comprehension + sum() + ord()
In this, we get summation using sum(), ord() is used to get the ASCII positional value, and list comprehension offers one-liner solution to this problem.
Python3
# Python3 code to demonstrate working of # Characters Positional Summation in String List# Using list comprehension + sum() + ord()  # initializing listtest_list = ["geeksforgeeks", "teaches",              "us", "discipline"]  # printing original listprint("The original list is : " + str(test_list))  # sum() gets summation, list comprehension# used to perform task in one line res = [sum([ord(ele) - 96 for ele in sub]) for sub in test_list]  # printing result print("Positional Summation List : " + str(res))
 Output:
The original list is : [‘geeksforgeeks’, ‘teaches’, ‘us’, ‘discipline’]Position Summation List : [133, 61, 40, 100]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the powers of an array values element-wise in Python-Pandas?

18 Aug, 2020
Let’s see how to get the powers of an array values element-wise. Dataframe/Series.pow() is used to calculate the power of elements either with itself or with other Series provided. This function is applicable for real numbers only, and doesn’t give results for complex numbers. So let’s see the programs:
Example 1: The uni-dimensional arrays are mapped to a pandas series with either default numeric indices or custom indexes Then corresponding elements are raised to its own power. 
Python3
# import required modulesimport numpy as npimport pandas as pd   # create an arraysample_array = np.array([1, 2, 3])    # uni dimensional arrays can be# mapped to pandas seriessr = pd.Series(sample_array)   print ("Original Array :")print (sr)  # calculating element-wise power power_array = sr.pow(sr)  print ("Element-wise power array")print (power_array)
Output:
Example 2: Powers can also be computed for floating-point decimal numbers. 
Python3
# module to work with arrays in pythonimport array  # module required to compute powerimport pandas as pd  # creating a 1-dimensional floating # point array containing three elementssample_array = array.array('d',                            [1.1, 2.0, 3.5])    # uni dimensional arrays can # be mapped to pandas seriessr = pd.Series(sample_array)   print ("Original Array :")print (sr)  # computing power of each # element with itself power_array = sr.pow(sr)  print ("Element-wise power array")print (power_array)
Output:
Example 3: The Multi-dimensional arrays can be mapped to pandas data frames. The data frame then contains each cell comprising a numeric (integer or floating-point numbers) which can be raised to its own individual powers. 
Python3
# module to work with # arrays in pythonimport array  # module required to # compute powerimport pandas as pd  # 2-d matrix containing # 2 rows and 3 columnsdf = pd.DataFrame({'X': [1,2],                   'Y': [3,4],                   'Z': [5,6]});  print ("Original Array :")print(df)  # power function to calculate# power of data frame elements# with itselfpower_array = df.pow(df)  print ("Element-wise power array")print (power_array)
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sqoop - Export

This chapter describes how to export data back from the HDFS to the RDBMS database. The target table must exist in the target database. The files which are given as input to the Sqoop contain records, which are called rows in table. Those are read and parsed into a set of records and delimited with user-specified delimiter.
The default operation is to insert all the record from the input files to the database table using the INSERT statement. In update mode, Sqoop generates the UPDATE statement that replaces the existing record into the database.
The following is the syntax for the export command.
$ sqoop export (generic-args) (export-args) 
$ sqoop-export (generic-args) (export-args)
Let us take an example of the employee data in file, in HDFS. The employee data is available in emp_data file in ‘emp/’ directory in HDFS. The emp_data is as follows.
1201, gopal,     manager, 50000, TP
1202, manisha,   preader, 50000, TP
1203, kalil,     php dev, 30000, AC
1204, prasanth,  php dev, 30000, AC
1205, kranthi,   admin,   20000, TP
1206, satish p,  grp des, 20000, GR

It is mandatory that the table to be exported is created manually and is present in the database from where it has to be exported.
The following query is used to create the table ‘employee’ in mysql command line.
$ mysql
mysql> USE db;
mysql> CREATE TABLE employee ( 
   id INT NOT NULL PRIMARY KEY, 
   name VARCHAR(20), 
   deg VARCHAR(20),
   salary INT,
   dept VARCHAR(10));
The following command is used to export the table data (which is in emp_data file on HDFS) to the employee table in db database of Mysql database server.
$ sqoop export \
--connect jdbc:mysql://localhost/db \
--username root \
--table employee \ 
--export-dir /emp/emp_data
The following command is used to verify the table in mysql command line.
mysql>select * from employee;
If the given data is stored successfully, then you can find the following table of given employee data.
+------+--------------+-------------+-------------------+--------+
| Id   | Name         | Designation | Salary            | Dept   |
+------+--------------+-------------+-------------------+--------+
| 1201 | gopal        | manager     | 50000             | TP     |
| 1202 | manisha      | preader     | 50000             | TP     |
| 1203 | kalil        | php dev     | 30000             | AC     |
| 1204 | prasanth     | php dev     | 30000             | AC     |
| 1205 | kranthi      | admin       | 20000             | TP     |
| 1206 | satish p     | grp des     | 20000             | GR     |
How to declare a variable in Python without assigning a value to it?

Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement that assigns None to the variable. 
my_var = None
If you use this, you'll never end up with an uninitialized variable. But this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful when you use it.
HTML <body> bgcolor Attribute

06 Jan, 2022
The HTML <body> bgcolor Attribute is used to define a Background color of a Document.
Note: It is not supported by HTML5
Syntax:
<body bgcolor="color_name | hex_number | rgb_number">
Attribute Values:
color_name: It specifies the name of the Background color of the Document.
hex_number: It specifies the hex code of the Background color in the Document.
rgb_number: It specifies the rgb value of the Background color in the Document
Example: In this example, we simply set the bg color of the body to green.
HTML
<!DOCTYPE html><html><!-- body tag starts here -->  <body bgcolor="green">    <h2>GeeksforGeeks</h2>      <p> It is a Computer Science portal For Geeks </p>  </body><!-- body tag ends here -->  </html>
Output:
 HTML <body> bgcolor Attribute 
Example: This example describes the  HTML <body> bgcolor Attribute by specifying the text as green & background as orange color.
HTML
<!DOCTYPE html><html>  <head>    <title> HTML body Bgcolor Attribute </title></head><!-- body tag starts here -->  <body text="green" bgcolor="orange">    <center>        <h1>GeeksforGeeks</h1>        <h2>      HTML <body> bgcolor Attribute    </h2>          <p> It is a Computer Science portal For Geeks </p>      </center></body><!-- body tag ends here -->  </html>
Output:
 HTML <body> bgcolor Attribute 
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Microsoft Edge
ManasChhabra2
shubhamyadav4
bhaskargeeksforgeeks
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Python | Generate random string of given length

22 May, 2019
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let’s discuss certain ways in which this can be performed.
Method #1 : Using random.choices()
This function of random module can help us achieve this task, and provides a one liner alternative to a whole loop that might be required for this particular task. Works with Python > v3.6 .
# Python3 code to demonstrate# generating random strings # using random.choices()import stringimport random  # initializing size of string N = 7  # using random.choices()# generating random strings res = ''.join(random.choices(string.ascii_uppercase +                             string.digits, k = N))  # print resultprint("The generated random string : " + str(res))
The generated random string : 0D5YE91

 
Method #2 : Using secrets.choice()
For Cryptographically more secure random numbers, this function of secret module can be used as it’s internal algorithm is framed in a way to generate less predictable random numbers. Works with Python > v3.6 .
# Python3 code to demonstrate# generating random strings # using secrets.choice()import secretsimport string  # initializing size of string N = 7  # using random.choices()# generating random strings res = ''.join(secrets.choice(string.ascii_uppercase + string.digits)                                                  for i in range(N))  # print resultprint("The generated random string : " + str(res))
The generated random string : T7HPKVR

Python string-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Machine Learning - Scatter Matrix Plot

Scatter plots shows how much one variable is affected by another or the relationship between them with the help of dots in two dimensions. Scatter plots are very much like line graphs in the concept that they use horizontal and vertical axes to plot data points.
In the following example, Python script will generate and plot Scatter matrix for the Pima Indian Diabetes dataset. It can be generated with the help of scatter_matrix() function on Pandas DataFrame and plotted with the help of pyplot.
from matplotlib import pyplot
from pandas import read_csv
from pandas.tools.plotting import scatter_matrix
path = r"C:\pima-indians-diabetes.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = names)
Matcher matches() method in Java with Examples

26 Nov, 2018
The matches() method of Matcher Class is used to get the result whether this pattern matches with this matcher or not. It returns a boolean value showing the same.
Syntax:
public boolean matches()

Parameters: This method do not takes any parameter.
Return Value: This method returns a boolean value showing whether this pattern matches with this matcher or not.
Below examples illustrate the Matcher.matches() method:
Example 1:
// Java code to illustrate matches() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "Geeks";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the result state        // using matches() method        System.out.println("Result: "                           + matcher.matches());    }}
Result: false

Example 2:
// Java code to illustrate matches() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "GFG";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the result state        // using matches() method        System.out.println("Result: "                           + matcher.matches());    }}
Result: false

Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logger getLevel() method in Java with Examples

19 Mar, 2019
The getLevel() method of the Logger class in Java is used to get the log Level that has been specified for this Logger instance. Every Logger has specific log levels and if the result is null, which means that this logger’s effective level will be inherited from its parent.
Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging
Syntax:
public Level getLevel()

Parameters: This method accepts no parameters.
Return value: This method returns Level which represents level of logger.
Below programs illustrate the getLevel() method:Program 1:
// Java program to demonstrate// Logger.getLevel() method  import java.util.logging.Logger;import java.util.logging.Level;  public class GFG {      public static void main(String[] args)    {          // Create a Logger        Logger logger            = Logger.getLogger(                GFG.class.getName());          // Get level of logger        Level level            = logger.getLevel();          // If logger level is null        // then take a level of the parent of logger          if (level == null && logger.getParent() != null) {            level = logger.getParent().getLevel();        }          System.out.println("Logger Level = " + level);    }}
Logger Level = INFO

Program 2:
// Java program to demonstrate// Logger.getLevel() method  import java.util.logging.Logger;import java.util.logging.Level;import java.util.*;  public class GFG {      public static void main(String[] args)    {          // Create a Logger        Logger logger            = Logger.getLogger(                ArrayList.class.getName());          // Get level of logger        Level level = logger.getLevel();          System.out.println("Logger Level = "                           + level);    }}
Logger Level = null

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLevel()
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the purpose of “role” attribute in HTML ?

18 Nov, 2019
The main purpose of role attribute is to bolster ARIA i.e. Accessible Rich Internet Applications which helps in providing richness and quality from semantic perspective. Moreover, role attribute makes a website more facilitative and using this attribute is considered as a good practice. Generally, the role is necessary for languages which do not define their own role attribute.
Example:
<!DOCTYPE><html lang="en">  <head>    <meta charset="utf-8">    <title>        Output of Role Attribute    </title>    <style>        h1 {            text-align: center;            color: green;            font-size: 100px;        }                  h2 {            text-align: center;        }    </style></head>  <body role="document">    <h1>GeeksforGeeks</h1>    <h2>Understanding usage of "Role" Attribute</h2></body>  </html>
Output:
Output obtained for role attribute
The output doesn’t show any significant thing to notice. This shows that even if the role attribute is not used in the code, then also it won’t affect our code and output.
By using role attributes, we get to avail features like accessibility, device adaptation, server-side processing, complex data description, and many more such features. Thus role attribute is advised to be used for getting better performance of the code.
HTML-Attributes
HTML-Misc
HTML5
Picked
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB - Drop Collection

In this chapter, we will see how to drop a collection using MongoDB.
MongoDB's db.collection.drop() is used to drop a collection from the database.
Basic syntax of drop() command is as follows −
db.COLLECTION_NAME.drop()

First, check the available collections into your database mydb.
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection.
>db.mycollection.drop()
true
>
Again check the list of collections into database.
>show collections
mycol
system.indexes
tutorialspoint
>
drop() method will return true, if the selected collection is dropped successfully, otherwise it will return false.
Creating a User With an Expiry Date in Linux

22 Jun, 2020
Linux is a multi-user system and thus, it allows more than one person to interact with the system at the same time. There are numerous ways in which we can create new users in Linux. The system administrator has the responsibility to manage different users of the system.  For types of users in Linux refer Users in Linux System Administration. 
User accounts with an expiration date provide a facility to create a user account for temporary use. Let’s discuss how to create a user with an expiry date in Linux. 
Syntax: 
$ sudo useradd -e YYYY-MM-DD username

In the above command:
useradd is a command used to add a new user account. 
-e YYYY-MM-DD specifies the expiry date for a new user account. 
Let us create a new user with Username: Test and Expiry Date: June 10 2020.In order to create a new user execute the following command in terminal. 
sudo useradd -e 2020-06-10 Test

In order to login as a newly created user, a password needs to set up. Thus, we use paswd command. To set a new password execute the following command in the terminal. 
sudo passwd Test

Once the command executes a prompt will ask to set a new password.  
To verify the user account expiration details we can use chage command.To get the details, execute the following command in the terminal.  
sudo chage -l Test

Thus, in this way, we can create a new user account with an expiration date. 
linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
GATE | GATE-IT-2004 | Question 74 - GeeksforGeeks

15 Oct, 2019
Insert into department values (1, 'Mathematics')
Insert into department values (2, 'Physics')
Insert into student values (l, 'Navin', 1)
Insert into student values (2, 'Mukesh', 2)
Insert into student values (3, 'Gita', 1) 
How many rows and columns will be retrieved by the following SQL statement?
Select * from student, department
(A) 0 row and 4 columns(B) 3 rows and 4 columns(C) 3 rows and 5 columns(D) 6 rows and 5 columnsAnswer: (D)Explanation: Simple,Cartesian product of two tables will result
Rows = 3*2 = 6 
Columns = 3+2 = 5 
Option (D) is correct.
 Quiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Interview Oracle India | Set 24 (For 5 Years Experienced) - GeeksforGeeks

24 Mar, 2018
Round 1:
First round was multiple choice question based on Core Java on inheritance, exception handling, type erasure, threading etc.
Round 2:
Second round was coding round and the questions asked to me to code was as follows –
Priyanka works for an international toy company that ships by container. Her task is to the determine the lowest cost way to combine her orders for shipping.
She has a list of item weights. The shipping company has a requirement that all items loaded in a container must weigh less than or equal to 4 units plus the weight of the minimum weight item. All items meeting that requirement will be shipped in one container.
What is the smallest number of containers that can be contracted to ship the items based on the given list of weights?
Input Format
The first line contains an integer , the number of orders to ship.Next line will contain  integers,  , representing the orders in a weight array.
Output Format
Return the integer value of the number of containers Priyanka must contract ot ship all of the toys.
Constraints
Sample Input
8
1 2 3 21 7 12 14 21

Sample Output
4
Round 3:
This round was face to face . He asked me questions on
1.hibernate(versioning, many to one mapping etc..)
2.code matrix problem . A 2n+1 (odd) size square matrix is given . We have to check if the centre element is equal to the individual sum of all the half diagonals in only ONE for loop . For example –
5*5 matrix –
M =   2   9   1   4   -2
6   7   2   11   4
4    2  9  2   4
1   9   2    4   4
0   2   4   2   5
 
Sum of Half Diagonal 1 = 2+7=9
Sum of Half Diagonal 2 = 9+0=9
Sum of Half Diagonal 3 = 11 + -2 = 9
Sum of Half Diagonal 4 = 5+4 = 9
All the sums equal to the centre element that is M [2][2]=9, Hence return true or if any on of the sums of half diagonals doesnt match to the centre element, return false.
 
3. a puzzle to find a defective ball amongst a collection of balls
4. A way to synchronise booking of same seat on bookmyshow without using synchronisation like locks .
Round 4:
Design Round – Asked me to design a online retail System like Amazon taking into account the Customer, the Seller, the logistics and asked me to come up with database tables .
Round 5 :
Managerial Round –
He asked me few questions on my previous projects, nature of work that i have done, few behavioural questions and one coding question.
 
Oracle
Experienced
Interview Experiences
Oracle
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced)
Amazon Interview Experience for System Development Engineer (Exp - 6 months)
FactSet Interview Experience (Off-Campus) 8 Months Experienced
JP Morgan Chase Interview Questions
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Python math library | isclose() method - GeeksforGeeks

22 May, 2019
In Python math module, math.isclose() method is used to determine whether two floating point numbers are close in value. For using this function you must import math module.
Syntax: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0)
Parameters:rel_tol: maximum difference for being considered “close”, relative to the magnitude of the input valuesabs_tol: maximum difference for being considered “close”, regardless of the magnitude of the input values
-> rel_tol and abs_tol can be changed by using keyword argument, or by simply providing directly as according to their positions in the parameter list.
Return Value : Return True if a is close in value to b, and False otherwise.
Note: For the values to be considered close, the difference between them must be smaller than at least one of the tolerances.
Code #1:
# Importing Math moduleimport math  # printing whether two values are close or notprint(math.isclose(2.005, 2.005))print(math.isclose(2.005, 2.004))print(math.isclose(2.006, 2.005))
Output:
True
False
False

 Code #2:
# Importing Math moduleimport math  # printing whether two values are close or notprint(math.isclose(2.005, 2.125, abs_tol = 0.25))print(math.isclose(2.547, 2.0048, abs_tol = 0.5))print(math.isclose(2.0214, 2.00214, abs_tol = 0.02))
Output:
True
False
True

You can change absolute tolerance, as in above case absolute tolerance is different in all three cases.
Reference: Python math library
Python math-library-functions
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 configure node.js console font ? - GeeksforGeeks

27 Feb, 2020
You can format the console font in Node.js using the CHALK module. The chalk module is can be used to customize node console. By using it, one can change console look using features of it like bold the text, making underlines, highlighting the background color of a text, etc.
Features of Chalk module:
It’s easy to get started and easy to use.
It is widely used and popular module for formatting the text.
Users can format the console text very easily.
Installing Chalk module and using It:
You can visit the link Install Chalk module to install this package using command.$ npm install --save chalk
$ npm install --save chalk
After installing chalk module you can check your chalk version on command prompt by using the following command.npm version chalk
npm version chalk
After that, you can just create a folder and add a file for example app.js. To run this file you need to execute command.$ node app.js
$ node app.js
Requiring module: You need to include the chalk module in your file using these lines.var chalk = require('chalk');
var chalk = require('chalk');
Filename: app.js// Include chalk modulevar chalk = require('chalk')  // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks'));  // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks'));  // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks'));
// Include chalk modulevar chalk = require('chalk')  // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks'));  // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks'));  // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks'));
Steps to run the program:
The project structure will look like this:
Run app.js file using following commands:node app.js
node app.js
Node.js-Misc
Picked
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Export Module
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Writing to an excel sheet using Python

29 Jul, 2019
Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work.
Let’s see how to create and write to an excel-sheet using Python. 
# Writing to an excel # sheet using Pythonimport xlwtfrom xlwt import Workbook  # Workbook is createdwb = Workbook()  # add_sheet is used to create sheet.sheet1 = wb.add_sheet('Sheet 1')  sheet1.write(1, 0, 'ISBT DEHRADUN')sheet1.write(2, 0, 'SHASTRADHARA')sheet1.write(3, 0, 'CLEMEN TOWN')sheet1.write(4, 0, 'RAJPUR ROAD')sheet1.write(5, 0, 'CLOCK TOWER')sheet1.write(0, 1, 'ISBT DEHRADUN')sheet1.write(0, 2, 'SHASTRADHARA')sheet1.write(0, 3, 'CLEMEN TOWN')sheet1.write(0, 4, 'RAJPUR ROAD')sheet1.write(0, 5, 'CLOCK TOWER')  wb.save('xlwt example.xls')
Output : 
# importing xlwt moduleimport xlwt  workbook = xlwt.Workbook()   sheet = workbook.add_sheet("Sheet Name")  # Specifying stylestyle = xlwt.easyxf('font: bold 1')  # Specifying columnsheet.write(0, 0, 'SAMPLE', style)workbook.save("sample.xls")
Output : Code #3 : Adding multiple styles to a cell
# importing xlwt moduleimport xlwt  workbook = xlwt.Workbook()   sheet = workbook.add_sheet("Sheet Name")  # Applying multiple stylesstyle = xlwt.easyxf('font: bold 1, color red;')  # Writing on specified sheetsheet.write(0, 0, 'SAMPLE', style)  workbook.save("sample.xls")
Output :
shubham_singh
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON