code-rag-bench/online-tutorials huggingface dataset:
java.time.LocalDate.until() Method Example

The java.time.LocalDate.until(Temporal endExclusive, TemporalUnit unit) method calculates the amount of time until another date in terms of the specified unit.
Following is the declaration for java.time.LocalDate.until(Temporal endExclusive, TemporalUnit unit) method.
public long until(Temporal endExclusive, TemporalUnit unit)

endDateExclusive − the end date, exclusive, which is converted to a LocalDate, not null.
endDateExclusive − the end date, exclusive, which is converted to a LocalDate, not null.
unit − the unit to measure the amount in, not null.
unit − the unit to measure the amount in, not null.
the amount of time between this date and the end date.
DateTimeException − if the amount cannot be calculated, or the end temporal cannot be converted to a LocalDate.
DateTimeException − if the amount cannot be calculated, or the end temporal cannot be converted to a LocalDate.
UnsupportedTemporalTypeException − if the unit is not supported.
UnsupportedTemporalTypeException − if the unit is not supported.
ArithmeticException − if numeric overflow occurs.
ArithmeticException − if numeric overflow occurs.
The following example shows the usage of java.time.LocalDate.until(Temporal endExclusive, TemporalUnit unit) method.
package com.tutorialspoint;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class LocalDateDemo {
   public static void main(String[] args) {
	  LocalDate date = LocalDate.parse("2017-01-03");
      LocalDate date1 = LocalDate.now();
      System.out.println(date.until(date1, ChronoUnit.DAYS));  
   }
}
Let us compile and run the above program, this will produce the following result −
343

 Print
 Add Notes
 Bookmark this page
Python Pandas – Find the Difference between two Dataframes

To find the difference between two DataFrame, you need to check for its equality. Also, check the equality of columns.
Let us create DataFrame1 with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)
Create DataFrame2 with two columns −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)


Check for the equality of a specific column “Units” −
dataFrame2['Units'].equals(dataFrame1['Units'])
Check for equality of both the DataFrames −
Are both the DataFrames equal?",dataFrame1.equals(dataFrame2)

Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"\nDataFrame2 ...\n",dataFrame2


# check for specific column Units equality
print"\nBoth the DataFrames have similar Units column? ",dataFrame2['Units'].equals(dataFrame1['Units'])

# check for equality
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame2 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

Both the DataFrames have similar Units column? True

Are both the DataFrames equal? True
How to plot 2D math vectors with Matplotlib?

To plot 2D math vectors with matplotlib, we can take the following steps−
Create vector cordinates using numpy array.
Get x, y, u and v data points.
Create a new figure or activate an existing figure using figure method.
Get the current axis using gca() method.
Set x an y limits of the axes.
To redraw the current figure, use draw() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
soa = np.array([[0, 0, 3, 2], [0, 0, 4, 5], [0, 0, 9, 9]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color=['red', 'green', 'yellow'])
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
plt.draw()
plt.show()
PostgreSQL – Insert Data Into a Table using Python

30 Aug, 2020
In this article we will look into the process of inserting data into a PostgreSQL Table using Python. To do so follow the below steps:
Step 1: Connect to the PostgreSQL database using the connect() method of psycopg2 module.
conn = psycopg2.connect(dsn)

Step 2:  Create a new cursor object by making a call to the cursor() method
cur = conn.cursor()

Step 3: Now execute the INSERT statement by running the execute() method
cur.execute(sql, (value1,value2))

Step 4: After inserting the data call the commit() method to make the changes permanent.
conn.commit()

Step 5: Now terminate the cursor and the connection to the database.
cur.close()
conn.close()

Example:
For example we will use the Student table of the school database that we created in the earlier sections of the article series.
Here we will create a insert_student() function to insert student_name row to the student table:
Python3
#!/usr/bin/python  import psycopg2from config import config    def insert_student(student_name):    """ insert a new vendor into the vendors table """    sql = """INSERT INTO students(student_name)             VALUES(%s) RETURNING student_id;"""    conn = None    student_id = None    try:        # read database configuration        params = config()        # connect to the PostgreSQL database        conn = psycopg2.connect(**params)        # create a new cursor        cur = conn.cursor()        # execute the INSERT statement        cur.execute(sql, (student_name,))        # get the generated id back        student_id = cur.fetchone()[0]        # commit the changes to the database        conn.commit()        # close communication with the database        cur.close()    except (Exception, psycopg2.DatabaseError) as error:        print(error)    finally:        if conn is not None:            conn.close()      return student_id
Now to verify the insertion use the following command in the psql shell:
SELECT * FROM student;

Output:
postgreSQL-managing-table
PostgreSQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if two strings are anagram of each other using C++

Let’s Suppose we have given two strings ‘a’ and ‘b. We have to check that the given two strings are anagram of each other or not. Two Strings are said to be anagram of each other if one string contains the same character as another.
For Example
Input-1 −
a= anagram
b= gnarama
Output −
True
Explanation − String ‘gnarama’ has the same character as String ‘anagram’ has. Hence we return True.
Input-2 −
a= programmer
b= mprogretmrqp
Output −
False
Explanation − String ‘b’ has more characters than the string ‘a’ and thus we can say that the length of the string is different. Thus we return False.
For given two strings we have the length of the string if the length of the string is different we will return False. Otherwise, if the length of the string is the same then we will check if each character of that string matches with the characters of another string and return True otherwise False.
Take Input two strings ‘a’ and ‘b’
Take Input two strings ‘a’ and ‘b’
A Boolean function checkAnagram(string a, string b) takes two strings ‘a’ and string ‘b’ and returns whether they are anagram of each other or not.
A Boolean function checkAnagram(string a, string b) takes two strings ‘a’ and string ‘b’ and returns whether they are anagram of each other or not.
Find the length of the string ‘a’ and ‘b’ and check if they are equal or not. If they are not equal then return false.
Find the length of the string ‘a’ and ‘b’ and check if they are equal or not. If they are not equal then return false.
Using C++ STL(Standard Template Library) map function, create a hash table of each character of string ‘a’ by iterating over the string ‘a’.
Using C++ STL(Standard Template Library) map function, create a hash table of each character of string ‘a’ by iterating over the string ‘a’.
While creating a map of each character of string ‘a’ remove those characters which are present in string ‘b’.
While creating a map of each character of string ‘a’ remove those characters which are present in string ‘b’.
Then Iterate over the map and check If there are any characters left in the hash table and return False otherwise return True.
Then Iterate over the map and check If there are any characters left in the hash table and return False otherwise return True.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
bool checkAnagram(string a, string b){
   int len1= a.length();
   int len2= b.length();
   if(len1!= len2) {
      return false;
   }
   unordered_map <char,int> mp;
   for(int i=0;i<a.size();i++) {
      mp[a[i]]++;
      mp[b[i]]--;
   }
   for(auto it:mp){
      if(it.second) return false;
   }
   return true;
}
int main(){
   string a= "anagram";
   string b= "gnarama";
   cout<< checkAnagram(a,b)<<endl;
   return 0;
}
If we will run the above code then it will print the output as,
1
Since Both the Input string are anagram of each other hence it returns True i.e ‘1’
ggplot2 - Bar Plots & Histograms

Bar plots represent the categorical data in rectangular manner. The bars can be plotted vertically and horizontally. The heights or lengths are proportional to the values represented in graphs. The x and y axes of bar plots specify the category which is included in specific data set.
Histogram is a bar graph which represents the raw data with clear picture of distribution of mentioned data set.
In this chapter, we will focus on creation of bar plots and histograms with the help of ggplot2.
Let us understand the dataset which will be used. Mpg dataset contains a subset of the fuel economy data that the EPA makes available in the below link −
http://fueleconomy.gov
It consists of models which had a new release every year between 1999 and 2008. This was used as a proxy for the popularity of the car.
Following command is executed to understand the list of attributes which is needed for dataset.
> library(ggplot2)

The attaching package is ggplot2.
The following object is masked _by_ .GlobalEnv −
mpg

package arules was built under R version 3.5.1
package tuneR was built under R version 3.5.3
package ggplot2 was built under R version 3.5.3
The Bar Count plot can be created with below mentioned plot −
> # A bar count plot
> p <- ggplot(mpg, aes(x=factor(cyl)))+
+    geom_bar(stat="count")
> p

geom_bar() is the function which is used for creating bar plots. It takes the attribute of statistical value called count.
The histogram count plot can be created with below mentioned plot −
> # A historgram count plot
> ggplot(data=mpg, aes(x=hwy)) +
+    geom_histogram( col="red",
+       fill="green",
+       alpha = .2,
+       binwidth = 5)

geom_histogram() includes all the necessary attributes for creating a histogram. Here, it takes the attribute of hwy with respective count. The color is taken as per the requirements.
The general plots of bar graphs and histogram can be created as below −
> p <- ggplot(mpg, aes(class))
> p + geom_bar()
> p + geom_bar()

This plot includes all the categories defined in bar graphs with respective class. This plot is called stacked graph.
 Print
 Add Notes
 Bookmark this page
Group buttons on a single line with Bootstrap

Use the .btn-group class in Bootstrap to group buttons on a single like.
You can try to run the following code to implement .btn-group class in Bootstrap:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are the car brands:</p>
      <div class = "btn-group">
         <button type = "button" class = "btn btn-default">BMW</button>
         <button type = "button" class = "btn btn-default">Audi</button>
         <button type = "button" class = "btn btn-default">Jeep</button>
         <button type = "button" class = "btn btn-default">Datsun</button>
         <button type = "button" class = "btn btn-default">Toyota</button>
         <button type = "button" class = "btn btn-default">Mahindra</button>
      </div>
   </body>
</html>
How to use Get-ChildItem in PowerShell to filter a specific extension?

To get the output of the get-childitem with a specific extension, we need to use –includeparameter.
In the below example, we will use the below script to get only .xml files.
Get-ChildItem D:\Temp\ -Recurse -Include *.xml
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Include *.xml
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34           6215 Backup.xml
-a----       24-11-2018     11:34            602 Bkupinfo.xml
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       07-05-2018     23:00            301 cars.xml
You can filter multiple extensions with include parameter and for that, you need to add a comma (,) between extensions.
For example, we will get the output here with file extensions xml and csv.
Get-ChildItem D:\Temp\ -Recurse -Include *.xml, *.csv
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Include *.xml, *.csv
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\DomainSysvol\GPO\Machine\microsoft\windows
    nt\Audit
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34           6234 audit.csv
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34           6215 Backup.xml
-a----       24-11-2018     11:34            602 Bkupinfo.xml
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       07-05-2018     23:00            301 cars.xml
-a----       25-10-2017     08:13            104 testcsv.csv
How to get odd and even position characters from a string?

We have to write a function that removes every second character (starting from the very first
character) from a string and appends all of those removed characters at the end in JavaScript.
For example −
If the string is "This is a test!"
Then it should become "hsi etTi sats!"
Therefore, let’s write the code for this function −
const string = 'This is a test!';
const separateString = (str) => {
   const { first, second } = [...str].reduce((acc, val, ind) => {
      const { first, second } = acc;
      return {
         first: ind % 2 === 1 ? first+val : first,
         second: ind % 2 === 0 ? second+val : second
      };
   }, {
      first: '',
      second: ''
   })
   return first+second;
};
console.log(separateString(string));
The output in the console will be −
hsi etTi sats!
How to update existing data in EEPROM with Arduino?

Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data.
In this article, we will see how to update existing data in the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from: File → Examples → EEPROM.
We will look at the eeprom_update example. You essentially use the EEPROM.update() function. The EEPROM.update() function is different from EEPROM.write() in the sense that it will overwrite the value in the EEPROM only if the new value is different from what is already stored at that address. Why? Because each EEPROM has a limited number of write cycles (~100,000) per address. If we keep overwriting the same value at any address location, we reduce the lifespan of the EEPROM.
We begin with the inclusion of the library.
#include <EEPROM.h>
Next, we define a global variable for the address. Nothing happens in the setup.
int address = 0;
void setup() {
   /** EMpty setup **/
}
Within the loop, we read values from an analog input (A0 in this case), and write it to the EEPROM using the .update() function. We then increment the address and repeat this. If we reach the end of the EEPROM's length, we go back to the beginning (addr = 0).
Note that we are dividing the analog read output by 4, because a byte can only have values from 0 to 255, whereas analogRead() output values range from 0 to 1023.
void loop() {
   int val = analogRead(A0) / 4;
   EEPROM.update(address, val);
   /***
      The function EEPROM.update(address, val) is equivalent to the following:
      if( EEPROM.read(address) != val ){
         EEPROM.write(address, val);
      }
   ***/
   address = address + 1;
   if (address == EEPROM.length()) {
      address = 0;
   }
   delay(100);
}
As is mentioned in the comments, the .update() function is equivalent to reading the EEPROM at that address, and writing to it only if the new value is different from the read value.
How to find the critical value of F for one-way ANOVA in R?

To find the critical value of F for one-way ANOVA in R, we can follow the below steps −
First of all, create a data frame with one categorical and one numerical column.
Then, use aov function to find the anova table.
After that, use qf function to find the critical value of F for one-way ANOVA.
Let's create a data frame as shown below −
 Live Demo
Grp<-sample(LETTERS[1:4],20,replace=TRUE)
Score<-rnorm(20)
df<-data.frame(Grp,Score)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
   Grp   Score
1  B    1.75508031
2  D   -1.43867197
3  B   -0.18409783
4  C   -1.72435769
5  C   -0.95996448
6  B    0.19776077
7  B    0.52247374
8  C   -1.28337249
9  C   -0.63236147
10 B    0.93966870
11 B    0.23925102
12 B    0.86565239
13 B    0.07353123
14 A   -0.62096596
15 A    -1.76680335
16 A    0.12203536
17 B    0.66276852
18 D    -0.50199349
19 A    -1.30960082
20 D    -1.32413279
Using aov function and summary function to find the anova table −
 Live Demo
Grp<-sample(LETTERS[1:4],20,replace=TRUE)
Score<-rnorm(20)
df<-data.frame(Grp,Score)
ANOVA<-aov(Score~Grp,data=df)
ANOVA<-summary(ANOVA)
ANOVA
           Df Sum    Sq   Mean Sq F value Pr(>F)
Grp        3  12.870 4.29 11.6 0.000274 ***
Residuals 16  5.917 0.37
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Using qf function to find the critical value of F for one-way ANOVA −
 Live Demo
Grp<-sample(LETTERS[1:4],20,replace=TRUE)
Score<-rnorm(20)
df<-data.frame(Grp,Score)
ANOVA<-aov(Score~Grp,data=df)
ANOVA<-summary(ANOVA)
qf(1-0.05,ANOVA[[1]][1,1],ANOVA[[1]][2,1])
[1] 3.238872
Print all Jumping Numbers smaller than or equal to a given value in C++

In this problem, we are given a number n and we have to print all jumping numbers that are smaller than or equal to n.
Jumping Numbers are the number whose adjacent digits differ by one only. Some jumping numbers are 4565, 98, 7. All single-digit numbers are considered as jumping numbers. 235 is not a jumping number.
Now, let’ take an example to understand the problem
Input: N = 32
Output: 0 1 2 3 4 5 6 7 8 9 10 12 21 23 32
To solve this problem, we will assume a graph where 0 is the starting node and traverse it to all reachable nodes. You can traverse it using BFS or DFS. This graph is created using a condition that makes values jumping numbers.
The below code implements our solution −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void traverse(int N, int num) {
   queue<int> q;
   q.push(num);
   while (!q.empty()) {
      num = q.front();
      q.pop();
      if (num <= N) {
         cout << num << " ";
         int last_dig = num % 10;
         if (last_dig == 0)
            q.push((num * 10) + (last_dig + 1));
         else if (last_dig == 9)
            q.push((num * 10) + (last_dig - 1));
         else {
            q.push((num * 10) + (last_dig - 1));
            q.push((num * 10) + (last_dig + 1));
         }
      }
   }
}
void printJumpingNumber(int N) {
   cout<<0<<" ";
   for (int i = 1; i <= 9 && i <= N; i++)
   traverse(N, i);
}
int main() {
   int N = 54;
   cout<<"Jumping Numbers less than "<<N<<" are :\n";
   printJumpingNumber(N);
   return 0;
}
Jumping Numbers less than 54 are −
0 1 10 12 2 21 23 3 32 34 4 43 45 5 54 6 7 8 9
JSF - f:convertNumber

f:convertNumber tag is used to convert a string value to a number of required format.
<f:convertNumber minFractionDigits = "2" />

type
number (default), currency, or percent
pattern
Formatting pattern, as defined in java.text.DecimalFormat
maxFractionDigits
Maximum number of digits in the fractional part
minFractionDigits
Minimum number of digits in the fractional part
maxIntegerDigits
Maximum number of digits in the integer part
minIntegerDigits
Minimum number of digits in the integer part
integerOnly
True, if only the integer part is parsed (default: false)
groupingUsed
True, if grouping separators are used (default: true)
locale
Locale whose preferences are to be used for parsing and formatting
currencyCode
ISO 4217 currency code to use when converting currency values
currencySymbol
Currency symbol to use when converting currency values
Let us create a test JSF application to test the above tag.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:f = "http://java.sun.com/jsf/core">
   
   <h:head>
      <title>JSF tutorial</title>			
   </h:head>
   
   <h:body>
      <h2>ConvertNumber Example</h2>
      <table border = "1" cellspacing = "2" cellpadding = "2">
         <tr>
            <th>Parameter</th>
            <th>Value Passed</th>
            <th>Output</th>
         </tr>
         
         <tr>
            <td>minFractionDigits = "2"</td>
            <td>100.12345</td>
            <td>
               <h:outputText value = "100.12345" >
                  <f:convertNumber minFractionDigits = "2" />
               </h:outputText>
            </td>
         </tr>
         
         <tr>
            <td>pattern = "#000.000"</td>
            <td>100.12345</td>
            <td>
               <h:outputText value = "100.12345" >
                  <f:convertNumber pattern = "#000.000" />
               </h:outputText>
            </td>
         </tr>
         
         <tr>
            <td>currencySymbol = "$"</td>
            <td>$100</td>
            <td>
               <h:outputText value = "$100">
                  <f:convertNumber currencySymbol = "$" type = "currency" />
               </h:outputText>
            </td>
         </tr>
         
         <tr>
            <td>type = "percent"</td><td>100.12345%</td>
            <td>
               <h:outputText value = "100.12345%" >
                  <f:convertNumber type = "percent" />
               </h:outputText>
            </td>
         </tr>
      </table>
   
   </h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
remainder() in C++ program

In this article, we will be discussing the working, syntax, and examples of remainder() function in C++.
remainder() function is an inbuilt function in C++ STL, which is defined in <cmath> header file. remainder() is used to find the remainder of the parameters.
This function takes two arguments, one for the numerator and second for the and computes its
remainder and returns a floating-point which is rounded to the nearest.
This function computes −
remainder = numerator – roundquot * denominator;
In which “remainder” is the resulting numerator being the first argument and denominator is the
second argument and roundquot is the rounded off (toward the even number) result of
numerator/denominator.
This function is similar to the fmod function which rounds of the quotient towards zero.
double remainder(double numerator, double denominator);
The function accepts the following parameter(s) −
numerator − The value of quotient’s numerator.
numerator − The value of quotient’s numerator.
denominator − Quotient’s denominator.
denominator − Quotient’s denominator.
This function returns the remainder of numerator and denominator if the numerator is zero the function will also return zero. When the denominator is zero either the function returns zero or gives a domain error.
Input 
remainder(51, 5);
Output 
1
 Live Demo
#include <cmath>
#include <iostream>
using namespace std;
int main(){
   int numerator = 51;
   int denominator = 5, remainder_ans;
   remainder_ans = remainder(numerator, denominator);
   cout<<"Value of Remainder is " <<numerator << "/" << denominator << " is: " << remainder_ans << endl;
   return 0;
}
If we run the above code it will generate the following output −
Value of Remainder is 51/5 is: 1
//when the denominator is 0 output will be −
 Live Demo
#include <cmath>
#include <iostream>
using namespace std;
int main(){
   int numerator = 51;
   int denominator = 0, remainder_ans;
   remainder_ans = remainder(numerator, denominator);
   cout<<"Value of Remainder is " << numerator << "/" << denominator << " is: " <<
   remainder_ans << endl;
   return 0;
}
If we run the above code it will generate the following output −
Value of Remainder is 51/0 is: -2147483648 //garbage value
Determining how many digits there are in an integer in C++

Here we will see how to check how many digits are there in an integer in C++. At first we will see the traditional rule, then see one short method to find.
In the first method, we will reduce the number using dividing it by 10. And count until the number reaches to 0.
#include <iostream>
using namespace std;
int count_digit(int number) {
   int count = 0;
   while(number != 0) {
      number = number / 10;
      count++;
   }
   return count;
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}
Number of digits in 1245: 4
Now, we will see the shorter method. In this method we will use the log base 10 function to get the result. The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.
#include <iostream>
#include <cmath>
using namespace std;
int count_digit(int number) {
   return int(log10(number) + 1);
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}
Number of digits in 1245: 4
C# Program to get the difference between two dates in seconds

Set two dates.
DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20);
DateTime date2 = new DateTime(2018, 7, 15, 11, 14, 25);
Now calculate the difference between two dates.
TimeSpan ts = date2 - date1;
Move further and calculate the difference in seconds.
ts.TotalSeconds
Let us see the complete code.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20);
      DateTime date2 = new DateTime(2018, 7, 15, 11, 14, 25);
      TimeSpan ts = date2 - date1;
      Console.WriteLine("No. of Seconds (Difference) = {0}", ts.TotalSeconds);
   }
}
No. of Seconds (Difference) = 10745
Can we extend an enum in Java?

No, we cannot extend
an enum in Java. Java enums can extend java.lang.Enum class implicitly, so enum types cannot extend another class.
public abstract class Enum> implements Comparable, Serializable {
   // some statements
}
An Enum type is a special data type which is added in Java 1.5 version.
An Enum is used to define a collection of constants, when we need a predefined list of values which do not represent some kind of numeric or textual data, we can use an enum.
Enums are constants and by default, they are static and final. so the names of an enum type fields are in uppercase letters.
Public or protected modifiers can only be used with a top-level enum declaration, but all access modifiers can be used with nested enum declarations.
Live Demo
enum Country {
   US {
      public String getCurrency() {
         return "DOLLAR";
      }
   }, RUSSIA {
      public String getCurrency() {
         return "RUBLE";
      }
   }, INDIA {
      public String getCurrency() {
         return "RUPEE";
      }
   };
   public abstract String getCurrency();
}
public class ListCurrencyTest {
   public static void main(String[] args) {
      for (Country country : Country.values()) {
         System.out.println(country.getCurrency() + " is the currecny of " + country.name());
      }
   }
}
DOLLAR is the currecny of US
RUBLE is the currecny of RUSSIA
RUPEE is the currecny of INDIA
Apache POI Word - Borders

In this chapter, you will learn how to apply border to a paragraph using Java programming.
The following code is used to apply Borders in a Document −
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.Borders;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class ApplyingBorder {

   public static void main(String[] args)throws Exception {

      //Blank Document
      XWPFDocument document = new XWPFDocument(); 
        
      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File("applyingborder.docx"));
        
      //create paragraph
      XWPFParagraph paragraph = document.createParagraph();
        
      //Set bottom border to paragraph
      paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        
      //Set left border to paragraph
      paragraph.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        
      //Set right border to paragraph
      paragraph.setBorderRight(Borders.BASIC_BLACK_DASHES);
        
      //Set top border to paragraph
      paragraph.setBorderTop(Borders.BASIC_BLACK_DASHES);
        
      XWPFRun run = paragraph.createRun();
         run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming " +
         "Languages.");
        
      document.write(out);
      out.close();
      System.out.println("applyingborder.docx written successully");
   }
}
Save the above code in a file named ApplyingBorder.java, compile and execute it from the command prompt as follows −
$javac ApplyingBorder.java
$java ApplyingBorder

If your system is configured with the POI library, then it will compile and execute to generate a Word document named applyingborder.docx in your current directory and display the following output −
applyingborder.docx written successfully

The applyingborder.docx file looks as follows −

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
What are pointer data types in C#?

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. Similar to any variable or constant, you must declare a pointer before you can use it to store any variable address.
The syntax of a pointer is −
type *var-name;
The following is how you can declare a pointer type −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.
Here is the module showing how to declare and use a pointer variable. We have used unsafe modifier here −
static unsafe void Main(string[] args) {
   int var = 20;
   int* p = &var;
   
   Console.WriteLine("Data is: {0} ", var);
   Console.WriteLine("Address is: {0}", (int)p);
   Console.ReadKey();
}
Python Program for GCD of more than two (or array) numbers

30 Nov, 2018
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.
gcd(a, b, c) = gcd(a, gcd(b, c)) 
             = gcd(gcd(a, b), c) 
             = gcd(gcd(a, c), b)

# GCD of more than two (or array) numbers# This function implements the Euclidian # algorithm to find H.C.F. of two number  def find_gcd(x, y):    while(y):        x, y = y, x % y      return x            l = [2, 4, 6, 8, 16]  num1=l[0]num2=l[1]gcd=find_gcd(num1,num2)  for i in range(2,len(l)):    gcd=find_gcd(gcd,l[i])      print(gcd)  # Code contributed by Mohit Gupta_OMG
Output:
2

Please refer complete article on GCD of more than two (or array) numbers for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Regular Expressions in Julia

25 Aug, 2020
Julia has Perl-compatible regular expressions (regexes), as provided by the PCRE library. Regular expressions can be used to find regular patterns in strings and in Julia regular expressions are themselves input as strings which are parsed into a state machine that can be used to efficiently search for patterns in strings. 
In Julia, regular expressions are input using non-standard string literals prefixed with various identifiers beginning with r. The most basic regular expression literal without any options turned on just uses r”...”. The r”...” literal is constructed without interpolation and unescaping.
Julia
myregex = r"^\s*(?:#|$)" typeof(myregex)
Regex 

Use of different characters(regex tokens) while writing a Regular Expression :
match() is an inbuilt function in Julia which is used to search for the first match of the given regular expression in the specified string.
Syntax:
match(r::Regex, s::AbstractString, idx::Integer)

Parameters:
r::Regex: Specified regular expression.
s::AbstractString: Specified string.
idx::Integer: It specifies the point from which the searching get started.

Returns: It returns a RegexMatch object containing the match or nothing if the match failed.

Julia
# example 1:myregex = r"^\s*(?:#|$)" println(match(myregex, "# a comment"))  # example 2:println(match(myregex, "not a comment"))  # example 3:email_pattern = r".+@.+"input = "Harshit@GeeksforGeeks.com"println(match(email_pattern, input))
The Regex() constructor may be used to create a valid regex string programmatically. This permits using the contents of string variables and other string operations when constructing the regex string.
Julia
name = "Jon"regex_name = Regex("[\"( ]$name[\") ]")  # interpolate value of nameprintln(match(regex_name, " Jon "))println(match(regex_name, "[Jon]") === nothing)
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Python Programs | Set 19 (Strings)

03 Aug, 2021
1) What is the output of the following program?  
PYTHON3
str1 = '{2}, {1} and {0}'.format('a', 'b', 'c')str2 = '{0}{1}{0}'.format('abra', 'cad')print(str1, str2)
a) c, b and a abracad0 b) a, b and c abracadabra c) a, b and c abracadcad d) c, b and a abracadabra Ans. (d) Explanation: String function format takes a format string and an arbitrary set of positional and keyword arguments. For str1 ‘a’ has index 2, ‘b’ index 1 and ‘c’ index 0. str2 has only two indices 0 and 1. Index 0 is used twice at 1st and 3rd time.2) What is the output of the following program?  
PYTHON3
a = 2b = '3.77'c = -8str1 = '{0:.4f} {0:3d} {2} {1}'.format(a, b, c)print(str1)
a) 2.0000 2 -8 3.77 b) 2 3.77 -8 3.77 c) 2.000 3 -8 3.77 d) 2.000 2 8 3.77 Ans. (a) Explanation: At Index 0, integer a is formatted into a float with 4 decimal points, thus 2.0000. At Index 0, a = 2 is formatted into a integer, thus it remains to 2. Index 2 and 1 values are picked next, which are -8 and 3.77 respectively.3) What is the output of the following program?  
PYTHON3
import string Line1 = "And Then There Were None"Line2 = "Famous In Love"Line3 = "Famous Were The Kol And Klaus"Line4 = Line1 + Line2 + Line3print("And" in Line4)
a) True 2 b) True c) False d) False 2 Ans. (b) Explanation: The “in” operator returns True if the strings contains the substring (ie, And), else returns False. 4) What is the output of the following program?  
PYTHON3
line = "I'll come by then."eline = ""for i in line:    eline += chr(ord(i)+3)print(eline)   
a) L*oo frph e| wkhq1 b) L*oo#frph#e|#wkhq1 c) l*oo@frph@e|$wkhq1 d) O*oo#Frph#E|#wKhq1 Ans. (b) Explanation: This piece of code ciphers the plain text. Each character is moved to its 3rd next character by increasing the ascii value. ‘I’ becomes ‘L’, thus option (c) and (d) are ruled out. ‘ ‘ has ascii value of 32, thus it’ll become 35(‘#’), thus option (a) is ruled out as, ‘ ‘ can not remain to be ‘ ‘ in the ciphered text.5) What is the output of the following program?  
PYTHON3
line =  "What will have so will"L = line.split('a')for i in L:    print(i, end=' ')
a) [‘What’, ‘will’, ‘have’, ‘so’, ‘will’] b) Wh t will h ve so will c) What will have so will d) [‘Wh’, ‘t will h’, ‘ve so will’] Ans. (b) Explanation: split() will use ‘a’ as the delimiter. It’ll create partition at ‘a’, thus split() return an array L, which is in [‘Wh’, ‘t will h’, ‘ve so will’]. For loop will print the elements of the list.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nidhi_biet
kk9826225
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.tight_layout() in Python

11 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
Sample Code
# sample codeimport matplotlib.pyplot as plt     plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() 
Output:
The tight_layout() function in pyplot module of matplotlib library is used to automatically adjust subplot parameters to give specified padding.
Syntax: matplotlib.pyplot.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)
Parameters: This method accept the following parameters that are described below:
pad: This parameter is used for padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad, w_pad: These parameter are used for padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
rect: This parameter is rectangle in the normalized figure coordinate that the whole subplots area will fit into.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.tight_layout() function in matplotlib.pyplot :
Example-1:
import numpy as npimport matplotlib.pyplot as plt  fig, axs = plt.subplots(1, 2)  x = np.arange(0.0, 2.0, 0.02)y1 = np.sin(2 * np.pi * x)y2 = np.exp(-x)l1, = axs[0].plot(x, y1)l2, = axs[0].plot(x, y2, marker ='o')  y3 = np.sin(4 * np.pi * x)y4 = np.exp(-2 * x)l3, = axs[1].plot(x, y3, color ='tab:green')l4, = axs[1].plot(x, y4, color ='tab:red', marker ='o')  fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')    fig.suptitle('matplotlib.pyplot.tight_layout() Example')plt.tight_layout()plt.show()
Output:
Example-2:
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter  prng = np.random.RandomState(19680801)  xs = np.logspace(1, 9, 100)ys = (0.8 + 0.4 * prng.uniform(size = 100)) * np.log10(xs)**2  plt.xscale('log')  formatter0 = EngFormatter(unit ='Hz')plt.plot(xs, ys)plt.xlabel('Frequency')  plt.title('matplotlib.pyplot.tight_layout() Example')plt.tight_layout()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find the Nth term of series 5, 12, 21, 32, 45......

25 May, 2022
Given a number N, The task is to write a program to find the Nth term of the below series:  
5, 12, 21, 32, 45......  
Examples:  
Input: N = 2
Output: 12

Input: N = 5
Output: 45
 
Approach: The generalized Nth term of this series:  
Nth Term : n*n + 4*n  
Below is the required implementation:  
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find// the N-th term of the series:// 5, 12, 21, 32, 45...... #include <iostream>#include <math.h>using namespace std; // calculate Nth term of seriesint nthTerm(int n){    return pow(n, 2) + 4 * n;} // Driver codeint main(){     // Get N    int N = 4;     // Get the Nth term    cout << nthTerm(N) << endl;     return 0;}
// C program to find// the N-th term of the series:// 5, 12, 21, 32, 45......#include <stdio.h>#include <math.h> // calculate Nth term of seriesint nthTerm(int n){    return pow(n, 2) + 4 * n;} // Driver codeint main(){     // Get N    int N = 4;     // Get the Nth term    printf("%d\n",nthTerm(N));     return 0;} // This code is contributed by kothavvsaakash.
// Java  program to find// the N-th term of the series:// 5, 12, 21, 32, 45......import java.io.*; class GFG {       // calculate Nth term of seriesstatic int nthTerm(int n){    return (int)Math.pow(n, 2) + 4 * n;} // Driver code     public static void main (String[] args) {         // Get N    int N = 4;     // Get the Nth term    System.out.println( nthTerm(N));     }}// This code is contributed// by  inder_verma
# Python3 program to find# the N-th term of the series:# 5, 12, 21, 32, 45...... # calculate Nth term of seriesdef nthTerm(n):    return n ** 2 + 4 * n; # Driver code # Get NN = 4 # Get the Nth termprint(nthTerm(N)) # This code is contributed by Raj
// C# program to find the// N-th term of the series:// 5, 12, 21, 32, 45......using System; class GFG{     // calculate Nth term of seriesstatic int nthTerm(int n){    return (int)Math.Pow(n, 2) + 4 * n;} // Driver codepublic static void Main (){     // Get N    int N = 4;         // Get the Nth term    Console.WriteLine(nthTerm(N));}} // This code is contributed// by sh..
<?php// PHP program to find// the N-th term of the series:// 5, 12, 21, 32, 45...... // calculate Nth term of seriesfunction nthTerm($n){    return pow($n, 2) + 4 * $n;} // Driver code$N = 4; // Get the Nth termecho nthTerm($N); // This code is contributed// by Mahadev99?>
<script>// JavaScript program to find// the N-th term of the series:// 5, 12, 21, 32, 45......  // calculate Nth term of seriesfunction nthTerm( n){    return Math.pow(n, 2) + 4 * n;} // Driver code    // Get N    let N = 4;     // Get the Nth term    document.write( nthTerm(N)); // This code is contributed by todaysgaurav </script>
32
 
Mahadev99
inderDuMCA
vt_m
R_Raj
todaysgaurav
kothavvsaakash
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read multiple CSV files into separate DataFrames in Python

05 May, 2022
In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one data frame we can use pd.read_csv() function of pandas. It takes a path as input and returns data frame like 
df = pd.read_csv("file path")
Let’s have a look at how it works
Python3
# import moduleimport pandas as pd # read datasetdf = pd.read_csv("./csv/crime.csv")
  
Here, crime.csv is the file in the current folder. CSV is the folder that contains the crime.csv file and CSV Reader.ipynb is the file containing the above code.
 
Output:
 
 
It is the data frame that is read from the above function. One more file is present in the folder named – username.csv. To read them both and store them in different data frames use the below code
 
Python3
# import moduleimport pandas as pd # assign dataset nameslist_of_names = ['crime','username'] # create empty listdataframes_list = [] # append datasets into the listfor i in range(len(list_of_names)):    temp_df = pd.read_csv("./csv/"+list_of_names[i]+".csv")    dataframes_list.append(temp_df)
dataframes_list contains all the data frames separately.
dataframes_list[0]:
dataframes_list[1]:
Here is another approach, now suppose that there are many files, and we don’t know the names and number then, use the below code
Python3
# import modulesimport osimport pandas as pd # assign pathpath, dirs, files = next(os.walk("./csv/"))file_count = len(files)# create empty listdataframes_list = [] # append datasets to the listfor i in range(file_count):    temp_df = pd.read_csv("./csv/"+files[i])    dataframes_list.append(temp_df)     # display datasetsfor dataset in dataframes_list:    display(dataset)
  
Output:
 
 
abhishek0719kadiyan
surinderdawra388
Picked
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.
Java Program for Binary Search (Recursive)

Following is the program for Recursive Binary Search in Java −
 Live Demo
public class Demo{
   int rec_bin_search(int my_arr[], int left, int right, int x){
      if (right >= left){
         int mid = left + (right - left) / 2;
         if (my_arr[mid] == x)
         return mid;
         if (my_arr[mid] > x)
         return rec_bin_search(my_arr, left, mid - 1, x);
         return rec_bin_search(my_arr, mid + 1, right, x);
      }
      return -1;
   }
   public static void main(String args[]){
      Demo my_object = new Demo();
      int my_arr[] = { 56, 78, 90, 32, 45, 99, 104};
      int len = my_arr.length;
      int x = 104;
      int result = my_object.rec_bin_search(my_arr, 0, len - 1, x);
      if (result == -1)
         System.out.println("The element is not present in the array");
      else
         System.out.println("The element has been found at index " + result);
   }
}
The element has been found at index 6
A class named Demo contains the binary search function, that takes the left right and value that needs to be searched. Once the binary search is implemented, a main function creates an instance of the Demo object and assigns values to an array. This binary search function is called on the array by passing a specific value to search as a parameter. If found, the index is displayed, otherwise, a relevant message is displayed.