code-rag-bench/online-tutorials huggingface dataset:
Node.js Process exit Event

30 Jul, 2021
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. 
The process.exit() method is the method that is used to end the Node.js process. Every process action on the machine or a program is an event. For every event, there is even a handler associated with the particular event that executes when we fire the particular event. To assign an event handler to the event we use the object.on() method in the node.js. In this article, we will discuss process exit event in Node.js
Syntax:
process.on("exit", callbackfunction)
Parameters: This method takes the following two parameters.
exit: It is the name of the emit event in the process.
callbackfunction: It is the event handler of the event.
Return Type: The return type of this method is void.
Example 1:
index.js
console.log("Starting of the process")  // Binding the event to the eventhandlerprocess.on('exit',() => {    console.log("process.exit() method is fired")})  console.log("Ending of the process")  // Exiting the processprocess.exit()
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Example 2: Creating process exit event handler inside the user-defined event handler.
index.js
// Importing events objectconst events = require("events")  console.log("Starting of the process")const eventEmitter = new events.EventEmitter()  // Initializinging event Handlervar Handler = function() {     // Event handler of exit event   process.on('exit', () => {      console.log("process.exit() method is fired")   })}  // Bind the  user defined event eventEmitter.on("hello",Handler)  // Emit the eventeventEmitter.emit("hello")  console.log("Ending of the process")  // Exiting the processprocess.exit()
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Reference:https://nodejs.org/api/process.html#process_event_exit
gabaa406
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Tkinter – Frameless window

16 Oct, 2021
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing 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.
To create a Frameless window, we will use the overrideredirect() method.
Syntax:
root.overrideredirect(value)
To create a Frameless Window, we will pass value True or 1 as arguments in over ride redirect() method.
Below is the program that creates a normal tkinter window.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop()
Output:
Frame Window
Below is the Program to create a frameless tkinter window in python using the overrideredirect() method.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Use overrideredirect() methodroot.overrideredirect(True) # Execute tkinterroot.mainloop()
Output:
Frameless Window
ruhelaa48
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C/C++ Program for Finding the vertex, focus and directrix of the parabola?

A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from a point in the center (called focus) is a parabola.
The general equation for the parabola is
y = ax2 + bx + c
The vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight-line used to generate the curve.
Focus is the point with is equidistant from all points of the parabola.
Here, we will find the vertex, focus, and directrix of a parabola. There is a mathematical formula that finds all these values. And we will make a program using the mathematical formula for it.
Input:
a = 10,
b = 5,
c = 4
Output:
The vertex: (-0.25, 3.375)
The Focus: (-0.25, 3.4)
y-Directrix:-1036
The mathematical formula for find the vertex, focus and y-direction from the given values of the parabolic figure.
Vertex = {(-b/2a) , (4ac-b2/4a)}
Focus = {(-b/2a), (4ac-b2+1/4a)}
Direction = c - (b2 +1)*4a
#include <iostream>
using namespace std;
int main() {
   float a = 10, b = 5, c = 4;
   cout << "The vertex: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b)) / (4 * a)) << ")\n";
   cout << "The Focus: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b) + 1) / (4 * a)) << ")\n";
   cout << "y-Directrix:" << c - ((b * b) + 1) * 4 * a;
}
Java regex to exclude a specific String constant

regex ^((?!kk).)*$ returns true if a line does not contain kk, otherwise returns false
public class RegTest {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      String s="tutorials";
      boolean i=s.matches("^((?!kk).)*$");
      System.out.println(i);
   }
}
QlikView - Multi Box

A Multi Box represents the list of all the values from multiple fields as drop down values. Similar to list box, the selection of a value in Multi Box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Value
Sporting Goods,Outdoor Recreation,5642
Food, Beverages & Tobacco,2514
Apparel & Accessories,Clothing,2365
Apparel & Accessories,Costumes & Accessories,4487
Sporting Goods,Athletics,812
Health & Beauty,Personal Care,6912
Arts & Entertainment,Hobbies & Creative Arts,5201
Arts & Entertainment,Paintings,8451
Arts & Entertainment,Musical Instruments,1245
Hardware,Tool Accessories,456
Home & Garden,Bathroom Accessories,241
Food,Drinks,1247
Home & Garden,Lawn & Garden,5462
Office Supplies,Presentation Supplies,577
Hardware,Blocks,548
Baby & Toddler,Diapering,1247
Baby & Toddler,Toys,257
Home & Garden,Pipes,1241
Office Supplies,Display Board,2177

The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into the QlikView's memory.
LOAD Product_Line, 
     Product_category, 
     Value
FROM
[C:\Qlikview\data\product_sales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
Creation of Multi Box involves navigating through menu Layout → New Sheet Object → Multi Box. The following screen shows these steps.
Next we choose the fields of the Products sales tables to build the Multi Box.
Finishing the above steps brings the following screen, which shows the values of Product category as a Multi box.
Other Sheet Objects automatically get associated with the Multi Box and the association is easily observed by selecting values from the Multi Box.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
QTP - Virtual Objects

Sometimes, an application under test may contain standard window object but are not recognized by QTP. Under these circumstances, objects can be defined as virtual object(VO) of type button, link etc. so that user actions can be simulated on the virtual objects during execution.
Let us say we are automating a scenario in Microsoft Word. I activated MS word application and I click on any icon in the ribbon. For example, on the Ribbon, Insert tab is clicked and then the user clicks the "Picture" button. A button is recognized as WinObject; hence, importance of virtual objects is pronounced.
Window("Microsoft Word").WinObject("Ribbon").Click 145,45
Window("Microsoft Word").WinObject("Ribbon").WinObject("Picture...").Click 
170,104
Step 1 − In such scenarios, virtual Objects are created using Virtual Object Manager or New Virtual Object from "Tools" >> "Virtual Object" >> "New Virtual Object" and click the "Next" button.
Step 2 − Map the Object against the Class Type and click "Next".
Step 3 − Click "Mark Object" Button. A cross hair cursor would appear and mark the object that you would like to map and click "Next".
Step 4 − Select the parent of the Virtual object and click "Next".
Step 5 − Name the collection in which you would like to store the virtual object and click "Finish".
Virtual object Manager manages the collections of Virtual objects. Testers can add or Delete the Virtual Objects from the Virtual Object manager.
Navigation to Virtual object Manager : "Tools" >> "Virtual Object Manager" as shown below −
After creating the Virtual Objects, the created object can be used as shown below −
Window("Microsoft Word").WinObject("Ribbon").VirtualButton("button").Click

QTP does not support virtual objects for analog or low-level recording.
QTP does not support virtual objects for analog or low-level recording.
Checkpoints cannot be added on Virtual Objects.
Checkpoints cannot be added on Virtual Objects.
Virtual Objects are not controlled by Object Repository.
Virtual Objects are not controlled by Object Repository.
Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects.
Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects.
Object Spy cannot be used on Virtual Object.
Object Spy cannot be used on Virtual Object.
The test execution will fail if the screen resolution changes as the co-ordinates change.
The test execution will fail if the screen resolution changes as the co-ordinates change.
Application Window should be of same screen size so that Virtual objects are captured correctly.
Application Window should be of same screen size so that Virtual objects are captured correctly.

    108 Lectures 
     8 hours 

 Pavan Lalwani
 Print
 Add Notes
 Bookmark this page
jQuery Tutorial

jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery is easy to learn.
With our online editor, you can edit the code, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Use the correct selector to hide all <p> elements.
$("").hide();

Start the Exercise
Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself.
Test your jQuery skills at W3Schools!
At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events.
Get certified by completing the JQUERY course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
html.parser — Simple HTML and XHTML parser in Python

The HTMLParser class defined in this module provides functionality to parse HTML and XHMTL documents. This class contains handler methods that can identify tags, data, comments and other HTML elements.
We have to define a new class that inherits HTMLParser class and submit HTML text using feed() method.
from html.parser import HTMLParser
class parser(HTMLParser):
pass
p = parser()
p.feed('<a href = "www.tutorialspoint.com"></a>')
We have to override its following methods
handle_starttag(tag, attrs):
HTML tags normally are in pairs of starting tag and end tag. For example <head> and </head>. This method is called to handle the start of a tag.
Name of the tag converted to lower case. The attrs argument stands for attributes found inside the tag’s <> brackets.
For instance, for the tag <a href = "www.tutorialspoint.com"></a>, is fed to the parser object.
from html.parser import HTMLParser
class parser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
for attr in attrs:
print(" attr:", attr)
p = parser()
p.feed('<a href = "www.tutorialspoint.com">')
Start tag: a
attr: ('href', 'www.tutorialspoint.com')
handle_endtag(tag):
This method is called to handle the end tag of an element.
def handle_endtag(self, tag):
print ("end tag",tag)
handle_data(data):
This method is called to process arbitrary data between tags. For example:
def handle_data(self, data):
print (data)
p = parser()
html = '''
<html>
   <body>
      <h1>Tutorialspoint</h1>
      <b>Python standard library</b>
      <p>HTML module</p>
   </body>
</html>'''
p.feed(html)
Start tag: h1
Tutorialspoint
end tag h1
Start tag: b
Python standard library
end tag b
Start tag: p
HTML module
end tag p
Other methods in HTMLParser class are as follows:
Return the text of the most recently opened start tag.
Return current line number and offset.
Similar to handle_starttag(), but called when the parser encounters an XHTML-style empty tag (<img ... />).
This method is called when a comment is encountered (e.g. <!--comment-->).
p5.js | floor() function - GeeksforGeeks

09 Apr, 2019
The floor() function in p5.js is used to calculate the floor value of a number. This function maps to the Math.floor() of javascript. It calculates the closest int value that is less than or equal to the value of the parameter.
Syntax
floor(number)

Parameters: The function accepts only one parameter as mentioned above and described below:
number : This parameter stores the number to compute.Below program illustrates the floor() function in p5.js:Example:function setup() {      //create Canvas of size 270*80      createCanvas(270, 80);}  function draw() {    background(220);    //initialize the parameter      let x = 65.67;    //call to floor() function      let y = floor(x);    textSize(16);    fill(color('red'));    text("Given Number is : " + x, 50, 30);    text("Computed Number is : " + y, 50, 50);}Output:Reference: https://p5js.org/reference/#/p5/floorMy Personal Notes
arrow_drop_upSave
Below program illustrates the floor() function in p5.js:Example:
function setup() {      //create Canvas of size 270*80      createCanvas(270, 80);}  function draw() {    background(220);    //initialize the parameter      let x = 65.67;    //call to floor() function      let y = floor(x);    textSize(16);    fill(color('red'));    text("Given Number is : " + x, 50, 30);    text("Computed Number is : " + y, 50, 50);}
Output:
Reference: https://p5js.org/reference/#/p5/floor
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Style Bootstrap 4 card with bg-primary class

Use the bg-primary class in Bootstrap 4, to add important stuff to a card and set blue background color.
Style the Bootstrap 4 card as in the following code snippet −
<div class="card bg-primary text-white">
  <div class="card-body">Medical Books</div>
</div>
I have set the body of the card in the card-body class −
<div class="card-body">
  Medical Books
</div>
To implement the bg-primary class in Bootstarp 4, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</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.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h2>Books</h2>
    <div class="card bg-info text-white">
      <div class="card-body">History Books</div>
    </div><br>
    <div class="card bg-primary text-white">
      <div class="card-body">Medical Books</div>
    </div><br>
  </div>

</body>
</html>
C++ Program to Store Information of a Student in a Structure

A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows.
struct employee {
   int empID;
   char name[50];
   float salary;
};
A program that stores student information in a structure is given as follows.
 Live Demo
#include <iostream>
using namespace std;
struct student {
   int rollNo;
   char name[50];
   float marks;
   char grade;
};
int main() {
   struct student s = { 12 , "Harry" , 90 , 'A' };
   cout<<"The student information is given as follows:"<<endl;
   cout<<endl;
   cout<<"Roll Number: "<<s.rollNo<<endl;
   cout<<"Name: "<<s.name<<endl;
   cout<<"Marks: "<<s.marks<<endl;
   cout<<"Grade: "<<s.grade<<endl;
   return 0;
}
The student information is given as follows:
Roll Number: 12
Name: Harry
Marks: 90
Grade: A
In the above program, the structure is defined before the main() function. The structure contains the roll number, name, marks and grade of a student. This is demonstrated in the following code snippet.
struct student {
   int rollNo;
   char name[50];
   float marks;
   char grade;
};
In the main() function, an object of type struct student is defined. This contains the roll number, name, marks and grade values. This is shown as follows.
struct student s = { 12 , "Harry" , 90 , 'A' };
The structure values are displayed in the following manner.
cout<<"The student information is given as follows:"<<endl;
cout<<endl;
cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl;
AWT Event Listeners

The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept  instance of MouseEvent, where MouseEvent derives from EventObject.
It is a marker interface which every listener interface has to extend.This class is defined in java.util package.
Following is the declaration for java.util.EventListener interface:
public interface EventListener
Following is the list of commonly used event listeners.
ActionListener
This interface is used for receiving the action events.
ComponentListener
This interface is used for receiving the component events.
ItemListener
This interface is used for receiving the item events.
KeyListener
This interface is used for receiving the key events.
MouseListener
This interface is used for receiving the mouse events.
TextListener
This interface is used for receiving the text events.
WindowListener
This interface is used for receiving the window events.
AdjustmentListener
This interface is used for receiving the adjusmtent events.
ContainerListener
This interface is used for receiving the container events.
MouseMotionListener
This interface is used for receiving the mouse motion events.
FocusListener
This interface is used for receiving the focus events.

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
How to programmatically take a screenshot on iOS?

In this post we will learn how to take screen shot programmatically in iOS.
We will add on textField where we will change the value, take the screen shot by press of a button and then show the screen shot in an imageView which we will place just below the button itself.
Remember that you can add this functionality on long press or any other gesture, and even save the image if you want. But right now we will just focus on capturing the screen shot and showing it on an image view.
So let’s get started
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TakeScreenShot”
Step 2 − Open Main.storyboard add one UITextField, one button and one UIImageView as shown below 
Step 3 − Attach one @IBOutlet for the image view. Name it snapShotImageView. This is the image view where we will sow the captured screen shot.
Step 4 − Add one @IBAction for touchUpInside of ‘Take Snap Shot’ button. Name the function as takeSnapShotClicked.
Step 5 − In viewDidLoad of ViewController class set the border color and width for image the imageView to distinguish it from other part of the view.
self.snapShotImageView.layer.borderColor = UIColor.red.cgColor
self.snapShotImageView.layer.borderWidth = 2.0
Step 6 − We will be using the following method to capture the screenshot.
Start the graphic context.
Capture the current context in a variable.
Int the context variable, render the current views layer.
Get the image from context variable. Note that the context at this point will contain the screen shot of currently whatever is available on the view.
We will set the captured image from context to our imageView
End the graphic context
All of the above we will do in takeSnapShotClicked method. Which now would look like this
@IBAction func takeSnapShotClicked(_ sender: Any) {
   UIGraphicsBeginImageContextWithOptions(self.view.layer.frame.size, false, UIScreen.main.scale);
   guard let context = UIGraphicsGetCurrentContext() else {return }
   self.view.layer.render(in:context)
   self.snapShotImageView.image = UIGraphicsGetImageFromCurrentImageContext()
   UIGraphicsEndImageContext()
}
Step 7 − Build and run the project. Click on the take snapshot button. You should see the snapshot in the bottom image view.
LocalStorage in ReactJS

In this article, we are going to see how to set and retrieve data in the localStorage memory of the user’s browser in a React application.
LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time.
// To store data
localStorage.setItem('Name', 'Rahul');

// To retrieve data
localStorage.getItem('Name');

// To clear a specific item
localStorage.removeItem('Name');

// To clear the whole data stored in localStorage
localStorage.clear();
In this example, we will build a React application which takes the username and password from the user and stores it as an item in the localStorage of the user’s computer.
App.jsx
import React, { useState } from 'react';

const App = () => {

   const [name, setName] = useState('');
   const [pwd, setPwd] = useState('');

   const handle = () => {
      localStorage.setItem('Name', name);
      localStorage.setItem('Password', pwd);
   };
   const remove = () => {
      localStorage.removeItem('Name');
      localStorage.removeItem('Password');
   };
   return (
      <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            placeholder="Password"
            value={pwd}
            onChange={(e) => setPwd(e.target.value)}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {localStorage.getItem('Name') && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {localStorage.getItem('Password') && (
            <div>
               Password: <p>{localStorage.getItem('Password')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   );
};
export default App;
In the above example, when the Done button is clicked, the handle function is executed which will set the items in the localStorage of the user and display it. But when the Remove button is clicked, the remove function is executed which will remove the items from the localStorage.
This will produce the following result.
CSS Grid Lines

Grid Lines are columns lines and row lines.
Columns lines are the lines between columns and row lines between rows.
The following is an example of grid lines
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .container {
            display: grid;
            background-color: green;
            grid-template-columns: auto auto;
            padding: 20px;
            grid-gap: 20px;
         }
         .container > div {
            background-color: orange;
            border: 2px solid gray;
            padding: 35px;
            font-size: 30px;
            text-align: center;
         }
         .ele1 {
            grid-row-start: 1;
            grid-row-end: 6;
         }
      </style>
   </head>
   <body>
      <h1>Game Board</h1>
      <div class = "container">
         <div class = "ele1">1</div>
         <div class = "ele2">2</div>
         <div class = "ele3">3</div>
         <div class = "ele4">4</div>
         <div class = "ele5">5</div>
         <div class = "ele6">6</div>
      </div>
   </body>
</html>
How to use window.location to redirect to a different URL with JavaScript?

You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −
You can try to run the following code to learn how to use window.location to redirect to another URL. Here, we will redirect to the home page
Live Demo
<html>
   <head>
      <script>
         <!--
            function Redirect() {
               window.location.assign("https://www.tutorialspoint.com");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button, you will be redirected to home page.</p>
      <input type = "button" value="Redirect Me" onclick="Redirect();" />
   </body>
</html>
Decimal.Compare() Method in C#

The Decimal.Compare() method in C# is used to compare two specified Decimal values.
Following is the syntax −
public static int Compare (decimal val1, decimal val2);
Above, val1 is the first value to compare, whereas Val is the second value to compare.
The return value is less than zero if val1 is less than val2. Return value is 0, if Val = val2, whereas greater than zero, if val1 is greater than val2.
Let us now see an example to implement the Decimal.Compare() method −
using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 45.85m;
      Decimal val2 = 35.45m;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Comparison Value = "+Decimal.Compare(val1,val2));
   }
}
This will produce the following output −
Decimal 1 = 45.85
Decimal 2 = 35.45
Comparison Value = 1
Let us now see another example to implement the Decimal.Compare() method −
using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 65.15m;
      Decimal val2 = 65.15m;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Comparison Value = "+Decimal.Compare(val1,val2));
   }
}
This will produce the following output −
Decimal 1 = 65.15
Decimal 2 = 65.15
Comparison Value = 0
Container for form input and label with Bootstrap

Use the .form-group class in Bootstrap to set a container for form input and label &minus
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form role = "form">
         <div class = "form-group">
            <label for = "name">Student Name</label>
            <input type = "text" class = "form-control" id = "name" placeholder = "Enter Student Name">
         </div>
        <div class = "form-group">
           <label for = "inputfile">Upload Resume</label>
           <input type = "file" id = "inputfile">
           <p class = "help-block">Example block-level help text here.</p>
        </div>
        <button type = "submit" class = "btn btn-primary">Next</button>
      </form>
   </body>
</html>
Draw Spiralling Circles Using Turtle Graphics in Python - GeeksforGeeks

01 Oct, 2020
Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module, and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc.
Approach:
Import and create a turtle instance.Set the graphical visuals as per your needs.Run a for loop for some integer values i.For each value of i, draw a circle with a radius as i.Now rotate the turtle by a fixed degree. 
Import and create a turtle instance.
Set the graphical visuals as per your needs.
Run a for loop for some integer values i.
For each value of i, draw a circle with a radius as i.
Now rotate the turtle by a fixed degree. 
Below is the implementation of the above approach
Python3
# importing turtleimport turtle  # initialise the turtle instanceanimation = turtle.Turtle()  #creating animation# changes speed of turtleanimation.speed(0)  # hiding turtle animation.hideturtle()  # changing background coloranimation.getscreen().bgcolor("black")  # color of the animationanimation.color("red")  for i in range(100):          # drawing circle using circle function     # by passing radius i    animation.circle(i)      # changing turtle face by 5 degree from it's    # previous position after drawing a circle    animation._rotate(5)
Output: 
Python-turtle
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
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Geographical plotting using Python plotly

Python provides various libraries to handle geographical and graph data. Python plotly is one of those libraries which are used to draw geographical graphs. Plotly is a free and open source library. Plotly helps to plot various kinds of graphs like Line charts, Horizontal bar charts, bar charts, dashboards, scatter plots, bubble charts, pie charts and many more.
# Import important python geographical libraries.
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
# Must enable in order to use plotly off-line.
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot
# To establish connection
init_notebook_mode()
# type defined is choropleth to
# plot geographical plots
data = dict(type = 'choropleth',
# location: LosAngles, NewJersey, Texas
locations = ['AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL','IN','IA', 'KS', 'KY'],
# States of USA
locationmode = 'USA-states',
# colorscale can be added as per requirement
colorscale = 'Portland',
# text can be given anything you like
text = ['state 1', 'state 2', 'state 3', 'state 4', 'state 5','state 6', 'state 7', 'state 8', 'state 9', 'state 10','state 11', 'state 12', 'state 13', 'state 14', 'state 15','state 16', 'state 17', 'state 18', 'state 19', 'state 20'],
z = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0],
colorbar = {'title': 'USA-states'})
layout = dict(geo ={'scope': 'usa'})
# passing data dictionary as a list
choromap = go.Figure(data = [data], layout = layout)
# plotting graph
iplot(choromap)
With the help of the plot, we can visualize the data (input items) with different ways based on what we want to achieve. We can visualize the different states of India (29) with different colors based on what political party is ruling it or based on food choices (veg/non-veg) which states prefer what kind of food or any other thing you image. Plotly provides a very powerful and interactive library to visualize data in an easily understandable way (graph).
C++ program to Find Sum of Natural Numbers using Recursion

The natural numbers are the positive integers starting from 1.
The sequence of natural numbers is −
1, 2, 3, 4, 5, 6, 7, 8, 9, 10......
The program to find the sum of first n natural numbers using recursion is as follows.
 Live Demo
#include <iostream>
using namespace std;
int sum(int n) {
   if(n == 0)
   return n;
   else
   return n + sum(n-1);
}
int main() {
   int n = 10;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
   return 0;
}
Sum of first 10 natural numbers is 55
In the above program, the function sum() is a recursive function. If n is 0, it returns 0 as the sum of the first 0 natural numbers is 0. If n is more than 0, then sum recursively calls itself itself with the value n-1 and eventually returns the sum of n, n-1, n-2......2,1. The code snippet that demonstrates this is as follows.
int sum(int n) {
   if(n == 0)
   return n;
   else
   return n + sum(n-1);
}
In the function main(), the sum of the first n natural numbers is displayed using cout. This can be seen as follows −
cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
Multiplication of two Matrices in Single line using Numpy in Python

Matrix multiplication is a lengthy process where each element from each row and column of the matrixes are to be multiplied and added in a certain way. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first and the number of columns of the second matrix.
For smaller matrices we may design nested for loops and find the result. For bigger matrices we need some built in functionality in python to tackle this. We will see both approaches below.
We take two matrices of dimension 2x3 and 3x2 (rows x columns). The result of matrix multiplication is a 2x2 matrix. We have a nested for loop designed to go through the columns of A and rows of B and add the products of the values in those rows and columns.
 Live Demo
#matrix A with 2 rows
A = ([5,10,15],[20,25,30])

#matrix B with 2 columns
B = ([4,8],[12,10],[14,16])

result = [[0 for x in range(2)] for y in range(2)]

for i in range(len(A)):
   # iterate through columns of A
   for j in range(len(B[0])):
      # iterate through rows of B
      for k in range(len(B)):
         result[i][j] += A[i][k] * B[k][j]
for r in result:
   print(r)

Running the above code gives us the following result:
[350, 380]
[800, 890]
Numpy has a in-built function named dot, that carries out the matrix multiplication. Our number of lines of program becomes very less and the syntax is also very simple.
 Live Demo
import numpy as np

#matrix A
matrix_A = ([5,10,15],[20,25,30])

#matrix B
matrix_B = ([4,8],[12,10],[14,16])
result = np.dot(matrix_A,matrix_B)

# Result
print(result)
Running the above code gives us the following result:
[[350 380]
[800 890]]
SQL Query to Get Yesterday and Tomorrow

08 Apr, 2021
Queries help the users to interact with a database for creating, insertion, deleting, updating data in a database with different queries.
In this article let us see how to get yesterday and tomorrow with respect to the given dates in the database.
Example –
Given date: 2021-03-23Yesterday: 2021-03-22 MondayTomorrow: 2021-03-24 Wednesday
Creating a database calendar:
CREATE DATABASE calendar;
Using the database calendar
USE calendar;
Creating a Table schedule:
CREATE TABLE schedule
(dates date);
Viewing the description of the table:
DESCRIBE schedule;
Inserting rows into the schedule:
INSERT INTO schedule VALUES('2021-03-23');
INSERT INTO schedule VALUES('2020-08-04');
INSERT INTO schedule VALUES('2021-06-08');
INSERT INTO schedule VALUES('2030-04-04');
INSERT INTO schedule VALUES('2025-09-13');
  
Viewing the data in the table:
SELECT* FROM schedule;
Query to get the yesterday and tomorrow of current date:
To get the yesterday and tomorrow of the current date we can use the CURRDATE() function in MySQL and subtract 1 from it to get yesterday and add 1 to it to get tomorrow.
SELECT CURDATE(),
    DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS yesterday,
    DATE_ADD(CURDATE(),INTERVAL 1 DAY) AS tomorrow;
Here we can change the default column header to some other name by using AS.
Example1: 
Query to get yesterday and tomorrow of dates in the table:
Syntax:SELECT CURDATE(),DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS some_nameDATE_ADD(CURDATE(),INTERVAL 1 DAY) AS some_name;
 SELECT dates,
     DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,
     DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow
     FROM schedule;
Example2: 
Query to get the yesterday and tomorrow dates in the table with weekdays:
Syntax:
SELECT column_name,DATE_SUB(column_name,INTERVAL 1 DAY) AS some_name,DATE_ADD(column_name,INTERVAL 1 DAY) AS some_name,DAYNAME(current_date),DAYNAME(previous_day),DAYNAME(next_day); 
  SELECT dates,
     DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,
     DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow,
     DAYNAME(dates) AS weekdayofdate,
     DAYNAME(DATE_SUB(dates,INTERVAL 1 DAY)) AS weekdayofYd,
     DAYNAME( DATE_ADD(dates,INTERVAL 1 DAY)) AS weekdayofTm
     FROM schedule;
                    
          
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to get the Highlighted/Selected text in JavaScript?

15 Mar, 2021
There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below:
Example-1: By using window.getSelection property
function selection(){
if (window.getSelection)
       return window.getSelection();
}

Example 2: By using document.getSelection property
function selection(){
if (document.getSelection)
       return document.getSelection();
}

Example 3: By using document.selection property
function selection(){
if (document.selection)
       return document.selection.createRange().text;;
}

Time to try out the code. Run the code, select a text and press the button to show the selected text:Example:
<html>  <head>    <title>Selected Text</title></head>  <body>    <center>        <h1 style=color:green>          GeeksforGeeks      </h1>        <script>            // Function to get the Selected Text             function getSelectedText() {                var selectedText = '';                  // window.getSelection                if (window.getSelection) {                    selectedText = window.getSelection();                }                // document.getSelection                else if (document.getSelection) {                    selectedText = document.getSelection();                }                // document.selection                else if (document.selection) {                    selectedText =                     document.selection.createRange().text;                } else return;                // To write the selected text into the textarea                document.testform.selectedtext.value = selectedText;            }        </script>          <p>Select any part of this sentence          and press the button</p>          <!--Button to invoke the          function to get the selected text-->        <input type="button"               value="Get Selection"                onmousedown="getSelectedText()">                <!--Form to show the selected text as output-->        <form name="testform">            <textarea name="selectedtext"                       rows="5"                      cols="20"></textarea>        </form>    </center></body>  </html>
Output:Before:After:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a NumPy array to an image

02 Sep, 2020
NumPy Or numeric python is a popular library for array manipulation. Since images are just an array of pixels carrying various color codes. NumPy can be used to convert an array into image. Apart from NumPy we will be using PIL or Python Image Library also known as Pillow to manipulate and save arrays.
Approach:
Create a numpy array.Reshape the above array to suitable dimensions.Create an image object from the above array using PIL library.Save the image object in a suitable file format.
Create a numpy array.
Reshape the above array to suitable dimensions.
Create an image object from the above array using PIL library.
Save the image object in a suitable file format.
Below is the implementation:
Python3
# Python program to convert# numpy array to image  # import required librariesimport numpy as npfrom PIL import Image as im  # define a main functiondef main():      # create a numpy array from scratch    # using arange function.    # 1024x720 = 737280 is the amount     # of pixels.    # np.uint8 is a data type containing    # numbers ranging from 0 to 255     # and no non-negative integers    array = np.arange(0, 737280, 1, np.uint8)          # check type of array    print(type(array))          # our array will be of width     # 737280 pixels That means it     # will be a long dark line    print(array.shape)          # Reshape the array into a     # familiar resoluition    array = np.reshape(array, (1024, 720))          # show the shape of the array    print(array.shape)      # show the array    print(array)          # creating image object of    # above array    data = im.fromarray(array)          # saving the final output     # as a PNG file    data.save('gfg_dummy_pic.png')  # driver codeif __name__ == "__main__":      # function call  main()
Output:
<class 'numpy.ndarray'>
(737280,)
(1024, 720)
[[  0   1   2 ... 205 206 207]
 [208 209 210 ... 157 158 159]
 [160 161 162 ... 109 110 111]
 ...
 [144 145 146 ...  93  94  95]
 [ 96  97  98 ...  45  46  47]
 [ 48  49  50 ... 253 254 255]]

        gfg_dummy_pic.png 1024 x 720  
Note: Every array can’t be converted into an image because each pixel of an image consist of specific color code and if the given array is not in a suitable format the libraries won’t be able to process it Properly.
Python numpy-arrayManipulation
Python-numpy
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to convert image into base64 string using JavaScript ?

12 Apr, 2021
Approach :
Here we will create a gfg.js file which will include or JavaScript code and one gfg.html file.
Now we will put onchange  on input type and this will execute a function  imageUploaded() when you upload an image.
Now we will use file reader and use onload event in file reader than we will get image url and we need to remove some text to get the base64 string and store in variable named base64String and print on console.
And if you want to use this base64 you can write logic on button click like here we will alert this base64 String.
HTML
Javascript
<!DOCTYPE html><html lang="en">  <head>    <script src="gfg.js"></script></head>  <body>    <input type="file" name="" id="fileId"         onchange="imageUploaded()">    <br><br>      <button onclick="displayString()">        Display String    </button></body>  </html>
let base64String = "";  function imageUploaded() {    var file = document.querySelector(        'input[type=file]')['files'][0];      var reader = new FileReader();    console.log("next");          reader.onload = function () {        base64String = reader.result.replace("data:", "")            .replace(/^.+,/, "");          imageBase64Stringsep = base64String;          // alert(imageBase64Stringsep);        console.log(base64String);    }    reader.readAsDataURL(file);}  function displayString() {    console.log("Base64String about to be printed");    alert(base64String);}
Output:
JavaScript-Methods
JavaScript-Questions
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Compute Density of the Distribution Function in R Programming – dunif() Function

30 Jun, 2020
dunif() function in R Language is used to provide the density of the distribution function.
Syntax:dunif(x, min = 0, max = 1, log = FALSE)
Parameters:x: represents vectormin, max: represents lower and upper limits of the distributionlog: represents logical value for probabilities
Example 1:
# Create vector of random deviationu <- runif(20)  dunif(u) == u  print(dunif(u))
Output:
 
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Example 2:
# Output to be present as PNG filepng(file = "dunifGFG.png")  # Plot densitycurve(dunif(x, min = 2, max = 6), 0, 8, ylim = c(0, 0.5),      ylab = "f(x)", main = "Uniform Density f(x)")  # Saving the filedev.off()
Output:
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert Image to Byte Array in java?

Java provides ImageIO class for reading and writing an image. To convert an image to a byte array –
Read the image using the read() method of the ImageIO class.
Create a ByteArrayOutputStream object.
Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class.
Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageToByteArray {
   public static void main(String args[]) throws Exception{
      BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ImageIO.write(bImage, "jpg", bos );
      byte [] data = bos.toByteArray();
   }
}