code-rag-bench/online-tutorials huggingface dataset:
Create database in Cassandra - GeeksforGeeks

28 Apr, 2020
In this article, we are going to discuss how to create the database in Cassandra. so, for better understanding you can read “Introduction to Cassandra” article before creating a database in Cassandra.
Step-1: login into cqlshyou can log in into the cqlsh using Cassandra default credential. Now, here before creating a database you first need login into cqlsh. you can check the cluster information after login into cqlsh.let’s have a look.
cqlsh 127.0.0.1 -u cassandra -p cassandra 
Step-2: Creating a databaseCreating a keyspace in Cassandra is the same as creating a database in SQL. CQL query for creating a keyspace as following.
Syntax: 

CREATE  KEYSPACE [IF NOT EXISTS] keyspace_name                
   WITH REPLICATION = {replication_map}
   [AND DURABLE_WRITES =  true|false] ; 
Here’s an example that shows how to create a keyspace named App_data:
you must read replication strategy in Cassandra for better understanding.
Replication Strategy : NetworkTopologyStrategy
cqlsh> CREATE KEYSPACE IF NOT EXISTS App_data
       WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy',
       'datacenter1' : 3, 'datacenter2': 2 }; 
Now, here you must check If there are no errors, the database is created, or not then You can run the describe keyspaces command to ascertain that the database did indeed create the keyspace.
To check the all keyspaces which are already created then you can run the following CQL query given below.
cqlsh> describe keyspaces; 
To check the App_data keyspaces is created or not then you can run the following CQL query given below.
cqlsh> describe App_data; 
Output:
cassandra@cqlsh> describe keyspaces;

university   system    backup_copy     system_traces  system_schema
system_auth  app_data  system_distributed  operation 
In Cassandra, IF NOT EXISTS part is optional but it is always good practice using such statements because it helps avoid an error should the keyspace cycling already exist.
Step-3: Describing the keyspaceIn Cassandra, A keyspace is a defining container for replication. Now, You can see the new keyspace App_data in the list of keyspaces shown by the database.
Now, to check the details about App_data keyspace, you can execute the describe App_data command.
describe App_data; 
Output:
cassandra@cqlsh> describe App_data;

CREATE KEYSPACE app_data WITH 
replication = {'class': 'NetworkTopologyStrategy', 
               'datacenter1': '3', 'datacenter2': '2'}  
AND durable_writes = true; 
NoSQL
DBMS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
Introduction of ER Model
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
How to Load the Content of a Google Document in Python | by Angelica Lo Duca | Towards Data Science

It may happen that you have a document stored as a Google Doc in Google Drive and you want to load its content dynamically into a Python pandas DataFrame for further processing.
First of all, you need to access the Google Cloud Platform and create a new project, say MyProject. Then you must select the created project in the main dashboard and select explore and enable APIs. You can search for Google Docs API and you can click on Enable API. Once enabled, you should create new credentials.
You can select Google Doc API and check the User Data, as shown in the image below.
You can follow the wizard and complete the creation of credentials. In the section 4 OAuth Client ID, you can choose Desktop app as Application type.
Now you can download the created secret and rename it into credentials.json. Put this file in the same directory where you will write your Python code.
Now you can download and copy the code of the official Google Doc API documentation, which permits you to download the content of a Google Doc document. Make sure that you have the rights to read the Google Doc!!!
Once you’ve extracted the text, you can save it into a local file and then convert into a DataFrame for further analysis. You will store each line of the text as a new row in the DataFrame. Let’s suppose that you have stored the text of the Google Doc into a variable called text.
doc_content = body.get('content')text = read_strucutural_elements(doc_content)
Now, you can save it into a local file:
with open("my_doc.txt", "w") as text_file:    text_file.write(text)
and then you can reload the file and convert it to a DataFrame:
import pandas as pdwith open('my_doc.txt', 'r') as f:    text = [line for line in f.readlines()]df = pd.DataFrame(text,columns=['text'])
Eventually, you are ready to work with your data! Enjoy it!
In this tutorial, I have illustrated how to load a text from a Google Doc document through the official Google Doc API and convert it into a Python pandas DataFrame.
The procedure is simple, but it requires some important steps, including the configuration of the credentials used to access the Google Doc API.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube, and Github.
XSD - Numeric Data Types

Numeric data types are used to represent numbers in XML documents.
The <xs:decimal> data type is used to represent numeric values. It supports decimal numbers up to 18 digits.
Element declaration in XSD −
<xs:element name = "score" type = "xs:decimal"/>

Element usage in XML −
<score>9.12</score>

The <xs:integer> data type is used to represent integer values.
Element declaration in XSD −
<xs:element name = "score" type = "xs:integer"/>

Element usage in XML −
<score>9</score>

Following is the list of commonly used numeric data types.
byte
A signed 8 bit integer
decimal
A decimal value
int
A signed 32 bit integer
integer
An integer value
long
A signed 64 bit integer
negativeInteger
An integer having only negative values (..,-2,-1)
nonNegativeInteger
An integer having only non-negative values (0,1,2,..)
nonPositiveInteger
An integer having only non-positive values (..,-2,-1,0)
positiveInteger
An integer having only positive values (1,2,..)
short
A signed 16 bit integer
unsignedLong
An unsigned 64 bit integer
unsignedInt
An unsigned 32 bit integer
unsignedShort
An unsigned 16 bit integer
unsignedByte
An unsigned 8 bit integer
Following types of restrictions can be used with Date data types −
enumeration
fractionDigits
maxExclusive
maxInclusive
minExclusive
minInclusive
pattern
totalDigits
whiteSpace
 Print
 Add Notes
 Bookmark this page
Minimax Algorithm in Game Theory (Alpha-Beta Pruning) in C++

Aplha-Beta pruning is a optimization technique used in minimax algorithm. The idea benind this algorithm is cut off the branches of game tree which need not to be evaluated as better move exists already.
This algorithm introduces two new fields −
Alpha − This is best value(maximum) that maximizer player can guaratee at current level or its above level
Beta − This is the best value(minimum) that minimizer player can guaratee at the current level or its above level.
If game tree is −
arr [] = {13, 8, 24, -5, 23, 15, -14, -20}
then optimal value will be 13 if maximizer plays first
1. Start DFS traversal from the root of game tree
2. Set initial values of alpha and beta as follows:
a. alpha = INT_MIN(-INFINITY)
b. beta = INT_MAX(+INFINITY)
3. Traverse tree in DFS fashion where maximizer player tries to get the highest score possible while the minimizer player tries to get the lowest score possible.
4. While traversing update the alpha and beta values accordingly
#include <iostream>
#include <algorithm>
#include <cmath>
#include <climits>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int getHeight(int n) {
   return (n == 1) ? 0 : 1 + log2(n / 2);
}
int minmax(int height, int depth, int nodeIndex,
bool maxPayer, int values[], int alpha,
int beta) {
   if (depth == height) {
      return values[nodeIndex];
   }
   if (maxPayer) {
      int bestValue = INT_MIN;
      for (int i = 0; i < height - 1; i++) {
         int val = minmax(height, depth + 1, nodeIndex * 2 + i, false, values, alpha, beta);
         bestValue = max(bestValue, val);
         alpha = max(alpha, bestValue);
         if (beta <= alpha)
            break;
      }
      return bestValue;
   } else {
      int bestValue = INT_MAX;
      for (int i = 0; i < height - 1; i++) {
         int val = minmax(height, depth + 1, nodeIndex * 2 + i, true, values, alpha, beta);
         bestValue = min(bestValue, val);
         beta = min(beta, bestValue);
         if (beta <= alpha)
            break;
      }
      return bestValue;
   }
}
int main() {
   int values[] = {13, 8, 24, -5, 23, 15, -14, -20};
   int height = getHeight(SIZE(values));
   int result = minmax(height, 0, 0, true, values, INT_MIN, INT_MAX);
   cout <<"Result : " << result << "\n";
   return 0;
}
When you compile and execute above program. It generates
following output −
Result : 13
Detecting contours in an image using OpenCV

In this program, we will detect contours in an image. Contours can be explained simply as a curve joining all the continuous points having the same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
Step 1: Import OpenCV.
Step 2: Import matplotlib.
Step 3: Read the image.
Step 4: Convert the image from bgr2rgb.
Step 5: Convert the rgb image to grayscale.
Step 4: Perform thresholding on the image.
Step 5: Find contours on the image.
Step 6: Draw contours on the image.
Step 7: Display the output.
import cv2
import matplotlib.pyplot as plt

image = cv2.imread('testimage.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, binary = cv2.threshold(gray, 127,255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

image = cv2.drawContours(image, contours, -1, (0,255,0), 2)
plt.imshow(image)
plt.show()
Difference between volatile and transient in java

A volatile keyword is used in a multithreading environment where two threads reading and writing the same variable simultaneously. The volatile keyword flushes the changes directly to the main memory instead of the CPU cache. 
On the other hand, the transient keyword is used during serialization. Fields that are marked as transient can not be part of the serialization and deserialization. We don't want to save the value of any variable then we use transient keyword with that variable. 
// A sample class that uses transient keyword to
// skip their serialization.
class TransientExample implements Serializable {
   transient int age;
   // serialize other fields
   private String name;
   private String address;
   // other code
}
class VolatileExmaple extends Thread{
   boolean volatile isRunning = true;
   public void run() {
      long count=0;
      while (isRunning) {
         count++;
      }
      System.out.println("Thread terminated." + count);
   }
   public static void main(String[] args) throws InterruptedException {
      VolatileExmaple t = new VolatileExmaple();
      t.start();
      Thread.sleep(2000);
      t.isRunning = false;
      t.join();
      System.out.println("isRunning set to " + t.isRunning);
   }
}
Goal Seek in Excel - GeeksforGeeks

15 May, 2021
Goal Seek is a tool available in MS EXCEL to determine or calculate any input value based on the formula and the output/resultant value. 
To find the Goal seek : 
Go to Data Tab in MS EXCEL.In the Data Tools group, you will find a What-if analysis.Click on What if analysis, and you will find Goal seek.
Go to Data Tab in MS EXCEL.
In the Data Tools group, you will find a What-if analysis.
Click on What if analysis, and you will find Goal seek.
Goal seek dialogue box has three parts:
Set cell: In this, we write the reference of the cell which contains the formula.To value: In this, we write the value which we want to attain(or the given resultant value).By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated).
Set cell: In this, we write the reference of the cell which contains the formula.
To value: In this, we write the value which we want to attain(or the given resultant value).
By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated).
For example, we need to calculate the rate of interest when the time period, principal amount, and the simple interest are already known.
Given : Principle amount = 2000
        Time = 3 years 
        Simple interest = 6000
Follow the below steps to use Goal seek functionality in Excel:
Open the MS EXCEL and insert the values.
Write the formula of simple interest in any one cell (B4).
Open the Goal seek dialogue box.
In the Set Cell box select the cell which contains the formula of simple interest (B4).
In the To Value box write the resultant value of the simple interest i.e. 6000 (Given in question).
In the By Changing Cell write the reference of the cell in which you want the rate of interest value (B3).
Click OK.
The Rate of interest value is calculated in the cell (B3).
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
Calculating Areas Of Different Shapes Using Python - GeeksforGeeks

07 Jul, 2021
We are going to make a Python program for Calculating Areas Of some mathematical Shapes.
Example:
Input: shape name = "Rectangle"
       length = 10
       breadth = 15
Output: Area: 150

Input: shape name = "Square"
       side = 10
Output: Area: 100
Approach:
In this program, We will ask the user to input the shape’s name. If it exists in our program then we will proceed to find the entered shape’s area according to their respective formulas. If that shape doesn’t exist then we will print “Sorry! We cannot find this shape.” message on the screen.
Below is the implementation:
Python3
# define a function for calculating# the area of a shapesdef calculate_area(name):\     # converting all characters  # into lower cases  name = name.lower()     # check for the conditions  if name == "rectangle":    l = int(input("Enter rectangle's length: "))    b = int(input("Enter rectangle's breadth: "))         # calculate area of rectangle    rect_area = l * b    print(f"The area of rectangle is          {rect_area}.")     elif name == "square":    s = int(input("Enter square's side length: "))           # calculate area of square    sqt_area = s * s    print(f"The area of square is          {sqt_area}.")   elif name == "triangle":    h = int(input("Enter triangle's height length: "))    b = int(input("Enter triangle's breadth length: "))           # calculate area of triangle    tri_area = 0.5 * b * h    print(f"The area of triangle is          {tri_area}.")   elif name == "circle":    r = int(input("Enter circle's radius length: "))    pi = 3.14             # calculate area of circle    circ_area = pi * r * r    print(f"The area of triangle is          {circ_area}.")           elif name == 'parallelogram':    b = int(input("Enter parallelogram's base length: "))    h = int(input("Enter parallelogram's height length: "))         # calculate area of parallelogram    para_area = b * h    print(f"The area of parallelogram is          {para_area}.")       else:    print("Sorry! This shape is not available") # driver codeif __name__ == "__main__" :     print("Calculate Shape Area")  shape_name = input("Enter the name of shape whose area you want to find: ")     # function calling  calculate_area(shape_name)
  
Output:
 
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.
 
 
 
adnanirshad158
akshaysingh98088
school-programming
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
GATE | GATE-IT-2004 | Question 12 - GeeksforGeeks

19 Nov, 2018
Consider a system with 2 level caches. Access times of Level 1 cache, Level 2 cache and main memory are 1 ns, 10ns, and 500 ns, respectively. The hit rates of Level 1 and Level 2 caches are 0.8 and 0.9, respectively. What is the average access time of the system ignoring the search time within the cache?(A) 13.0 ns(B) 12.8 ns(C) 12.6 ns(D) 12.4 nsAnswer: (C)Explanation: First, the system will look in cache 1. If it is not found in cache 1, then cache 2 and then further in main memory (if not in cache 2 also).
The average access time would take into consideration success in cache 1, failure in cache 1 but success in cache 2, failure in both the caches and success in main memory.
Average access time = [H1*T1]+[(1-H1)*H2*T2]+[(1-H1)(1-H2)*Hm*Tm]
where,
H1 = Hit rate of level 1 cache = 0.8T1 = Access time for level 1 cache = 1 nsH2 = Hit rate of level 2 cache = 0.9T2 = Access time for level 2 cache = 10 nsHm = Hit rate of Main Memory = 1Tm = Access time for Main Memory = 500 ns
 
So, Average Access Time   = ( 0.8 * 1 ) + ( 0.2 * 0.9 * 10 ) + ( 0.2 * 0.1 * 1 * 500)
= 0.8 + 1.8 + 10
= 12.6 ns
Thus, C is the correct choice.
 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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Difference between cerr and clog - GeeksforGeeks

18 Oct, 2021
In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. cerr and clog both are associated with the standard C error output stream stderr but the cerr is the unbuffered standard error stream whereas the clog is the buffered standard error stream. In this article, we will learn what is the difference between these two streams in detail with examples.
cerr: It is the unbuffered standard error stream that is used to output the errors.  This is an object of the ostream class similar to cout.  It is unbuffered i.e, it is used when there is a need to display the error message immediately. As there is no buffer so it cannot store the error message to display it later.  So simply as cerr is unbuffered it can not store the message.
Example:
C++
// c++ program to implement// the above approach#include <iostream>using namespace std;  // Driver codeint main(){    cerr << "the message displayed is unbuffered";    return 0;}
Output:
clog: It is the buffered standard error stream that is used to output the errors.  This is also an object of the ostream class similar to cout.  It is buffered i.e, firstly the error message is inserted in the buffer, and then it is displayed on the screen. As there is a buffer so it can store the error message to display it later unlike cerr.  So simply as clog is buffered it can not display the message immediately. clog is commonly used for logging purposes. For non-critical event logging, efficiency is more important so clog is preferred to cerr.
Example:
C++
// C++ program to implement// the above approach#include <iostream>using namespace std;  // Driver codeint main(){    clog << "the message displayed is buffered";    return 0;}
Output:
Difference Table:
cerr
clog
CPP-Basics
Articles
C++
C++ Programs
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
SQL | Date functions
Difference between Min Heap and Max Heap
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C | Advanced Pointer | Question 3 - GeeksforGeeks

28 Jun, 2021
#include <stdio.h>int main(){    int a[5] = {1,2,3,4,5};    int *ptr = (int*)(&a+1);    printf("%d %d", *(a+1), *(ptr-1));    return 0;}
(A) 2 5(B) Garbage Value(C) Compiler Error(D) Segmentation FaultAnswer: (A)Explanation: The program prints “2 5′′.
Since compilers convert array operations in pointers before accessing the array elements, (a+1) points to 2.
The expression (&a + 1) is actually an address just after end of array ( after address of 5 ) because &a contains address of an item of size 5*integer_size and when we do (&a + 1) the pointer is incremented by 5*integer_size.
ptr is type-casted to int * so when we do ptr -1, we get address of 5Quiz of this Question
Advanced Pointer
C-Advanced Pointer
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Core Dump (Segmentation fault) in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
Output of C programs | Set 64 (Pointers)
C | Arrays | Question 7
Scala Map retain() method with example - GeeksforGeeks

26 Jul, 2019
The retain() method is utilized to retain all the pairs of the map that satisfies the stated condition.
Method Definition: def retain(p: (A, B) => Boolean): Map.this.type
Return Type: It returns all the “key-value” pairs of the map which satisfies the stated predicate.
Example #1:
// Scala program of retain()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a mutable map        val m1 = scala.collection.mutable.Map(3 -> "geeks",                                     1 -> "for", 2 -> "cs")                  // Applying retain method        val result = m1.retain((key,value) => key > 1)                  // Displays output        println(result)          }}
Map(2 -> cs, 3 -> geeks)

Example: 2#
// Scala program of retain()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a mutable map        val m1 = scala.collection.mutable.Map(3 -> "geeks",                                    1 -> "for", 1 -> "cs")                  // Applying retain method        val result = m1.retain((key,value) => key > 1)                  // Displays output        println(result)              }}
Map(3 -> geeks)

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Operators in Scala
Scala Constructors
Scala | Arrays
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala
byte Keyword in C# - GeeksforGeeks

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System.Byte.
byte keyword occupies 1 byte (8 bits) in the memory.
Syntax:
byte variable_name = value;
Example:
Input: 250

Output: number: 250
        Size of a byte variable: 1

Input: 150

Output: Type of num1: System.Byte
        num1: 150
        Size of a byte variable: 1

Example 1:
// C# program to show the usage of byte keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // byte variable declaration        byte num = 255;          // to print value        Console.WriteLine("num: " + num);          // to print size of a byte        Console.WriteLine("Size of a byte variable: " + sizeof(byte));    }}
Output:
num: 255
Size of a byte variable: 1

Example 2:
// C# program to show the usage of byte keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // byte variable declaration        byte num1 = 261;          // to print value        Console.WriteLine("num1: " + num1);          // to print size of a byte        Console.WriteLine("Size of a byte variable: " + sizeof(byte));    }}
Error: When we enter number beyond the range from (0-255).
Constant value `261' cannot be converted to a `byte'
Example 3:
// C# program to show the usage of byte keywordusing System;using System.Text;  namespace geeks {  class GFG {    static void Main(string[] args)    {        // byte variable declaration        byte num1 = 150;          // to print type of variable        Console.WriteLine("Type of num1: " + num1.GetType());          // to print value        Console.WriteLine("num1: " + num1);          // to print size of a byte        Console.WriteLine("Size of a byte variable: " + sizeof(byte));          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of num1: System.Byte
num1: 150
Size of a byte variable: 1

CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Linked List Implementation in C#
Convert String to Character Array in C#
Node.js date-and-time Date.subtract() Method - GeeksforGeeks

07 Oct, 2021
The date-and-time Date.subtract() method is used to subtract the two date objects.
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
const subtract(date1, date2)
Parameters: This method takes the following arguments as a parameter:
date1: It is the first date object from which the second date is subtracted.
date2: It is the second date object.
Return Value: This method returns the result object subtracting date2 from date1.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.subtract() method  // Importing date-and-time moduleconst date = require('date-and-time')  // Creating object of current date and time // by using Date() const now  =  new Date();  // Creating object of given date and timeconst date1 = new Date(2015, 0, 1);  // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1);  // Display the resultconsole.log("total days between them "    + value.toDays())
Run the index.js file using the following command:
node index.js
Output:
total days between them 2270.3951833333335
Example 2:
index.js
// Node.js program to demonstrate the  // Date.subtract() method  // Importing date-and-time moduleconst date = require('date-and-time')  // Creating object of current date and time // by using Date() const now  =  new Date();  // Setting days in the existing datenow.setDate(20);  // Creating object of given date and timeconst date1 = new Date(2015, 0, 1);  // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1);  // Display the resultconsole.log("total days between them " + value.toDays())
Run the index.js file using the following command:
node index.js
Output:
total days between them 2270.397227997685
Reference: https://github.com/knowledgecode/date-and-time#subtractdate1-date2
kashishsoda
Node.js-Methods
NodeJS date-time
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
ChronoLocalDate isEqual() method in Java with Examples - GeeksforGeeks

29 Apr, 2019
The isEqual() method of ChronoLocalDate interface in Java checks if this date is equal to the specified date or not.
Syntax:
public boolean isEqual(ChronoLocalDate date2)

Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null.
Return Value: The function returns true if this date is equal to the specified date.
Below programs illustrate the isEqual() method of ChronoLocalDate in Java:
Program 1:
// Program to illustrate the isEqual() method  import java.util.*;import java.time.*;import java.time.chrono.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        ChronoLocalDate dt1            = LocalDate.parse("2018-11-27");          // Parses the second date        ChronoLocalDate dt2            = LocalDate.parse("2018-11-27");          // Check if these two are equal        System.out.println(dt1.isEqual(dt2));    }}
true

Program 2:
// Program to illustrate the isEqual() method  import java.util.*;import java.time.*;import java.time.chrono.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        ChronoLocalDate dt1            = LocalDate.parse("2018-11-27");          // Parses the second date        ChronoLocalDate dt2            = LocalDate.parse("2015-11-27");          // Check if these two are equal        System.out.println(dt1.isEqual(dt2));    }}
false

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#isEqual-java.time.chrono.ChronoLocalDate-
Java-ChronoLocalDate
Java-Functions
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Matplotlib.pyplot.rcdefaults() in Python - GeeksforGeeks

19 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.
The rcdefaults() function in pyplot module of matplotlib library is used to restore the rc params from Matplotlib’s internal default style.
Syntax: matplotlib.pyplot.rcdefaults()
Parameters: This method does not accepts any parameter.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot:
Example 1:
# implementation of the matplotlib functionimport matplotlib.pyplot as plt  plt.subplot(211)plt.rc('font', weight ='bold')plt.rc('xtick.major', size = 5, pad = 7)plt.rc('xtick', labelsize = 15)plt.plot([1, 2, 3])  plt.text(0.4, 3.5, 'matplotlib.pyplot.rcdefaults() Example')  plt.rcdefaults()plt.subplot(212)plt.plot([1, 2, 3])plt.grid(True)  plt.show()
Output:
Example 2:
# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  np.random.seed(19680801)  plt.rcdefaults()fig, ax = plt.subplots()  people = ('Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5')y_pos = np.arange(len(people))performance = 3 + 5 * np.random.rand(len(people))error = np.random.rand(len(people))  ax.bar(y_pos, performance, xerr = error, align ='center')ax.set_yticks(y_pos)ax.set_yticklabels(people)ax.invert_yaxis()plt.grid(True)  plt.title('matplotlib.pyplot.rcdefaults() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
MySQL ON vs USING?

In general, we use ON in MySQL. In Joins, we use ON in a set of columns. USING is useful when both the tables share a column of the exact same name on which they join.
Example of On.
Creating our first table.
mysql> CREATE table ForeignTableDemo
   -> (
   -> Id int,
   -> Name varchar(100),
   - > FK int
   - > );
Query OK, 0 rows affected (0.47 sec)
Creating our second table.
mysql> CREATE table PrimaryTableDemo
   - > (
   - >  FK int,
   - > Address varchar(100),
   - > primary key(FK)
   - > );
Query OK, 0 rows affected (0.47 sec)
Let us now add constraints.
mysql> ALTER table ForeignTableDemo add constraint FKConst foreign key(FK) references PrimaryTableDemo(FK);
Query OK, 0 rows affected (1.54 sec)
Records: 0  Duplicates: 0  Warnings: 0
To add records into the second table.
mysql> INSERT into PrimaryTableDemo values(1,'US');
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into PrimaryTableDemo values(2,'UK');
Query OK, 1 row affected (0.14 sec)

mysql>  INSERT into PrimaryTableDemo values(3,'Unknown');
Query OK, 1 row affected (0.08 sec)
Displaying all the records.
mysql> SELECT * from PrimaryTableDemo;
The following is the output.
+----+---------+
| FK | Address |
+----+---------+
|  1 | US      |
|  2 | UK      |
|  3 | Unknown |
+----+---------+
3 rows in set (0.00 sec)

Now, to add records into the first table.
mysql>  INSERT into ForeignTableDemo values (1,'John',1);
Query OK, 1 row affected (0.20 sec)

mysql>  INSERT into ForeignTableDemo values (2,'Bob',2);
Query OK, 1 row affected (0.27 sec)
Let us now display all the records from the first table.
mysql> SELECT * from ForeignTableDemo;
Here is the output.
+------+------+------+
| Id   | Name | FK   |
+------+------+------+
|    1 | John |    1 |
|    2 | Bob  |    2 |
+------+------+------+
2 rows in set (0.00 sec)

The query for straight join that displays only matching rows is shown below. We have used ON here.
mysql> SELECT ForeignTableDemo.Id, ForeignTableDemo.Name, PrimaryTableDemo.Address
   - > from ForeignTableDemo
   - > join PrimaryTableDemo
   - > on ForeignTableDemo.FK = PrimaryTableDemo.FK;
The following is the output.
+------+------+---------+
| Id   | Name | Address |
+------+------+---------+
|    1 | John | US      |
|    2 | Bob  | UK      |
+------+------+---------+
2 rows in set (0.14 sec)

Example of USING.
The following is the syntax of USING in MySQL, that displays the record where FK = 1.
mysql> select *from ForeignTableDemo join PrimaryTableDemo using(FK) where FK=1;
Here is the output.
+------+------+------+---------+
| FK   | Id   | Name | Address |
+------+------+------+---------+
|    1 |    1 | John | US      |
+------+------+------+---------+
1 row in set (0.09 sec)
Opening and Closing Files in Python

Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.
Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
file_name − The file_name argument is a string value that contains the name of the file that you want to access.
access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file −
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −
 Live Demo
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
fileObject.close()

 Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
This produces the following result −
Name of the file: foo.txt
How to submit a form by clicking a link in JavaScript ? - GeeksforGeeks

14 Aug, 2021
In this article, we have submitted a form using JavaScript by clicking a link. In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method.
Example: Create a form and submit it using the above approach. It is required for the form structure where the user will provide his/her details.
HTML
<!DOCTYPE html><html>  <body>    <h2 style="color:green">GeeksforGeeks</h2>    <b>Submit form details</b>      <form id="form__submit" action="form.php" method="post">        <label>NAME: </label><br />        <input type="text" name="name" /><br />        <label>AGE: </label><br />        <input type="number" name="age" /><br />        <label>CITY: </label><br />        <input type="text" name="city" /><br /><br />        <a href="#" onclick="submitForm()">Submit Here</a>    </form>      <script>        function submitForm() {            let form = document.getElementById("form__submit");            form.submit();        }    </script></body>  </html>
Note: The given HTML code will redirect the form data to the site or file which is mentioned in the action attribute.
PHP Code: Create a PHP file to get the user entered form data, rename this PHP file as “form.php”. This code displays the user form data.
PHP
<?php    $name=$_POST['name'];    $age=$_POST['age'];    $city=$_POST['city'];      echo "NAME-SUBMITTED : $name <br>";      echo "AGE-SUBMITTED :  $age <br>";      echo "CITY-SUBMITTED:  $city";?>
Output:
user form data
PHP is a client-side language. So it requires a server. Please refer PHP tutorial for a better understanding.
HTML-Questions
JavaScript-Questions
PHP-basics
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to print % using printf()?

Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use ‘%%’. Neither single % will print anything nor it will show any error or warning.
Here is an example to print % in printf() in C language,
 Live Demo
#include<stdio.h>
int main() {
   printf("%");
   printf("%%");
   getchar();
   return 0;
}
%
There are some other ways to print % in the text message as in the following example,
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   printf("welcome%\n");
   printf("%%\n");
   printf("%c\n",'%');
   printf("%s\n","%");
   char a[5];
   strcpy(a, "%%");
   printf("This is a's value: %s\n", a);
   return 0;
}
welcome%
%
37
%
%
This is a's value: %%
Python - Display True for infinite values in a Pandas DataFrame

Use the isin() method to display True for infinite values. At first, let us import the required libraries with their respective aliases −
import pandas as pd
import numpy as np
Create a dictionary of list. We have set the infinity values using the Numpy np.inf −
d = { "Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] }

Creating DataFrame from the above dictionary of list −
dataFrame = pd.DataFrame(d)
Display True for infinite values −
res = dataFrame.isin([np.inf, -np.inf])

Following is the code −
import pandas as pd
import numpy as np

# dictionary of list
d = { "Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] }

# creating dataframe from the above dictionary of list
dataFrame = pd.DataFrame(d)
print"DataFrame...\n",dataFrame

# checking for infinite values and displaying the count
count = np.isinf(dataFrame).values.sum()
print"\nInfinity values count...\n ",count

# Displaying TRUE for infinite values
res = dataFrame.isin([np.inf, -np.inf])
print"\n Updated DataFrame...\n",res
This will produce the following output −
DataFrame...
      Reg_Price
0   7000.505700
1           inf
2   5000.000000
3           inf
4   9000.757680
5   6000.000000
6    900.000000
7           inf

Infinity values count...
   3

Updated DataFrame...
   Reg_Price
0      False
1       True
2      False
3       True
4      False
5      False
6      False
7       True
PHP | getcwd( ) Function - GeeksforGeeks

11 Jul, 2018
The getcwd() function in PHP is an inbuilt function which is used to return the current working directory. This function does not accepts any parameter and returns the current working directory on successful function call or FALSE on failure.
Syntax:
getcwd()
Parameters: This function does not accept any parameter.
Return Value: It returns the current working directory on successful function call or FALSE on failure.
Errors And Exceptions:
getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set.If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link.
getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set.
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link.
Below programs illustrate the getcwd() function:
Program 1:
<?php  //current directory$cur_dir = getcwd();  // displaying current directoryecho $cur_dir ; ?>
Output:
user/home/gfg

Program 2:
<?php//current directory $cur_dir = getcwd();  echo("Current Directory is " . $cur_dir);  echo "<br>" ;  //changing current directory$flag = chdir("user/home/articles");  if($flag == true) { $cur_dir = getcwd();echo("Directory Has Been Successfully Changed to " . $cur_dir);}else{echo("Failed to Change Directory.");}?>
Output:
Current Directory Location is user/home/gfg
Directory Has Been Successfully Changed to user/home/articles

Reference: http://php.net/manual/en/function.getcwd.php
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to show a window that was hidden using the "withdraw" method in Tkinter?

Tkinter withdraw method hides the window without destroying it internally. It is similar to the iconify method that turns a window into a small icon. Let us suppose we want to reveal the hidden window during the execution of an application then we can use deiconify() method. It can be invoked with the window or frame of a widget in the application.
In this example, we will define a button in a Toplevel window (Popup Window) which can be the trigger to reveal the main window.
#Import the library
from tkinter import *
from tkinter import ttk

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

#Set the window geometry
win.geometry("750x200")

#Create a Label
Label(win, text= "Tkinter is a GUI Library in Python", font=('Helvetica 15 bold')).pack(pady=20)

#Define a function to show the Main window
def show_win():
   win.deiconify()

#Create another Toplevel Window
new_win= Toplevel(win)
new_win.geometry("700x250")
new_win.title("NEW WINDOW")

#Hide the Main Window
win.withdraw()

#Create a Button to Hide/ Reveal the Main Window
button= ttk.Button(new_win, text="Show" ,command= show_win)
button.pack(pady=50)

win.mainloop()
Running the above code will show the output as,
When we click the button "Show", it will display the Main window.
How to maximize the browser window in Selenium WebDriver using C#?

We can maximize the browser window with Selenium webdriver in C#. This can be done with the help of the Maximize method. We shall launch the browser and then apply this method on the driver object.
driver.Manage().Window.Maximize();
For implementation we shall be using the NUnit framework.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String u = "https://www.tutorialspoint.com/index.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate().GoToUrl(u);
         //maximizing browser
         d.Manage().Window.Maximize();
         Console.WriteLine("Browser Maximized");
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}
Click on Run All Tests −
Then, click on Open additional output for this result link