code-rag-bench/online-tutorials huggingface dataset:
Path normalize() method in Java with Examples

30 Jul, 2019
The normalize() method of java.nio.file.Path used to return a path from current path in which all redundant name elements are eliminated.The precise definition of this method is implementation dependent and it derives a path that does not contain redundant name elements. In many file systems, the “.” and “..” are special names indicating the current directory and parent directory. In those cases all occurrences of “.” are considered redundant and If a “..” is preceded by a non-“..” name then both names are considered redundant.
Syntax:
Path normalize()

Parameters: This method accepts nothing. It is parameter less method.
Return value: This method returns the resulting path or this path if it does not contain redundant name elements; an empty path is returned if this path does not have a root component and all name elements are redundant.
Below programs illustrate normalize() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.normalize() method  import java.nio.file.*;  public class GFG {    public static void main(String[] args)    {          // create object of Path        // In this example \\.. starts with non".."        // element        Path path            = Paths.get("D:\\..\\..\\.\\p2\\core"                        + "\\cache\\binary");          // print actual path        System.out.println("Actual Path : "                           + path);          // normalize the path        Path normalizedPath = path.normalize();          // print normalized path        System.out.println("\nNormalized Path : "                           + normalizedPath);    }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.normalize() method  import java.nio.file.*;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path            = Paths.get("\\.\\.\\core"                        + "\\file\\binary.java");          // print actual path        System.out.println("Actual Path : "                           + path);          // normalize the path        Path normalizedPath = path.normalize();          // print normalized path        System.out.println("\nNormalized Path : "                           + normalizedPath);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#normalize()
Java-Functions
Java-Path
java.nio.file 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
How to iterate any Map in Java
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
math.NaN() Function in Golang With Examples

13 Apr, 2020
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You get an IEEE 754 “not-a-number” value with the help of NaN() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the NaN() function.
Syntax:
func NaN() float64
Example 1:
// Golang program to illustrate math.NaN() Function  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Getting Not-a-number value    // Using NaN() function    res := math.NaN()      // Displaying the result    fmt.Println("Result: ", res)  }
Output:
Result:  NaN

Example 2:
// Golang program to illustrate math.NaN() Function  package main  import (    "fmt"    "math")  // Main functionfunc main() {       // Checking whether the given     // value is not-a-number or not    // Using NaN() function    nvalue := math.NaN()    if nvalue == math.NaN() {        fmt.Println("Given value is not-a-number")    } else {        fmt.Println("Given value is not a not-a-number")    }  }
Output:
Given value is not a not-a-number
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Time Durations in Golang
Loops in Go Language
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
Python – Change legend size in Plotly chart

23 Jun, 2022
The data on the graph’s Y-axis, also known as the graph series, is reflected in the legend of the graph. This is the information that comes from the columns of the relevant grid report, and it usually consists of metrics. A graph legend is usually displayed as a box on the right or left side of your graph.
Plotly’s update_layout() function is used to change legend size in the plotly chart.
Syntax:
update_layout(dict1=None, overwrite=False, **kwargs)
The values in the input dict / keyword arguments are used to iteratively alter the parts of the original layout.
Parameters:
dict1 (dict) – To be updated is a dictionary of properties.
overwrite (bool) – If True, existing properties will be overwritten. If False, recursively apply updates to existing properties, retaining properties that are not specified in the update operation.
kwargs – To be updated is a keyword/value pair of properties.
Example: Before editing size and font
Packages and CSV are imported. A plotly scatter plot is created using the px.scatter() method, X, Y, and color arguments are given. The below code is for a simple scatter plot without formatting the legend size.
To view and access the CSV file click here.
Python3
# import packagesimport plotly.express as pximport pandas as pd # importing csv filedf = pd.read_csv("iris.csv") # scatter plot using plotlyfig = px.scatter(df, x="sepal_length", y="sepal_width",                 color="species") fig.show()
Output:
After editing size and font:
Packages and CSV are imported. a plotly scatter plot is created using the px.scatter() method, X, Y, and color arguments are given. The below code is for creating a modified scatter plot where we use the update_layout() method to give extra parameters to our legend and change the font family and font size.
Python3
# import packagesimport plotly.express as pximport pandas as pd # importing csv filedf = pd.read_csv("iris.csv") # scatter plot using plotlyfig = px.scatter(df, x="sepal_length", y="sepal_width", color="species") # update_layout method used to modify change and sizefig.update_layout(legend=dict(title_font_family="Times New Roman",                              font=dict(size= 20))) fig.show()
Output:
nikhatkhan11
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
sciPy stats.mean() function | Python

10 Feb, 2019
scipy.stats.mean(array, axis=0) function calculates the arithmetic mean of the array elements along the specified axis of the array (list in python).
It’s formula –
Parameters :array: Input array or object having the elements to calculate the arithmetic mean.axis: Axis along which the mean is to be computed. By default axis = 0
Returns : Arithmetic mean of the array elements based on the set parameters.
Code #1:
# Arithmetic Mean    import scipy  arr1 = scipy.mean([1, 3, 27])    print("Arithmetic Mean is :", arr1) 
Arithmetic Mean is : 10.3333333333

Code #2: With multi-dimensional data
# Arithmetic Mean    from scipy import mean  arr1 = [[1, 3, 27],         [3, 4, 6],         [7, 6, 3],         [3, 6, 8]]    print("Arithmetic Mean is :", mean(arr1))   # using axis = 0print("\nArithmetic Mean is with default axis = 0 : \n",       mean(arr1, axis = 0))  # using axis = 1print("\nArithmetic Mean is with default axis = 1 : \n",       mean(arr1, axis = 1))  
Arithmetic Mean is : 6.41666666667

Arithmetic Mean is with default axis = 0 : 
 [  3.5    4.75  11.  ]

Arithmetic Mean is with default axis = 1 : 
 [ 10.33333333   4.33333333   5.33333333   5.66666667]

Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to define multiple style rules for a single element in CSS?

You may need to define multiple style rules for a single element. You can define these rules to combine multiple properties and corresponding values into a single block as defined in the following example: 
h1 {
   color: #36C; font-weight: normal;
   letter-spacing: .4em;
   margin-bottom: 1em;
   text-transform: lowercase;
}
Here all the property and value pairs are separated by a semicolon (;). You can keep them in a single line or multiple lines. For better readability, we keep them on separate lines.
Check if divisible by 10 | Practice | GeeksforGeeks

Given a binary number in the form of string, the task is to check whether the decimal representation of the given binary number is divisible by 10 or not. The number could be very large and may not fit even in long long int.
Example 1:
Input:
bin = "1010"
Output:
1
Explanation:
The decimal representation of given 
string is 10 which is divisible by 10.
So, answer is 1.
Example 2:
Input:
bin = "10"
Output:
0
Explanation:
The decimal representation of bin is 
2, which is not divisible by 10, so 
answer is 0.

Your Task:
You don't need to read input or print anything.Your Task is to complete the function isDivisibleBy10() which takes a binary string bin as input parameter and returns 0 if the decimal representaion of bin is not divisible by 10.Otherwise it returns 1.

Expected Time Complexity:O(N)
Expected Auxillary Space:O(1)
Constraints:
1 <= |bin| <= 105
0
gupta2411sumit3 days ago
def isDivisibleBy10(self,bin):       #code here       num  = int(bin,2)       if num%10 == 0 :           return 1        return 0 
+1
chessnoobdj4 months ago
C++
int isDivisibleBy10(string bin) {
        int n = bin.size(), sum = 0, k = 1;
        if(bin[n-1] == '1')
            return 0;
        if(n == 1 && bin[0] == '0')
            return 1;
        for(int i=n-2; i>=0; i--){
            k *= 2;
            sum += (bin[i]-'0')*k;
            if(k == 16)
                k = 1;
            sum %= 10;
        }
        return sum%10 == 0;
    }
+1
Chintan Kothari7 months ago
Chintan Kothari
0
Archit Jindal
This comment was deleted.
+1
Rohit Yadav1 year ago
Rohit Yadav
python3 def isDivisibleBy10(self,bin):
        a=int(bin,2)        if a%10==0:            return '1'        else:            return '0'
0
ASHISH KUMAR1 year ago
ASHISH KUMAR
can someone help me to find error
class Solution:    def isDivisibleBy10(self,bin):        #code here        n=len(bin)        res=0;        for i in range(n):            res=res+ (int(bin[i])*(2**(n-i-1)));
        if(res%10==0):            return 1;        else:            return 0;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to convert a string to date in MySQL?

We can convert a string to date with the help of STR_TO_DATE() function. Let us see an example.
Creating a table.
mysql> create table StringToDateDemo
   -> (
   -> YourDate varchar(100)
   -> );
Query OK, 0 rows affected (0.49 sec)
Inserting records into the table.
mysql>  insert into StringToDateDemo values('10/27/2018');
Query OK, 1 row affected (0.11 sec)
The following is the syntax to convert string to date using the STR_TO_DATE() function.
SELECT  STR_TO_DATE(yourColumnName, '%m/%d/%Y')
   from yourTableName;
Let us now implement it.
mysql>SELECT  STR_TO_DATE(YourDate, '%m/%d/%Y')
   -> from StringToDateDemo;
Here is the output.
+-----------------------------------+
| STR_TO_DATE(YourDate, '%m/%d/%Y') |
+-----------------------------------+
| 2018-10-27                        |
+-----------------------------------+
1 row in set (0.00 sec)
Java program to count the occurrences of each character - GeeksforGeeks

09 Feb, 2021
Write a Java program which prints number of occurrences of each characters and also it should not print repeatedly occurrences of duplicate characters as given in the example:Examples: 
Input : geeksforgeeks
Output :
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
Approach:
The idea is to create a count array of size 256. Traverse input string and for every character increment its count. 
JAVA
// Java program for the above approachclass NoOfOccurenceOfCharacters {    static final int MAX_CHAR = 256;     static void getOccuringChar(String str)    {                 // Create an array of size 256        // i.e. ASCII_SIZE        int count[] = new int[MAX_CHAR];         int len = str.length();         // Initialize count array index        for (int i = 0; i < len; i++)            count[str.charAt(i)]++;         // Create an array of given String size        char ch[] = new char[str.length()];        for (int i = 0; i < len; i++) {            ch[i] = str.charAt(i);            int find = 0;            for (int j = 0; j <= i; j++) {                 // If any matches found                if (str.charAt(i) == ch[j])                    find++;            }             if (find == 1)                System.out.println(                    "Number of Occurrence of "                    + str.charAt(i)                    + " is:" + count[str.charAt(i)]);        }    }       // Driver Code    public static void main(String[] args)    {        String str = "geeksforgeeks";        getOccuringChar(str);    }}
Output: 
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
unholycat
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Find free disk space using C#

Firstly, create an instance of DriveInfo −
DriveInfo dInfo = new DriveInfo("E");
Display free space −
Console.WriteLine("Disk Free space = {0}", dInfo.AvailableFreeSpace);
Now, use AvailableFreeSpace property and get the percentage of free space −
Double pc = (dInfo.AvailableFreeSpace / (float)dInfo.TotalSize) * 100;
Here, you will get the percentage of free size in comparison with the total disk space −
Console.WriteLine("\n Free space (percentage) = {0:0.00}%.", pc);
Tryit Editor v3.6 - Show Sass

@mixin important-text {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
}

.danger {
  @include important-text;
  background-color: green;
}

.danger {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
  background-color: green;
}

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="mystyle.css">
<body>

<h1>Hello World</h1>

<p class="danger">Warning! This is some text.</p>

</body>
</html>
Warning! This is some text.
Comparator reverseOrder() method in Java with examples

29 Apr, 2019
The reverseOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in reverse of natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null.
Syntax:
static <T extends Comparable<T>> 
    Comparator<T> reverseOrder()

Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the reverse natural ordering on Comparable objects.
Below programs illustrate reverseOrder() method:Program 1:
// Java program to demonstrate// Comparator.reverseOrder()  method  import java.util.Arrays;import java.util.Comparator;import java.util.List;  public class GFG {    public static void main(String... args)    {          List<Integer> values            = Arrays.asList(212, 324,                            435, 566,                            133, 100,                            121);          // reverseOrder is a static method        values.sort(Comparator.reverseOrder());          // print sorted number based on natural order        System.out.println(values);    }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Comparator.reverseOrder()  method  import java.util.Arrays;import java.util.Comparator;import java.util.List;  public class GFG {    public static void main(String... args)    {          List<String> stringList            = Arrays.asList("Aman", "Kajal",                            "Joyita", "Das");          System.out.println("Before sorting:");        stringList.forEach(System.out::println);          stringList.sort(Comparator.reverseOrder());        System.out.println("\nAfter sorting:");        stringList.forEach(System.out::println);    }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reverseOrder()
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a database in MongoDB using Python

22 Apr, 2022
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model. MongoDB has no separate command to create a database. Instead, it uses the use command to create a database. The use command is used to switch to the specific database. If the database name specified after the use keyword does not exist, then a new database is created with the specified name.
To use Python in MongoDB, we are going to import PyMongo. From that, MongoClient can be imported which is used to create a client to the database. Using the client, a new database can be created. Example: List of databases using MongoDB shell (before):  
Python3
# import MongoClientfrom pymongo import MongoClient  # Creating a clientclient = MongoClient('localhost', 27017) # Creating a database name GFGdb = client['GFG']print("Database is created !!")
Output:
Database is created!!
In the above example, it is clearly shown how a database is created. When creating a client, the local host along with its port number, which is 27017 here, is passed to the MongoClient. Then, by using the client, a new database named ‘GFG’ is created. We can check if the database is present in the list of databases using the following code: 
Python3
list_of_db = client.list_database_names() if "mydbase" in list_of_db:    print("Exists !!")
Output:
Exists!!
List of Databases in MongoDB shell (after): 
moabd774
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Trim a String to a Specified Display Width in R Programming – strtrim() Function

12 Jun, 2020
strtrim() function in R Language is used to trim a string to a specified display width.
Syntax: strtrim(x, width)
Parameters:x: character vectorwidth: specified width
Example 1:
# R program to trim a string# to specified width  # Creating a vectorx1 <- "GeeksforGeeks"x2 <- "R Programming"  # Calling strtrim() functionstrtrim(x1, 5)strtrim(x2, 7)
Output:
[1] "Geeks"
[1] "R Progr"

Example 2:
# R program to trim a string# to specified width  # Creating a vectorx <- c("Hello", "Geeks", "GFG")  # Calling strtrim() functionstrtrim(x, 2)strtrim(x, c(1, 2, 3))
Output:
[1] "He" "Ge" "GF"
[1] "H"   "Ge"  "GFG"

R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.path.isabs() method

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.isabs() method in Python is used to check whether the specified path is an absolute path or not.
On Unix platforms, an absolute path begins with a forward slash (‘/’) and on Windows it begins with a backward slash (‘\’) after removing any potential drive letter.
Syntax: os.path.isabs(path)
Parameter:path: A path-like object representing a file system path.A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an absolute path, otherwise returns False.
Code #1: Use of os.path.isabs() method (On Unix platforms)
# Python program to explain os.path.isabs() method     # importing os.path module import os.path  # Pathpath = '/home/User/Documents'  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)    # Pathpath = 'home/User/Documents/'  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)    # Pathpath = '../User/Documents/'  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)
True
False
False

Code #2: Use of os.path.isabs() method (On Windows)
# Python program to explain os.path.isabs() method     # importing os.path module import os.path  # Pathpath = r"C:\\Users\\Documents"  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)    # Pathpath = r"\\User\\Documents"  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)    # Pathpath = r"User\\Documents"  # Check whether the # specified path is an# absolute path or notisabs = os.path.isabs(path)print(isabs)
True
True
False

Reference: https://docs.python.org/3/library/os.path.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a Splash Screen using Tkinter? - GeeksforGeeks

12 Dec, 2021
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
A splash screen in tkinter is a tkinter window that disappears after a fixed period and then a particular operation takes place. To Create a splash screen we will use after() and destroy() method.
The after() method assigns a time period (as argument) after which a particular operation takes place, that operation is transformed into a function and is passed as an argument in after() method.
Syntax:
root.after(time in millisecond, function name)
The destroy() method is used to close the current tkinter window.
Syntax:
root.destroy()
Below is a program that creates two normal Tkinter windows. The smaller window acts as a splash screen but it will not disappear.
Python3
# Import modulefrom tkinter import * # Create objectsplash_root = Tk() # Adjust sizesplash_root.geometry("200x200") # Set Labelsplash_label = Label(splash_root, text="Splash Screen", font=18)splash_label.pack() # main window functiondef main():    # Create object    root = Tk()     # Adjust size    root.geometry("400x400")  # Call main functionmain() # Execute tkintermainloop()
Output:
Main Window
Splash Window
Now we will use the below methods:
destroy()
after()
To create a splash screen in tkinter.
Below is a program that creates Splash screen in tkinter using after() and destroy() methods.
Python3
# Import modulefrom tkinter import *   # Create objectsplash_root = Tk()   # Adjust sizesplash_root.geometry("200x200") # Set Labelsplash_label = Label(splash_root,text="Splash Screen",font=18)splash_label.pack() # main window functiondef main():     # destroy splash window    splash_root.destroy()     # Execute tkinter    root = Tk()           # Adjust size    root.geometry("400x400") # Set Intervalsplash_root.after(3000,main) # Execute tkintermainloop()
Output:
Here a splash screen is created and it stays for a particular time period and then a next operation takes place i.e a new window is generated.
kalrap615
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
C++ | new and delete | Question 1 - GeeksforGeeks

29 Jul, 2020
How to create a dynamic array of pointers (to integers) of size 10 using new in C++?
Hint: We can create a non-dynamic array using int *arr[10](A) int *arr = new int *[10];(B) int **arr = new int *[10];(C) int *arr = new int [10];(D) Not PossibleAnswer: (B)Explanation: Dynamic array of pointer having size 10 using new is created as,
int **arr = new int *[10]; 
So, option (B) is correct.Quiz of this Question
vivekkumarmth0077
C++-new and delete
new and delete
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Operator Overloading | Question 10
C++ | Inheritance | Question 3
C++ | Virtual Functions | Question 2
C++ | Virtual Functions | Question 4
C++ | Inheritance | Question 11
C++ | Virtual Functions | Question 1
C++ | References | Question 4
C++ | Inheritance | Question 12
How to fill the missing values of an R data frame from the mean of columns?

Dealing with missing values is one of the initial steps in data analysis and it is also most difficult because we don’t fill the missing values with the appropriate method then the result of the whole analysis might become meaningless. Therefore, we must be very careful about dealing with missing values. Mostly for learning purposes, people use mean to fill the missing values but can use many other values depending on our data characteristic. To fill the missing value with mean of columns, we can use na.aggregate function of zoo package.
Consider the below data frame −
x1<-c(1:5,NA,17:30)
x2<-c(1:2,NA,4:20)
x3<-sample(c(1,5,8,NA,6,3),20,replace=TRUE)
x4<-sample(c(45,75,68,NA,36,43),20,replace=TRUE)
x5<-rep(c(23,45,55,78,NA),times=4)
df<-data.frame(x1,x2,x3,x4,x5)
df
x1 x2 x3 x4 x5
1 1 1 6 36 23
2 2 2 5 36 45
3 3 NA 1 68 55
4 4 4 1 43 78
5 5 5 3 45 NA
6 NA 6 3 75 23
7 17 7 5 68 45
8 18 8 6 43 55
9 19 9 NA 75 78
10 20 10 8 75 NA
11 21 11 3 43 23
12 22 12 1 68 45
13 23 13 8 45 55
14 24 14 5 36 78
15 25 15 5 36 NA
16 26 16 5 75 23
17 27 17 5 75 45
18 28 18 6 43 55
19 29 19 8 NA 78
20 30 20 6 75 NA
library(zoo)
na.aggregate(df)
      x1    x2    x3    x4    x5
1 1.00000 1.00000 6.000000 36.00000 23.00
2 2.00000 2.00000 5.000000 36.00000 45.00
3 3.00000 10.89474 1.000000 68.00000 55.00
4 4.00000 4.00000 1.000000 43.00000 78.00
5 5.00000 5.00000 3.000000 45.00000 50.25
6 18.10526 6.00000 3.000000 75.00000 23.00
7 17.00000 7.00000 5.000000 68.00000 45.00
8 18.00000 8.00000 6.000000 43.00000 55.00
9 19.00000 9.00000 4.736842 75.00000 78.00
10 20.00000 10.00000 8.000000 75.00000 50.25
11 21.00000 11.00000 3.000000 43.00000 23.00
12 22.00000 12.00000 1.000000 68.00000 45.00
13 23.00000 13.00000 8.000000 45.00000 55.00
14 24.00000 14.00000 5.000000 36.00000 78.00
15 25.00000 15.00000 5.000000 36.00000 50.25
16 26.00000 16.00000 5.000000 75.00000 23.00
17 27.00000 17.00000 5.000000 75.00000 45.00
18 28.00000 18.00000 6.000000 43.00000 55.00
19 29.00000 19.00000 8.000000 55.78947 78.00
20 30.00000 20.00000 6.000000 75.00000 50.25
Let’s have a look at another example −
var1 <-sample(c(1,2,NA),20,replace=TRUE)
var2 <-sample(c(2,NA),20,replace=TRUE)
var3 <-c(rnorm(10),rep(NA,10))
var_data <-data.frame(var1,var2,var3)
var_data
   var1 var2 var3
1 1 NA 0.15883062
2 NA 2 0.65976414
3 NA 2 2.22051966
4 NA NA -1.18394507
5 1 NA -0.07395583
6 NA 2 -0.41635467
7 NA NA -0.19148234
8 NA NA 0.06954478
9 1 2 1.15534832
10 2 2 0.59495735
11 2 NA NA
12 1 2 NA
13 NA 2 NA
14 NA NA NA
15 1 NA NA
16 1 NA NA
17 1 2 NA
18 NA 2 NA
19 1 2 NA
20 2 NA NA
na.aggregate(var_data)
   var1 var2 var3
1 1.000000 2 0.15883062
2 1.272727 2 0.65976414
3 1.272727 2 2.22051966
4 1.272727 2 -1.18394507
5 1.000000 2 -0.07395583
6 1.272727 2 -0.41635467
7 1.272727 2 -0.19148234
8 1.272727 2 0.06954478
9 1.000000 2 1.15534832
10 2.000000 2 0.59495735
11 2.000000 2 0.29932269
12 1.000000 2 0.29932269
13 1.272727 2 0.29932269
14 1.272727 2 0.29932269
15 1.000000 2 0.29932269
16 1.000000 2 0.29932269
17 1.000000 2 0.29932269
18 1.272727 2 0.29932269
19 1.000000 2 0.29932269
20 2.000000 2 0.29932269
Merge two sets in Java

To merge two sets in Java, the code is as follows −
 Live Demo
import java.util.stream.*;
import java.util.*;
import java.io.*;
public class Demo{
   public static <T> Set<T> set_merge(Set<T> set_1, Set<T> set_2){
      Set<T> my_set = set_1.stream().collect(Collectors.toSet());
      my_set.addAll(set_2);
      return my_set;
   }
   public static void main(String[] args){
      Set<Integer> my_set_1 = new HashSet<Integer>();
      my_set_1.addAll(Arrays.asList(new Integer[] { 34, 67, 89, 102 }));
      Set<Integer> my_set_2 = new HashSet<Integer>();
      my_set_2.addAll(Arrays.asList(new Integer[] { 77, 11, 0 , -33}));
      System.out.println("The first set contains " + my_set_1);
      System.out.println("The second set contains " + my_set_2);
      System.out.println("The two sets are merged " + set_merge(my_set_1, my_set_2));
   }
}
The first set contains [34, 67, 102, 89]
The second set contains [0, -33, 11, 77]
The two sets are merged [0, -33, 34, 67, 102, 89, 11, 77]
A class named Demo contains a function named ‘set_merge’ that uses the ‘addAll’ function to merge the two sets that are passed as parameters to the function. In the main function, two sets are defined and elements are added into it using the ‘addAll’ function. Relevant messages are printed on the console.
Preparing the data for Transformer pre-training — a write-up | by Steven van de Graaf | Towards Data Science

Introduced only a little over a year ago, the best-known incarnation of the Transformer model introduced by Vaswani et al. (2017), the Bidirectional Encoder Representations from Transformers (better known as BERT) model by Devlin et al. (2018) has since become hugely popular within the Natural Language Processing (NLP) community. This is due not only due to its state-of-the-art results on a wide array of NLP tasks, but also due to it being available publicly through their own repository, but also the increasingly popular Transformers library by HuggingFace.
BERT and other Transformers like RoBERTa, XLM and XLNet are pre-trained on (among others) a concatenation of the Toronto BookCorpus dataset (Zhu et al., 2015) and English Wikipedia. As the former is no longer publicly available, and the latter requires significant pre-processing, this write-up presents a complete picture (and code) of everything involved in collecting, concatenating, shuffling and tokenizing the data needed required to experiment with these Transformer models yourself.
As mentioned previously, the Toronto BookCorpus (TBC) dataset by Zhu et al. (2015) is no longer publicly available. Smashwords, the source of the dataset, is still available, however. As such, you can replicate the TBC dataset yourself following this previous write-up of mine below:
towardsdatascience.com
While Wikipedia dumps are freely available, they still need to be extracted, cleaned and pre-processed before they are ready to be used for Transformer pre-training. As such, similar to the TBC dataset, you can do so yourself following another previous write-up of mine below:
towardsdatascience.com
Now that you have collected both the Toronto BookCorpus dataset and English Wikipedia, we can proceed to concatenate and shuffle the two. This can be accomplished quite simply in Bash or similar using the code below:
cat tbc_replica.txt en_wiki.txt | shuf >> concat_shuffled.txt
With the data collected, concatenated and shuffled, all that is left now is to tokenize the data. In an ideal world, we would tokenize our data on-the-fly, but for performance reasons, we pre-tokenize our data instead. For this, we use the recently released, blazingly fast Tokenizers library, also by HuggingFace via the code below:
To tokenize the data, first download the vocab file here and then simply run the following command in your terminal: python3 tokenize_data.py concat_shuffled.txt bert-base-uncased-vocab.txt
And that’s it, you’re done! You can now start experimenting with these Transformer models yourself, using the data you’ve freshly prepared. 🤗
[1] J. Devlin et al., Bert: Pre-training of deep bidirectional transformers for language understanding (2018), arXiv preprint arXiv:1810.04805.
[2] Vaswani et al., Attention is all you need (2017), Advances in neural information processing systems (pp. 5998–6008).
[3] Zhu et al., Aligning books and movies: Towards story-like visual explanations by watching movies and reading books (2015), Proceedings of the IEEE international conference on computer vision (pp. 19–27).
MongoDB | ObjectID() Function - GeeksforGeeks

05 Jun, 2020
ObjectID() Function: MongoDB uses ObjectID to create unique identifiers for all the documents in the database. It is different than the traditional autoincrementing integer ID, but it comes with its own set of advantages.
An ObjectID is a GUID (Globally Unique Identifier). GUIDs are generated randomly via an algorithm to ensure uniqueness. These IDs can be generated on the server, but as seen in the snippet above, they can be generated on the client as well. That means a client can generate the ID for a document it’s about to insert into the database.
Installation of mongodb module:
You can visit the link to Install mongodb module. You can install this package by using this command.npm install mongodbAfter installing mongodb module, you can check your mongodb version in command prompt using the command.npm version mongodbAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongodb module. You can install this package by using this command.npm install mongodb
npm install mongodb
After installing mongodb module, you can check your mongodb version in command prompt using the command.npm version mongodb
npm version mongodb
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
MongoDB provides ObjectID which can be used to generate new ObjectIDs. The example below generates a new ID and prints it to the console.
Filename: index.js
const { MongoClient, ObjectID } = require('mongodb');const id = new ObjectID();  // Print new id to the consoleconsole.log(id); 
Steps to run the program:
The project structure will look like this:Make sure you have installed mongodb module using following command:npm install mongodbRun index.js file using below command:node index.js
The project structure will look like this:
Make sure you have installed mongodb module using following command:npm install mongodb
npm install mongodb
Run index.js file using below command:node index.js
node index.js
So this is how you can use the MongoDB ObjectID() function to create unique identifiers for all the documents in the database.
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Spring Boot JpaRepository with Example
Aggregation in MongoDB
How to build a basic CRUD app with Node.js and ReactJS ?
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
Add elements to a Queue using Javascript

Enqueuing elements to a Queue means adding them to the end of the array. We are taking the end of the container array to be the tail of the queue as we'll perform all insertions operations with respect to it.
So we can implement the enqueue function as follows −
enqueue(element) {
   // Check if Queue is full
   if (this.isFull()) {
      console.log("Queue Overflow!");
      return;
   }
   // Since we want to add elements to end, we'll just push them.
   .container.push(element);
}
You can check if this function is working fine using −
 let q = new Queue(2);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.display();
This will give the output −
Queue Overflow!
[ 1, 2 ]
Check if a directed graph is connected or not in C++

To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have only outward edge but no inward edge, so that node will be unvisited from any other starting node.
In this case the traversal algorithm is recursive DFS traversal.
Input − Adjacency matrix of a graph
Output − The Graph is connected.
traverse(u, visited)
Input: The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
Begin
   mark u as visited
   for all vertex v, if it is adjacent with u, do
      if v is not visited, then
         traverse(v, visited)
   done
End
isConnected(graph)
Input: The graph.
Output: True if the graph is connected.
Begin
   define visited array
   for all vertices u in the graph, do
      make all nodes unvisited
      traverse(u, visited)
      if any unvisited node is still remaining, then
         return false
   done
   return true
End
 Live Demo
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 0, 0, 0},
   {0, 0, 1, 0, 0},
   {0, 0, 0, 1, 1},
   {1, 0, 0, 0, 0},
   {0, 1, 0, 0, 0}
};
void traverse(int u, bool visited[]){
   visited[u] = true; //mark v as visited
   for(int v = 0; v<NODE; v++){
      if(graph[u][v]){
         if(!visited[v])
         traverse(v, visited);
      }
   }
}
bool isConnected(){
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++){
      for(int i = 0; i<NODE; i++)
      vis[i] = false; //initialize as no node is visited
      traverse(u, vis);
      for(int i = 0; i<NODE; i++){
         if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
         return false;
      }
   }
   return true;
}
int main(){
   if(isConnected())
   cout << "The Graph is connected.";
   else
   cout << "The Graph is not connected.";
}
The Graph is connected.
What are annotations in Java?

Annotations are a tag (metadata) which provides info about a program.
Annotations in Java Start with the symbol ‘@’.
They are used by the compiler to detect errors.
Software tools to generate code.
They are used to show attributes of an element: e.g. @Deprecated, @Override.
Annotation are used to describe the purpose of an element of the framework, e.g. @Entity, @TestCase, @WebService
Annotations describe the behaviour of an element: @Statefull, @Transaction.
 Live Demo
class Sample{
   public void display(){
      System.out.println(" ");
   }
}
public class Test extends Sample {
   @Override
   public void display(){
      System.out.println("Welcome to Tutorialspoint");
   }
   public static void main(String[] args) {
      Test obj = new Test();
      obj.display();
   }
}
Welcome to Tutorialspoint
How do we send an email using HTML forms?

To send an email using HTML forms, you need to add the email id to the action attribute of the form. In that, add email proceeding with mailto: i.e. mailto:emailid@example.com.
You can try to run the following code to send an email using HTML forms −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <h2>Student Contact Form</h2>
      <form action="mailto:emailid@example.com" method="post" enctype="text/plain">
         Student Name:<br><input type="text" name="sname"> <br>
         Student Subject:<br><input type="text" name="ssubject"><br>
         <input type="submit" value="Send">
      </form>
   </body>
</html>
is keyword in Python

26 Mar, 2020
In programming, a keyword is a “reserved word” by the language which conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Python, keywords are case sensitive.
This keyword is used to test object identity. The “is keyword” is used to test whether two variables belong to the same object. The test will return True if the two objects are the same else it will return False even if the two objects are 100% equal.
Note: The == operator is used to test if two objects are the same.
Syntax:
a is b

# Using if statement
if a is b:
    statement(s)
Example 1:
# Python program to demonstrate# is keyword    x = ["a", "b", "c", "d"]  y =  ["a", "b", "c", "d"]  print(x is y)print(x == y)
Output :FalseTrue
Example 2:
# Python program to demonstrate# is keyword    x = 10y = 10  if x is y:    print(True)else:    print(False)
Output:
True
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2017 | Question 78

15 Mar, 2018
Consider the results of a medical experiment that aims to predict whether someone is going to develop myopia based on some physical measurements and heredity. In this case, the input dataset consists of the person’s medical characteristics and the target variable is binary: 1 for those who are likely to develop myopia and 0 for those who aren’t. This can be best classified as(A) Regression(B) Decision Tree(C) Clustering(D) Association RulesAnswer: (B)Explanation: Regression: It is a statistical analysis which is used to establish relation between a response and a predictor variable. It is mainly used in finance related applications.Decision Tree: Decision tree is a computational method which works on descriptive data and records the observations of each object to reach to a result.Clustering: It is a method of grouping more similar objects in a group and the non-similar objects to other groups.Association Rules: It uses if-then reasoning method using the support-confidence technique to give a result.According to the question Decision Tree is the most suitable technique that can be used to get best result of the experiment.Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change selection background color of a canvas circle using Fabric.js ?

12 May, 2020
In this article, we are going to see how to change the selection background color of a canvas circle using FabricJS. The canvas means the circle is movable and can be stretched according to requirement. Further, the circle can be customized when it comes to initial stroke color, fill color, stroke width or radius.
Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our circle. After this, we will initialize instances of Canvas and Circle provided by FabricJS and change the selection background color of the circle using selectionBackgroundColor property and render the Circle on the Canvas as given in the example below.
Syntax:
fabric.Circle({
    radius: number,
    selectionBackgroundColor: string
}); 
Parameters: This function accepts two parameters as mentioned above and described below:
radius: It specifies the radius.
selectionBackgroundColor: It specifies the color of selection background.
Example: This example uses FabricJS to change selection background color of a canvas circle. Note that you have to click on the object to see its selection background color.
<!DOCTYPE html><html>  <head>    <title>        How to change selection background color        of a canvas circle using FabricJS?    </title>      <!-- FabricJS CDN -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head>  <body>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000">    </canvas>      <script>          // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");          // Initiate a Circle instance        var circle = new fabric.Circle({            radius: 50,            selectionBackgroundColor: 'green'        });          // Render the circle in canvas        canvas.add(circle);    </script></body>  </html>
Output:
Fabric.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.