code-rag-bench/online-tutorials huggingface dataset:
How to Install Jupyter Notebook on MacOS? - GeeksforGeeks

26 Oct, 2021
>
In this article, we will learn how to install Jupyter Notebook in Python on MacOS. 
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
Follow the below steps to install the Jupyter Notebook package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Jupyter Notebook using pip3.
pip3 install jupyter
Follow the below steps to install the Jupyter Notebook package on macOS using the setup.py file:
Step 1: Download the latest source package of Jupyter Notebook for python3 from here.
curl https://files.pythonhosted.org/packages/c9/a9/371d0b8fe37dd231cf4b2cff0a9f0f25e98f3a73c3771742444be27f2944/jupyter-1.0.0.tar.gz > jupyter.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf jupyter.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd jupyter-1.0.0
python3 setup.py install
Enter the following command in your terminal to start up Jupyter Notebook and verify if the installation has been done properly:
jupyter notebook
If there is any error while importing the module then is not installed properly.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
How to Install OpenCV for Python on Windows?
Java Tutorial
How to Install FFmpeg on Windows?
Installation of Node.js on Linux
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Install and Run Apache Kafka on Windows?
Binary Number System


Binary Number System is one the type of Number Representation techniques. It is most popular and used in digital systems. Binary system is used for representing binary quantities which can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: open or close.
In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1. Represented by any device that only 2 operating states or possible conditions. Binary numbers are indicated by the addition of either an 0b prefix or an 2 suffix.
Position of every digit has a weight which is a power of 2. Each position in the Binary system is 2 times more significant than the previous position, that means numeric value of a Binary number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system.
Voltage range between 0V to 0.8V is used for binary logic 0 and voltage range between 2V to 5V is used for binary logic 1. Voltage range between 0.8V to 2V is not used because it may causes error in a digital circuit.
Example-1 − The number 125 is interpreted as
125 = 1x26+1x25+1x24+1x23+1x22+0x21+1x20=1111101
Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB).
Example-2 − The number 90.75 is interpreted as
90.75 = 1x26+0x25+1x24+1x23+0x22+1x21+0x20+1x2-1+1x2-2=1011010.11
Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB).
Example-3 − A decimal number 21 to represent in Binary representation
(21)10 =16+0+4+0+1 = 1x24+0x23+1x22+0x21+1x20 =(10101)2
So, decimal value 21 is equivalent to 10101 in Binary Number System.
The binary number system is very useful in computer technology and computer programming languages also uses binary number system that is helpful in digital encoding. The binary number system can also be used in Boolean algebra.
The main advantage of using binary is that it is a base which is easily represented by electronic devices. The Binary Number System are also ease of use in coding, fewer computations and less computational errors.
The major disadvantage of binary number is difficult to read and write for humans because of large number of binary of a equivalent decimal number.
To get 1’s complement of a binary number, simply invert the given number. For example, 1’s complement of binary number 110010 is 001101.
2’s complement of binary number is 1’s complement of given number plus 1 to the least significant bit (LSB). For example 2’s complement of binary number 10010 is (01101) + 1 = 01110.
C++ | A Speed Breaker | Practice | GeeksforGeeks

Write a program to display the floating number a with a given precision value b.
Example 1:
Input: a = 4.567, b = 2
Output: 
4.57
Explanation: Rounding a to two decimal
places.

Example 2:
Input: a = 8.92, b = 3
Output: 
8.920
Explanation: Rounding a to three decimal
places.

Your Task:  
You dont need to read input. Complete the function speedBreaker() which takes a and b as input parameters and print the floating number a with a given precision value b.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ b ≤ 15
0
n000nautiyal7 months ago
What mistake i was doing, maybe you are also facing the same issue: 
After submitting its showing error and the output of my code is: 45.72.2203010.05500051 this long.
This occured due to a problem of not writing endl in this line;
cout<<fixed<<setprecision(b)<<a<<endl;
You may be also writing as: 
cout<<fixed<<setprecision(b)<<a;
It needs a new line basically.
0
Gurucharan Rajput
This comment was deleted.
0
Muskan Gupta1 year ago
Muskan Gupta
void speedBreaker(double a, int b){        // code here        cout<<fixed<<setprecision(b)<<a; }="" why="" this="" code="" is="" creating="" problem="" during="" submission.="">
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 change the color of an icon using jQuery ? - GeeksforGeeks

18 Oct, 2021
In this article, we will see how to change the color of the icon using jQuery. To change the color of the icon, we will use a jquery method.
jQuery css() method this method is used to change the styling of a particular selector. This method is also can be used for changing the color of the icon. First, we will create an icon element using font awesome icon and add some styles on it using CSS property. We have added an HTML button and when the button is clicked, the css() method is called and added some color and background color on the icon element.
Syntax:
$(selector).css(property)
Return value: It will return the value of the property for the selected element. 
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>        How to change the color of the icon using jQuery?    </title>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <link rel="stylesheet"           href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">    <style>        .btn {            background-color: blue;            border: none;            color: white;            padding: 16px 16px;            font-size: 100px;            border-radius: 5px;        }          #append {            padding: 5px 15px;        }    </style>    <!-- Script to add div element          in the HTML document -->    <script>        $(document).ready(function () {            $("button").click(function () {                $(".btn").css({                    backgroundColor: "green",                    color: "yellow"                });            });        });    </script>  </head>  <body>      <center>        <h1 style="color: green;">            GeeksforGeeks        </h1>          <h3>            How to change the color of the icon using jQuery?        </h3>          <button class="btn">            <i class="fa fa-home"></i>        </button>          <br><br>          <button id="append">            Change Icon Color        </button>      </center></body>  </html>
Output:
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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?
PHP | strstr() Function

02 Nov, 2020
The strstr() function is a built-in function in PHP. It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified). This function is case-sensitive.
Syntax : 
strstr( $string, $search, $before )


Parameters : This function accepts three parameters as shown in the above syntax out of which the first two parameters must be supplied and the third one is optional. All of these parameters are described below: 
$string : It is a mandatory parameter which specifies the string in which we want to perform the search.
$search : It is a mandatory parameter which specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number
$before : It is an optional parameter. It specifies a boolean value whose default is false. If set to true, it returns the part of the $string before the first occurrence of the $search parameter.
Return Value : The function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
Examples: 
Input : $string = "Hello world!", $search = "world"
Output : world!

Input : $string = "Geeks for Geeks!", $search = "k"
Output : ks for Geeks!


Below programs illustrate the strstr() function in PHP :
Program 1: In this program, we will display the portion of $string from the first occurrence of $search.  
PHP
<?phpecho strstr("Geeks for Geeks!", "k");?>
Output: 
ks for Geeks! 


Program 2: In this program, we will display the portion of $string before the first occurrence of $search. 
PHP
<?phpecho strstr("Geeks for Geeks!", "k", true);?>
Output: 
Gee


Program 3: In this program we will pass an integer as $search. 
PHP
<?php  $string = "Geeks";  echo strstr($string, 101); // 101 is ASCII value of lowercase e?>
Output: 
eeks


Reference: http://php.net/manual/en/function.strstr.php 
arorakashish0911
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tailwind CSS Transition Property

23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. The transition-property class is used to specify the name of the CSS property for which the transition effect will occur. In CSS, we have done that by using the CSS transition-property.
Transition Property classes:
transition-none: This value is used to specify that no class will get a transition effect.
transition-all: All the class will get a transition effect. This is also the default value for this class.
transition: We can specify the names of CSS properties for which transition effect will be applied. We can also specify multiple properties by separating them with a comma.
transition-colors: This value is used to specify that the color class will get a transition effect.
transition-opacity: This value is used to specify that the opacity class will get a transition effect.
transition-shadow: This value is used to specify that the shadow class will get a transition effect.
transition-transform: This value is used to specify that the transformation into a defined shape.
Syntax:
<element class="transition-{properties}">...</element>
Example:
HTML
<!DOCTYPE html> <html><head>     <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"        rel="stylesheet"> </head>   <body class="text-center mx-4 space-y-2">     <h1 class="text-green-600 text-5xl font-bold">         GeeksforGeeks     </h1>     <b>Tailwind CSS Transition Property Class</b>     <div class="bg-green-200 m-8 grid grid-flow-col gap-4 p-5">         <button class="transition duration-500 ease-in-out                        bg-green-300 hover:bg-green-600 transform                        hover:-translate-y-1 hover:scale-110                        rounded-lg p-4 border border-green-900">            Hover me        </button>        <button class="transition-opacity duration-500 ease-in-out                        bg-green-300 hover:opacity-75 transform                        hover:-translate-y-1 hover:scale-110                        rounded-lg p-4 border border-green-900">            Hover me        </button>        <button class="transition-none duration-500 ease-in-out                        bg-green-300 hover:bg-green-600 transform                        hover:-translate-y-1 hover:scale-110                        rounded-lg p-4 border border-green-900">            Hover me        </button>        <button class="transition-colors duration-500 ease-in-out                        bg-green-300 hover:bg-yellow-600 transform                        hover:scale-110 rounded-lg p-4 border                        border-green-900 hover:border-black">            Hover me        </button>    </div> </body>   </html> 
Output:
            
different property class
Tailwind CSS
Tailwind-Transition & Animation
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove rows based on blanks in a column from a data frame in R?

Sometimes data is incorrectly entered into systems and that is the reason we must be careful while doing data cleaning before proceeding to analysis. A data collector or the sampled unit might enter blank to an answer if he or she does not find an appropriate option for the question. This also happens if the questionnaire is not properly designed or blank is filled by mistake. Also, if we have categorical variable then a control category might be filled with blank or we may want to have a blank category to use a new one at later stage. Whatever the reason behind, an analyst faces such type of problems. These blanks are actually inserted by using space key on computers. Therefore, if a data frame has any column with blank values then those rows can be removed by using subsetting with single square brackets.
Consider the below data frame:
Live Demo
> set.seed(24)
> x1<-sample(c(" ",1:5),20,replace=TRUE)
> x2<-rnorm(20,4,1.25)
> df1<-data.frame(x1,x2)
> df1
  x1   x2
1 2 3.413674
2 1 3.581267
3 2 5.920315
4 4 4.762493
5 1 4.645420
6 5 3.907114
7 1 3.243554
8 1.862944
9 3 3.664134
10 3.189261
11 3.882362
12 4 3.893074
13 4 4.149414
14 3.854630
15 4 2.820216
16 4 3.957828
17 3 3.268216
18 4 4.766064
19 1 5.896403
20 4.821726
Removing rows with blanks:
Live Demo
> df1[!df1$x1==" ",]
  x1   x2
1 2 3.413674
2 1 3.581267
3 2 5.920315
4 4 4.762493
5 1 4.645420
6 5 3.907114
7 1 3.243554
9 3 3.664134
12 4 3.893074
13 4 4.149414
15 4 2.820216
16 4 3.957828
17 3 3.268216
18 4 4.766064
19 1 5.896403
Live Demo
> y1<-sample(c(" ",rpois(5,1)),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2
 y1 y2
1 1 2
2 0 4
3   3
4 10
5 0 6
6 0 5
7 0 7
8 0 3
9 1 1
10 1 6
11 2 7
12 2 5
13 0 5
14   3
15 0 5
16 0 3
17 1 4
18 0 4
19 2 2
20 14
Removing rows with blanks:
> df2[!df2$y1==" ",]
 y1 y2
1 1 2
2 0 4
5 0 6
6 0 5
7 0 7
8 0 3
9 1 1
10 1 6
11 2 7
12 2 5
13 0 5
15 0 5
16 0 3
17 1 4
18 0 4
19 2 2
Saving a Networkx graph in GEXF format and visualize using Gephi

29 Sep, 2021
Prerequisites: Networkx
NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms and draw networks.
In this article we will discuss how we can save a networkx graph in GEXF format and then visualize it using Gephi. 
GEXF stands for Graph Exchange XML Format. Although it has features for supporting visualization of graphs but there are some limitations of visualization methods provided by NetworkX library. Hence, the need of using external tools like Gephi used for graph visualization arises. But we cannot straight away export graphs from python to Gephi we need to convert the graph into a format supported by it. GEXF is one such file format.
Gephi needs to installed first to be used: Gephi
To achieve this we will be employing write_gexf() function which as the name suggests saves a networkx graph into gexf format easily. 
Syntax:
networkx.write_gexf( G , path )
Parameter:
G: In this argument NetworkX graph object or simply the graph is sent as parameter.
path: In this argument a valid path for saving the graph is specified.
Approach:
Import module
Create a networkx graph
Save this graph in gexf format
Program:
Python3
# importing the required moduleimport networkx as nx # making a simple graph with 1 node.G = nx.path_graph(10) # saving graph created above in gexf formatnx.write_gexf(G, "geeksforgeeks.gexf")
Output:
A file named geeksforgeeks.gexf will be saved at the specified path, it can be viewed using any text editor which will be shown in XML.
The graph created in the above program will be visualized using Gephi.
Approach
Install Gephi
Import gexf file
After visualization this is what the graph looks like:
sumitgumber28
Python DSA-exercises
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lex program to check if a Date is valid or not

03 May, 2019
Problem: Write a Lex program to check if a date is valid or not.
Explanation:Flex (Fast lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Note: Format of Date is DD/MM/YYYY.
Examples:
Input: 02/05/2019
Output: It is a valid date

Input: 05/20/2019
Output: It is not a valid date 
Implementation:
/* Lex program to check if a date is valid or not */  %{   /* Definition section */   #include<stdio.h>   int i=0, yr=0, valid=0;%}  /* Rule Section */%%([0-2][0-9]|[3][0-1])\/((0(1|3|5|7|8))|(10|12))            \/([1-2][0-9][0-9][-0-9]) {valid=1;}  ([0-2][0-9]|30)\/((0(4|6|9))|11)         \/([1-2][0-9][0-9][0-9]) {valid=1;}  ([0-1][0-9]|2[0-8])\/02            \/([1-2][0-9][0-9][0-9]) {valid=1;}  29\/02\/([1-2][0-9][0-9][0-9])      { while(yytext[i]!='/')i++; i++;       while(yytext[i]!='/')i++;i++;       while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0');        if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;}  %%  // driver code main(){  yyin=fopen("vpn.txt", "r");  yylex();  if(valid==1) printf("It is a valid date\n");  else printf("It is not a valid date\n");} int yywrap(){ return 1;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js router.param() function

16 Jul, 2020
The parameters of router.param() are name and a function. Where name is the actual name of parameter and function is the callback function. Basically router.param() function triggers the callback function whenever user routes to the parameter. This callback function will be called for only single time in request response cycle, even if user routes to the parameter multiple times.
Syntax:
router.param(name, function)
Parameters of callback function are: 
req – the request objectres – the response objectnext – the next middleware functionid – the value of name parameter
req – the request object
res – the response object
next – the next middleware function
id – the value of name parameter
First you need to install express node module into your node js application.
Installations of express js is as follows:
npm init 
npm install express 
Create a file names app.js and paste the following code in the file.
//const express = require("express");const app = express();  //import router module from route.js fileconst userRoutes = require("./route");  app.use("/", userRoutes);  //PORTconst port = process.env.PORT || 8000;  //Starting a serverapp.listen(port, () => {  console.log(`app is running at ${port}`);});
We have to create another file named route.js in the same directory
Code for route.js file
const express = require("express");const router = express.Router();  router.param("userId", (req, res, next, id) => {    console.log("This function will be called first");    next();});  router.get("/user/:userId", (req, res) => {    console.log("Then this function will be called");    res.end();});// Export router module.exports = router;
Start the server by entering the following command
node app.js
Enter the following address into the browser
http://localhost:8000/user/343
You will see the following output in your terminal
Express.js
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector set() Method in Java

14 Aug, 2018
The Java.util.Vector.set() method is used to replace any particular element in the vector, created using the Vector class, with another element.
Syntax:
Vector.set(int index, Object element)
Parameters: This function accepts two mandatory parameters as shown in the above syntax and described below.
index: This is of integer type and refers to the position of the element that is to be replaced from the vector.
element: It is the new element by which the existing element will be replaced and is of the same object type as the vector.
Return Value: The method returns the previous value from the vector that is replaced with the new value.
Below programs illustrate the Java.util.Vector.set() method:
Program 1:
// Java code to illustrate set()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements in the vector        vec_tor.add("Geeks");        vec_tor.add("for");        vec_tor.add("Geeks");        vec_tor.add("10");        vec_tor.add("20");          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Using set() method to replace Geeks with GFG        System.out.println("The Object that is replaced is: "                           + vec_tor.set(2, "GFG"));          // Using set() method to replace 20 with 50        System.out.println("The Object that is replaced is: "                           + vec_tor.set(4, "50"));          // Displaying the modified vector        System.out.println("The new Vector is:" + vec_tor);    }}
Vector: [Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new Vector is:[Geeks, for, GFG, 10, 50]

Program 2:
// Java code to illustrate set()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<Integer> vec_tor = new Vector<Integer>();          // Use add() method to add elements in the vector        vec_tor.add(12);        vec_tor.add(23);        vec_tor.add(22);        vec_tor.add(10);        vec_tor.add(20);          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Using set() method to replace 12 with 21        System.out.println("The Object that is replaced is: "                           + vec_tor.set(0, 21));          // Using set() method to replace 20 with 50        System.out.println("The Object that is replaced is: "                           + vec_tor.set(4, 50));          // Displaying the modified vector        System.out.println("The new Vector is:" + vec_tor);    }}
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]

Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
main and init function in Golang

05 Sep, 2019
The Go language reserve two functions for special purpose and the functions are main() and init() function.
In Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a special type of function and it is the entry point of the executable programs. It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function.
Example:
// Go program to illustrate the// concept of main() function  // Declaration of the main packagepackage main  // Importing packagesimport (    "fmt"    "sort"    "strings"    "time")  // Main functionfunc main() {      // Sorting the given slice    s := []int{345, 78, 123, 10, 76, 2, 567, 5}    sort.Ints(s)    fmt.Println("Sorted slice: ", s)      // Finding the index    fmt.Println("Index value: ", strings.Index("GeeksforGeeks", "ks"))      // Finding the time    fmt.Println("Time: ", time.Now().Unix())  }
Output:
Sorted slice:  [2 5 10 76 78 123 345 567]
Index value:  3
Time:  1257894000

init() function is just like the main function, does not take any argument nor return anything. This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, so you cannot reference it from anywhere and you are allowed to create multiple init() function in the same program and they execute in the order they are created. You are allowed to create init() function anywhere in the program and they are called in lexical file name order (Alphabetical Order). And allowed to put statements if the init() function, but always remember to init() function is executed before the main() function call, so it does not depend to main() function. The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context.
Example:
// Go program to illustrate the// concept of init() function  // Declaration of the main packagepackage main  // Importing packageimport "fmt"  // Multiple init() functionfunc init() {    fmt.Println("Welcome to init() function")}  func init() {    fmt.Println("Hello! init() function")}  // Main functionfunc main() {    fmt.Println("Welcome to main() function")}
Output:
Welcome to init() function
Hello! init() function
Welcome to main() function

Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to run a function when the page is loaded in JavaScript ?

21 Jul, 2021
A function can be executed when the page loaded successfully. This can be used for various purposes like checking for cookies or setting the correct version of the page depending on the user browser.
Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded. The function that is required to be executed is given here.
Syntax:
<body onload="functionToBeExecuted">
Example:
<!DOCTYPE html><html>  <head>    <title>        How to run a function when the        page is loaded in javascript ?    </title></head>  <body onload="console.log('The Script will load now.')">          <h1 style="color: green">GeeksforGeeks</h1>          <b>        How to run a function when the        page is loaded in javascript ?    </b>          <p>        The script has been executed. Check        the console for the output.    </p></body>  </html>
Output:Console Output:
Method 2: The window object represents the browser window. The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property. It will run the function as soon as the webpage has been loaded.
Syntax:
window.onload = function exampleFunction() {      // Function to be executed}
Example:
<!DOCTYPE html><html>  <head>    <title>        How to run a function when the        page is loaded in javascript ?     </title></head>  <body>    <h1 style="color: green">        GeeksforGeeks    </h1>          <b>        How to run a function when the        page is loaded in javascript?    </b>          <p>        The script has been executed. Check        the console for the output.    </p>          <script>        window.onload = function exampleFunction() {            console.log('The Script will load now.');        }    </script></body>  </html>
Output:Console Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to Convert java.util.Date to java.sql.Date in Java?

17 Jan, 2022
Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whenever we need to store or read the data of DATE type in SQL, also Date class of java.sql package stores information only regarding the date, whereas Date class of java.util package stores both date and time information.
It must be remembered that when we need to convert one data form to another, we must use getTime() method of the Date class of java.util package.Though java.sql.Date class is a subclass of java.util.Date class, we can’t use java.sql.Date class wherever java.util.Date class must be passed, else it will violate the Liskov Substitution principle and our program will throw run time errors on execution, therefore it is not advised to pass SQL Date to methods that expect util date. Let us do discuss getTime() method prior to landing upon the implementation part.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by the Date object.
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throw any exceptions.
Example:
Java
// Java Program to Convert java.sql.Date to java.util.Date // Importing utility package// Importing SQL packageimport java.sql.*;import java.util.*; // Main Classpublic class GFG {     // Main driver method    public static void main(String[] args)    {         // Date class of Util package contains both date and        // time information        java.util.Date utilPackageDate            = new java.util.Date();         // Print and display the utility package date in        // java        System.out.println("Util Package date in Java is : "                           + utilPackageDate);         // Date class of sql package contains only date        // information without time        java.sql.Date sqlPackageDate            = new java.sql.Date(utilPackageDate.getTime());         // Print and display the SQL java package        System.out.println("SQL Package  date in Java : "                           + sqlPackageDate);    }}
  
Util Package date in Java is : Wed Mar 17 11:56:06 UTC 2021
SQL Package  date in Java : 2021-03-17
Note: The above date and time are fetched at the time program is being compiled and run. It will vary along the passage of time where the baseline for time calculations is epoch time
 
sweetyty
Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to reverse a Vector using STL in C++?

30 May, 2021
Given a vector, reverse this vector using STL in C++.Example:  
Input: vec = {1, 45, 54, 71, 76, 12}
Output: {12, 76, 71, 54, 45, 1}

Input: vec = {1, 7, 5, 4, 6, 12}
Output: {12, 6, 4, 5, 7, 1}
Approach: Reversing can be done with the help of reverse() function provided in STL. The Time complexity of the reverse() is O(n) where n is the length of the string.Syntax: 
reverse(start_index, last_index);
CPP
// C++ program to reverse Vector// using reverse() in STL #include <bits/stdc++.h>using namespace std; int main(){     // Get the vector    vector<int> a = { 1, 45, 54, 71, 76, 12 };     // Print the vector    cout << "Vector: ";    for (int i = 0; i < a.size(); i++)        cout << a[i] << " ";    cout << endl;     // Reverse the vector    reverse(a.begin(), a.end());     // Print the reversed vector    cout << "Reversed Vector: ";    for (int i = 0; i < a.size(); i++)        cout << a[i] << " ";    cout << endl;     return 0;}
Vector: 1 45 54 71 76 12 
Reversed Vector: 12 76 71 54 45 1
 
Time Complexity: O(n) where n is the length of the string.
CoderSaty
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
Inheritance in C++
Object Oriented Programming in C++
C++ Classes and Objects
Sorting a vector in C++
How to append data to <div> element using JavaScript ?

11 Oct, 2019
To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div.
Syntax:
document.getElementById("div_name").innerText += "Your Data Here";
Example:
<!DOCTYPE html> <html>   <head>     <title>        How to append data to        div using JavaScript ?    </title>           <meta charset="utf-8">           <meta name="viewport"        content="width=device-width, initial-scale=1">           <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">  </head>   <body>     <div class="container">         <h1 style="text-align:center;color:green;">             GeeksforGeeks         </h1>                   <hr>                  <form>             <div class="form-group">                 <label for="">Enter Your Name:</label>                 <input id="name" class="form-control"                    type="text"                    placeholder="Input Your Name Here">             </div>                          <div class="form-group text-center">                 <button id="my_button"                    class="btn btn-outline-success btn-lg"                        type="button">                     Add Name                 </button>             </div>         </form>                   <h3>List of Names:</h3>        <div id="my_div"></div>    </div>           <script>        function append_to_div(div_name, data){            document.getElementById(div_name).innerText += data;        }                  document.getElementById("my_button")                .addEventListener('click', function() {                          var user_name = document.getElementById("name");            var value = user_name.value.trim();                          if(!value)                alert("Name Cannot be empty!");            else                append_to_div("my_div", value+"\n");                          user_name.value = "";        });    </script>      </body>   </html>
Output:
Before Adding the Data:
After Adding the Data:
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Removing empty fields from MongoDB

To remove empty fields, use deleteMany(). Let us first create a collection with documents −
> db.removeEmptyFieldsDemo.insertOne({"StudentName":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9578f00858fb12e919")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9878f00858fb12e91a")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92b9c78f00858fb12e91b")
}
> db.removeEmptyFieldsDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce92ba078f00858fb12e91c")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.removeEmptyFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce92b9578f00858fb12e919"), "StudentName" : "" }
{ "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName" : "" }
{ "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
Following is the query to remove empty fields from MongoDB −
> db.removeEmptyFieldsDemo.updateMany({"StudentName": ""}, { $unset : {"StudentName" : 1 }});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Let us check the document once again −
> db.removeEmptyFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce92b9578f00858fb12e919") }
{ "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ce92b9c78f00858fb12e91b") }
{ "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
C# factorial

To calculate factorial in C#, you can use while loop and loop through until the number is not equal to 1.
Here n is the value for which you want the factorial −
int res = 1;
while (n != 1) {
   res = res * n;
   n = n - 1;
}
Above, let’s say we want 5! (5 factorial)
For that, n=5,
Loop Iteration 1 −
n=5
res = res*n i.e res =5;
Loop Iteration 2 −
n=4
res = res*n i.e. res = 5*4 = 20
Loop Iteration 3 −
n=3
res = res*n i.e. res = 20*3 = 60
In this way, all the iterations will give the result as 120 for 5! as shown in the following example.
Live Demo
using System;
namespace MyApplication {
   class Factorial {
      public int display(int n) {
         int res = 1;
         while (n != 1) {
            res = res * n;
            n = n - 1;
         }
         return res;
      }
      static void Main(string[] args) {
         int value = 5;
         int ret;
         Factorial fact = new Factorial();
         ret = fact.display(value);
         Console.WriteLine("Value is : {0}", ret );
         Console.ReadLine();
      }
   }
}
Value is : 120
Find and Draw Contours using OpenCV in Python

For the purpose of image analysis we use the Opencv (Open Source Computer Vision Library) python library. The library name that has to be imported after installing opencv is cv2.
In the below example we find the contours present in an image files. Contours help us identify the shapes present in an image. Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. The findContours function in OPenCV helps us identify the contours. Similarly the drawContours function help us draw the contours. Below is the syntax of both of them.
cv.FindContours(image, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE)
Where
image is the name of the image
Mode is Contour retrieval mode
Method is Contour approximation method

cv.DrawContours(img, contours, contourIdx, colour, thickness)
Where
image is the name of the image
contours – All the input contours.
contourIdx – Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
color – Color of the contours
thickness is how thick are the lines drawing the contour
In the below example we use the image below as our input image. Then run the below program to get the contours around it.
We can find three shapes in the above diagram. We can draw contours around all or some of them using the below program.
import cv2
# Load an image
image = cv2.imread(“path to image file”)
# Changing the colour-space
LUV = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)
# Find edges
edges = cv2.Canny(LUV, 10, 100)
# Find Contours
contours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Find Number of contours
print("Number of Contours is: " + str(len(contours)))
# Draw yellow border around two contours
cv2.drawContours(image, contours, 0, (0, 230, 255), 6)
cv2.drawContours(image, contours, 2, (0, 230, 255), 6)
# Show the image with contours
cv2.imshow('Contours', image)
cv2.waitKey(0)
Running the above code gives us the following result −
Number of Contours found = 3
And we get the below diagram showing the output.
Java if-else-if ladder statement

An if statement can be followed by an optional else if...elsestatement, which is very useful to test various conditions using single if...else if statement.
When using if, else if, else statements there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Following is the syntax of an if...else statement −
if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
   // Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
   // Executes when the Boolean expression 3 is true
}else {
   // Executes when the none of the above condition is true.
}
Live Demo
public class Test {
   public static void main(String args[]) {
      int x = 30;

      if( x == 10 ) {
         System.out.print("Value of X is 10");
      }else if( x == 20 ) {
         System.out.print("Value of X is 20");
      }else if( x == 30 ) {
         System.out.print("Value of X is 30");
      }else {
         System.out.print("This is else statement");
      }
   }
}
This will produce the following result −
Value of X is 30
Error-First Callback in Node.js - GeeksforGeeks

16 Feb, 2022
Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function.
The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null.
The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.
The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null.
Below is the implementation of Error-First Callback:
Create a file with the name index.js. The file requires an fs module. We will be implementing an error-first callback function on methods of the fs module. fs module can be used in the program by using the below command:
const fs = require("fs");
The file can be executed by using the below command:
node index.js
We will be using fs.readFile()  to show error-first callback function. 
Example 1:
Javascript
const fs = require("fs"); // This file does not existsconst file = "file.txt"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => {  if (err) {    return console.log(err);  }  console.log("Function successfully executed");}; // function execution// This will return// error because file do// not existfs.readFile(file, ErrorFirstCallback);
Output:
Example 2:
Javascript
const fs = require("fs"); // This file existsconst file = "file.txt"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => {  if (err) {    return console.log(err);  }  console.log("Function successfully executed");  console.log(data.toString());}; // function execution// This will return// data objectfs.readFile(file, ErrorFirstCallback);
Output:
adnanirshad158
sagar0719kumar
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Mongoose Populate() Method
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript