code-rag-bench/online-tutorials huggingface dataset:
Python Program for simple interest - GeeksforGeeks

18 Apr, 2020
Simple interest formula is given by:Simple Interest = (P x T x R)/100Where,P is the principle amountT is the time andR is the rate
Examples:
EXAMPLE1:
Input : P = 10000
        R = 5
        T = 5
Output :2500
We need to find simple interest on 
Rs. 10,000 at the rate of 5% for 5 
units of time.

EXAMPLE2:
Input : P = 3000
        R = 7
        T = 1
Output :210

Python3
# Python3 program to find simple interest# for given principal amount, time and# rate of interest.    def simple_interest(p,t,r):    print('The principal is', p)    print('The time period is', t)    print('The rate of interest is',r)          si = (p * t * r)/100          print('The Simple Interest is', si)    return si      # Driver codesimple_interest(8, 6, 8)
The principal is 8
The time period is 6
The rate of interest is 8
The Simple Interest is 3.84

#Please refer complete article on Program to find simple interest for more details!
AnkanDatta
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Iterate over characters of a string in Python
Python Program for Bubble Sort
Python | Convert set into a list
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python | Convert a list into a tuple
PyQt5 – How to hide the title bar of window ? - GeeksforGeeks

26 Mar, 2020
When we design the GUI (Graphical User Interface) application using PyQt5, there exist the window. A window is a (usually) rectangular portion of the display on a computer monitor that presents its contents (e.g., the contents of a directory, a text file or an image) seemingly independently of the rest of the screen. Windows are one of the elements that comprise a graphical user interface (GUI).
In a window we can see there exist a title bar which comprises the icon and title on the left size and on the right side there exist control button.
In this article we will see how we can hide title bar. In order to do so we will use setWindowFlag() method and pass which belongs to the QWidget class.
Syntax : setWindowFlag(Qt.FramelessWindowHint)
Argument : It takes Window type as argument.
Action performed : It removes the title bar.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import Qtimport sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # this will hide the title bar        self.setWindowFlag(Qt.FramelessWindowHint)          # set the title        self.setWindowTitle("no title")          # setting  the geometry of window        self.setGeometry(100, 100, 400, 300)          # creating a label widget        # by default label will display at top left corner        self.label_1 = QLabel('no title bar', self)          # moving position        self.label_1.move(100, 100)          # setting up border and background color        self.label_1.setStyleSheet("background-color: lightgreen;                                    border: 3px solid green")          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
Stack in Python
Matplotlib.axes.Axes.set_xticklabels() in Python - GeeksforGeeks

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_xticklabels() function in axes module of matplotlib library is used to Set the x-tick labels with list of string labels.
Syntax: Axes.set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs)
Parameters: This method accepts the following parameters.
labels : This parameter is the list of of string labels.
fontdict : This parameter is the dictionary controlling the appearance of the ticklabels.
minor : This parameter is used whether set major ticks or to set minor ticks
Return value: This method returns a list of Text instances.
Below examples illustrate the matplotlib.axes.Axes.set_xticklabels() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Polygon        def func(x):    return (x - 4) * (x - 6) * (x - 5) + 100        a, b = 2, 9  # integral limitsx = np.linspace(0, 10)y = func(x)    fig, ax = plt.subplots()ax.plot(x, y, "k", linewidth = 2)ax.set_ylim(bottom = 0)    # Make the shaded regionix = np.linspace(a, b)iy = func(ix)verts = [(a, 0), *zip(ix, iy), (b, 0)]  poly = Polygon(verts, facecolor ='green',               edgecolor ='0.5', alpha = 0.4)ax.add_patch(poly)    ax.text(0.5 * (a + b), 30,         r"$\int_a ^ b f(x)\mathrm{d}x$",        horizontalalignment ='center',         fontsize = 20)    fig.text(0.9, 0.05, '$x$')fig.text(0.1, 0.9, '$y$')    ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)  ax.set_xticks((a, b-a, b))ax.set_xticklabels(('$a$', '$valx$', '$b$'))    fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt    # Fixing random state for reproducibilitynp.random.seed(19680801)    x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape)    fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2)   ax.set_xticks([0, np.pi, 2 * np.pi])ax.set_xticklabels(['0', r'$\pi$', r'2$\pi$'])    ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)    fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
process.argv() Method in Node.js

The process.argv() method is used for returning all the command-line arguments that were passed when the Node.js process was being launched. The first element will always contains the same value as process.execPath.
process.argv()
Since it returns all the command line arguments passed before the node.js process. It does not need any inputs from the user.
Create a file with name – argv.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node argv.js
argv.js
 Live Demo
// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Printing property value for process.argv
console.log(process.argv);
C:\home\node>> node argv.js
[ '/usr/bin/node',
'/home/node/test/process.js' ]
Let's take a look at one more example.
 Live Demo
// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Printing process.argv property value
var args = process.argv;

console.log("Total number of arguments are: "+args.length);
args.forEach((val, index) => {
   console.log(`${index}: ${val}`);
});
C:\home\node>> node argv.js
Total number of arguments are: 2
0: /usr/bin/node
1: /home/node/test/process.js
Implement multiple LIKE operators in a single MySQL query

To implement multiple LIKE clauses, the syntax is as follows −
select * from yourTableName
 where yourColumnName1 LIKE ('%yourValue1%' or yourColumnName2 LIKE '%yourValue2%') or (yourColumnName3 LIKE '%yourValue3');
Let us first create a table −
mysql> create table DemoTable1534
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20),
   -> ClientAge int,
   -> ClientCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Chris Brown',29,'AUS');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('David Miller',49,'UK');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('John Doe',43,'US');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Adam Smith',38,'US');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Carol Taylor',36,'UK');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1534;
This will produce the following output −
+----------+--------------+-----------+-------------------+
| ClientId | ClientName   | ClientAge | ClientCountryName |
+----------+--------------+-----------+-------------------+
|        1 | Chris Brown  |        29 | AUS               |
|        2 | David Miller |        49 | UK                |
|        3 | John Doe     |        43 | US                |
|        4 | Adam Smith   |        38 | US                |
|        5 | Carol Taylor |        36 | UK                |
+----------+--------------+-----------+-------------------+
5 rows in set (0.00 sec)
Following is the query for multiple LIKE operator usage in a single query −
mysql> select * from DemoTable1534
   -> where ClientName LIKE ('%Doe%' or ClientAge LIKE '%38%') or (ClientCountryName LIKE '%S');
This will produce the following output −
+----------+-------------+-----------+-------------------+
| ClientId | ClientName  | ClientAge | ClientCountryName |
+----------+-------------+-----------+-------------------+
|        1 | Chris Brown |        29 | AUS               |
|        3 | John Doe    |        43 | US                |
|        4 | Adam Smith  |        38 | US                |
+----------+-------------+-----------+-------------------+
3 rows in set, 5 warnings (0.00 sec)
Python Number acos() Method

Python number  method acos() returns the arc cosine of x, in radians.
Following is the syntax for acos() method −
acos(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error.
x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error.
This method returns arc cosine of x, in radians.
The following example shows the usage of acos() method.
#!/usr/bin/python
import math

print "acos(0.64) : ",  math.acos(0.64)
print "acos(0) : ",  math.acos(0)
print "acos(-1) : ",  math.acos(-1)
print "acos(1) : ",  math.acos(1)
When we run above program, it produces following result −
acos(0.64) :  0.876298061168
acos(0) :  1.57079632679
acos(-1) :  3.14159265359
acos(1) :  0.0
Python | Numpy np.assert_equal() method

23 Jan, 2020
With the help of np.assert_equal() method, we can get the assertion error when two objects are not equal by using np.assert_equal() method.
Syntax : np.assert_equal(actual, desired)Return : Return assertion error if two object are unequal.
Example #1 :In this example we can see that by using np.assert_equal() method, we are able to get the assertion error when two objects are not equal by using this method.
# import numpy and assert_equalimport numpy as npimport numpy.testing as npt  # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [1, 2])  print(gfg)
Output :
None
Example #2 :
# import numpy and assert_equalimport numpy as npimport numpy.testing as npt  # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [5, 2])  print(gfg)
Output :
AssertionError:Items are not equal:item=0
ACTUAL: 1DESIRED: 5
Python numpy-Testing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
HTML & CSS | Tabindex attribute & Navigation bars

04 Dec, 2018
The tabindex attribute specifies the tab order of an element. “tab” button is used for navigation. The tabindex content attribute allows users to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.Syntax :
element tabindex = "number" 
Attribute :
number: This specify the “tab” order when tab key is used to navigate.
Example :
<div tabindex = "0"><p>GFG Article 1</P></div><div tabindex = "1"><p>GFG Article 2</P></div><div tabindex = "2"><p>GFG Article 3</P></div>
In the above example, when tab button is used to navigating elements Article 1 will focused first followed by Article 2 and Article 3.
Note: If tabindex value is -1 then it will not be focusable. For example the below link will not be focused while using tab keys to traverse.Example :
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
Navigation bars :Navigation bars are important to any websites. They are the blocks associated with links to the different pages of the websites.
There are two types of navigation menu:
Vertical Nav bars
Horizontal Nav bars
Vertical Nav bars: Vertical bar menu displays one above another.Examples :Code :
<style>    ul {        list-style-type: none;        margin: 0;        padding: 0;        width: 20%;        background-color: white;        position: fixed;        height: 25%;        overflow: hidden;    }          li a {        display: block;        color: #000;        padding: 8px 16px;        text-decoration: none;    }          .hme {        background-color: #4CB96B;    }</style>  <body>    <ul>        <li><a class="hme" href="#" tabindex="2">Home</a></li>        <li><a href="#" tabindex="1">Blog</a></li>        <li><a class="hme" href="#" tabindex="4">About Us</a></li>        <li><a href="#a" tabindex="3">Contact Us</a></li>    </ul></body>
Horizontal Nav bars:Horizontal Nav bars menu displays one followed by other or side by side.Examples :Code :
<style>    ul {        list-style-type: none;        margin: 0;        padding: 0;        background-color: white;        height: 25%;        overflow: hidden;    }          li {        float: left;    }          li a {        display: block;        color: #000;        padding: 8px 16px;        text-decoration: none;    }          .hme {        background-color: #4CB96B    }</style>  <body>    <ul>        <li><a class="hme" href="#" tabindex="1">Home</a></li>        <li><a href="#" tabindex="2">Blog</a></li>        <li><a class="hme" href="#" tabindex="3">About Us</a></li>        <li><a href="#" tabindex="4">Contact Us</a></li>    </ul></body>
CSS-Advanced
HTML-Attributes
Web technologies
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program To Recursively Linearly Search An Element In An Array

25 Jan, 2022
Given an array arr[] of n elements, write a function to recursively search a given element x in arr[].
Illustration:
Input  : arr[] = {25, 60, 18, 3, 10}
Output : Element to be searched : 3


Input  : arr[] = {10,20,30,24,15,40}
Output : -1
For x = 35
Element x is not present in arr[]
Procedure:
The idea is to search the element from both the sides of array recursively. If the element that needs to searched matches with the leftmost element of the left boundary, or it matches with the rightmost element of the right boundary, directly return the position of the element, else recur for the remaining array to search for the element with the value same as x.
Example
Java
// Java Program to Search an element in an Array Recursively // Main classpublic class GFG {     // Method 1    // Recursive method to search for an element and    // its index in the array    static int recursiveSearch(int arr[], int l, int r,                               int x)    {         // if r<l,it means that element is not present in        // the array        if (r < l)            return -1;         if (arr[l] == x)            return l;         if (arr[r] == x)            return r;         // Since element has not found on both left most and        // rightmost boundary,ie at l and r, now recursive the        // array to find position of x.        return recursiveSearch(arr, l + 1, r - 1, x);    }     // Method 2    // Main driver method    public static void main(String[] args)    {        // Element to be searched for        // Custom input number        int x = 3;         // Declaring and initializing the integer array        int arr[] = new int[] { 25, 60, 18, 3, 10 };         // Calling the above recursive method method to        // search for the element in the array         // Recursive function is called over array to        // get the index of the element present in an array        int index            = recursiveSearch(arr, 0, arr.length - 1, x);         // If index is found means element exists        if (index != -1)             // Print the element and its index            System.out.println("Element " + x                               + " is present at index "                               + index);         // If we hit else case means        // element is not present in the array        else             // Simply display the corresponding element            // is not present            System.out.println("Element " + x                               + " is not present");    }}
  
Element 3 is present at index 3
 
surinderdawra388
sagartomar9927
java-basics
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Collections.nCopies() in Java

28 Feb, 2018
The role of Collections.nCopies() is to return an immutable list which contains n copies of given object. This function helps if we want to create a list with n copies of given object. The newly allocated data object is tiny i.e, it contains a single reference to the data object.
Syntax :
public static <T> List<T> nCopies(int number, T object)

where, number is the number of copies
of object and object represents the 
element which will appear number times
in the returned list. T represents generic type. 

Exception : The function throws IllegalArgumentException if value of number is less than 0.
Example :
Java
// Java code to show implementation// of Collections.nCopies()import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // creating a list where first argument        // represents the number of copies and        // the second argument represents the        // element to be copied for 'number' times        // This will create 4 copies of the objects.        List list = Collections.nCopies(4, "GeeksforGeeks");          // Displaying the list returned        System.out.println("The list returned is :");        Iterator itr = list.iterator();        while (itr.hasNext()) {            System.out.print(itr.next() + " ");        }        System.out.println("\n");          List list1 = Collections.nCopies(3, "GeeksQuiz");              // Displaying the list returned        System.out.println("The list returned is :");        Iterator itr1 = list1.iterator();          while (itr1.hasNext()) {            System.out.print(itr1.next() + " ");        }        System.out.print("\n");    }}
The list returned is :
GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks 

The list returned is :
GeeksQuiz GeeksQuiz GeeksQuiz  

Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python Program to Sort Words in Alphabetical Order

23 Aug, 2021
Given an input string, our task is to write a Python program to sort the words present in the string in alphabetical order.
Examples:
Input : “geeks for Geeks”
Output : “for geeks geeks”  
Input : “the Quick brown fox jumPs over the lazY Dog”
Output : “brown dog fox jumps lazy over quick the the”
sorted() is a predefined function in Python which returns the sorted list of any particular sequence.
Python3
# Python3 program to sort the words of a string in# alphabetical order# Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)):# convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S))# Driver codeS = “the Quick brown fox jumPs over the lazY Dog”# function callFunc(S)
# Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)):
# convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S))
# Driver codeS = “the Quick brown fox jumPs over the lazY Dog”
# function callFunc(S)
Output:
brown dog fox jumps lazy over quick the the
Python list sort() function can be used to sort a list in ascending, descending, or user-defined order. 
Python3
# Python3 program to sort the words of a# string in alphabetical order# Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort()# return the sorted wordsreturn ‘ ‘.join(W)# Driver codeS = “GeekS for geEks”print(F(S))
# Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort()
# return the sorted wordsreturn ‘ ‘.join(W)
# Driver codeS = “GeekS for geEks”print(F(S))
Output:
for geeks geeks
Picked
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Narcissistic number

A narcissistic number in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits.
For example −
153 = 1^3 + 5^3 + 3^3 = 1+125+27 = 153
Similarly,
1 = 1^1 = 1
We will first count the number of digits using a while loop. Then with another while loop, we pick
last digit of the number and add its (count) th power to a variable sum. After the loop we return a
boolean checking whether the sum is equal to the number or not.
The code for this approach will be −
const isNarcissistic = (num) => {
   let m = 1, count = 0;
   while(num / m > 1){
      m *= 10;
      count++;
   };
   let sum = 0, temp = num;
   while(temp){
      sum += Math.pow(temp % 10, count);
      temp = Math.floor(temp / 10);
   };
   return sum === num;
};
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));
The output in the console will be −
true
true
false
false
Java.util.Collections.frequency() in Java with Examples

07 Dec, 2018
java.util.Collections.frequency() method is present in java.util.Collections class. It is used to get the frequency of a element present in the specified list of Collection. More formally, it returns the number of elements e in the collection.
Syntax
public static int frequency(Collection<?> c, Object o)
Parameters : 
c - the collection in which to determine the frequency of o
o - the object whose frequency is to be determined
Returns :
Returns the number of elements in the specified collection 
equal to the specified object.
Throws:
NullPointerException - if c is null

// Java program to demonstrate working of // java.utils.Collections.frequency()  import java.util.*;   public class FrequencyDemo{    public static void main(String[] args)    {        // Let us create a list of strings        List<String>  mylist = new ArrayList<String>();        mylist.add("practice");        mylist.add("code");        mylist.add("code");        mylist.add("quiz");        mylist.add("geeksforgeeks");           // Here we are using frequency() method        // to get  frequency of element "code"        int freq = Collections.frequency(mylist, "code");           System.out.println(freq);    }}
Output:
2

How to Quickly get frequency of an element in an array in Java ?
Arrays class in Java doesn’t have frequency method. But we can use Collections.frequency() to get frequency of an element in an array also.
// Java program to get frequency of an element //  with java.utils.Collections.frequency()  import java.util.*;   public class FrequencyDemo{    public static void main(String[] args)    {        // Let us create an array of integers        Integer arr[] = {10, 20, 20, 30, 20, 40, 50};           // Please refer below post for details of asList()        // https://www.geeksforgeeks.org/array-class-in-java/        int freq = Collections.frequency(Arrays.asList(arr), 20);           System.out.println(freq);    }}
Output:
3

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java - util package
Java-Collections
Java-Collections-Class
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.hrtime( ) Method

29 Sep, 2021
The process.hrtime() method to measure code execution time which returns array which include current high-resolution real time in a [seconds, nanoseconds]. We measure the code execution time by providing the time returned by the first process.hrtime() call as a parameter in the second process.hrtime() call.
The Advantage of process.hrtime() is it measures time very accurate execution time which last less than a millisecond.
Syntax:
process.hrtime([time])
Parameter: This method accept a single parameter as mentioned above an described below.
time : The time is an optional parameter that must be the result of a previous process.hrtime() call to difference with the current time.
Return Type: It returns an array of 2 ints. The 1. int contains the seconds and the 2. int the nanoseconds. These times are relative to an arbitrary time in the past, and not related to the time of day.
Example 1:
Javascript
// Implement the function.. var hrTime = process.hrtime() // Time in millisecond...console.log("Time in millisecond is: ", hrTime[0] * 1000 + hrTime[1] / 1000000)
 Output: 
Time in millisecond is:  218394926745.5
 
Example 2:
 
Javascript
// Create a variable and call the process.hrtime() function.var start_time = process.hrtime();   // Print the Start time:console.log("Start Time:",start_time); // Make the add functionsetTimeout(function(){ // Create two variablevar a = '40',b = '50'; // Print the Addition result:console.log("Add of two number is :",(a - 0) + (b - 0));       // Create a variable and call the second process.hrtime()    // function and pass the start time as parameter.    var end_time = process.hrtime(start_time);    // Print the Execution time.    console.log("End Time:",end_time);     }, 1000);
Output: It means 1 second and 8779100 nanoseconds from start to end time is taken.
Start Time: [ 682340, 452477300 ]
Add of two number is : 90
End Time: [ 1, 8779100 ]
Example 3:
Javascript
// Create a variable and call the process.hrtime() function.var start_time = process.hrtime();   // Print the Start time:console.log("Start Time:",start_time); // Make the add functionsetTimeout(function(){     console.log("Execution time will be calculated"+                " for printing this message....");     // Create a variable and call the second process.hrtime()    // function and pass the start time as.    var end_time = process.hrtime(start_time);    // Print the Execution time.    console.log("End Time:",end_time);     }, 1000);
  
Output: It means 1 second and 10987200 nanoseconds from start to end time is taken.
 
Start Time: [ 682865, 516565300 ]
Execution time will be calculated for printing this message....
End Time: [ 1, 10987200 ]
 
Reference Taken : https://nodejs.org/api/process.html#process_process_hrtime_time
 
sagartomar9927
kerbaton
Node.js-Methods
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO CS 2014 - GeeksforGeeks

27 Sep, 2021
while (m < n)
   if (x > y ) and (a < b) then
      a=a+1
      y=y-1
   end if
   m=m+1 
end while 
= (number of edges) - (number of nodes) + 1 = 8-6+2 = 4
= Total number of regions = 4
= Total number of decision points + 1 = 3+1 = 4 
S → SS
S → (S)
S → ε

1) S → (S)
2) S → (SS)
3) S → ((S)S)
4) S → ((SS)S)
5) S → (((S)S))S)
6) S → (((S)(S))S)
7) S → (((S)(S))(S))  [S → ε]  
8) S → ((()(S))S)     [S → ε]
9) S → ((()())S)      [S → ε]  
10) S → ((()()))

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
ABS() Function in SQL Server

29 Dec, 2020
ABS() function :
This function in SQL Server is used to return the absolute value of a specified number. Absolute value is used for depicting the distance of a number on the number line from 0. The direction of the number from zero is not considered since the absolute value of a number is never negative. This function takes as an argument any numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type. The value returned by this function is of the same data type as the numeric data type of the argument.
Features :
This function is used to find the absolute value of a specified number.
This function accepts a single parameter.
The accepted parameter is of numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type.
The returned value will be in the same data type as the numeric data type of the specified parameter.
Syntax :
SELECT ABS(number);
Parameter :
This method accepts a parameter as given below:
number: Specified numeric value whose absolute value going to be returned.
Returns :
It returns the absolute value of a specified number.
Example-1 :
Getting the absolute value 0 of a specified number 0.
SELECT ABS(0);
Output :
0
Example-2 :
Getting the absolute value .7 of a specified number -0.7
SELECT ABS(-0.7);
Output :
.7
Example-3 :
Using ABS() function with a variable and getting the absolute value 123 of a specified number 123.
DECLARE @Parameter_Value INT;
SET @Parameter_Value = 123;
SELECT ABS(@Parameter_Value);
Output :
123
Example-4 :
Using ABS() function with a variable and getting the absolute value 34.87 of a specified float value “-34.87”.
DECLARE @Parameter_Value float;
SET @Parameter_Value = -34.87;
SELECT ABS(@Parameter_Value);
Output :
34.869999999999997
Application :
This function is used to return the absolute value of a specified numeric value.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Assign values to Values List

02 Sep, 2020
Given 2 dictionaries, assign values to value list elements mapping from dictionary 2.
Input : test_dict = {‘Gfg’ : [3, 6], ‘best’ :[9]}, look_dict = {3 : [1, 5], 6 : “Best”, 9 : 12}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}, ‘best’: {9: 12}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on.
Input : test_dict = {‘Gfg’ : [3, 6]}, look_dict = {3 : [1, 5], 6 : “Best”}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on.
Method #1 : Using nested dictionary comprehension
In this, we use inner dictionary comprehension to map values elements to dict 2, and outer dict is used to extract all keys from dictionary 1.
Python3
# Python3 code to demonstrate working of # Assign values to Values List# Using nested dictionary comprehension  # initializing dictionarytest_dict = {'Gfg' : [3, 6],             'is' : [4, 2],              'best' :[9]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing lookup dict look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"}  # nested dictionaries to sought solutionres = {idx: {ikey: look_dict[ikey] for ikey in test_dict[idx]} for idx in test_dict}  # printing result print("The mapped dictionary : " + str(res)) 
The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}

Method #2 : Using items() + dictionary comprehension
Similar to above method, another one-liner, difference being that items() is used for element access.
Python3
# Python3 code to demonstrate working of# Assign values to Values List# Using items() + dictionary comprehension  # initializing dictionarytest_dict = {'Gfg': [3, 6],             'is': [4, 2],             'best': [9]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing lookup dictlook_dict = {3: [1, 5], 6: "Best", 4: 10, 9: 12, 2: "CS"}  # nested dictionaries to sought solution# items() used to access key-val pairsres = {key: {ikey: ival for (ikey, ival) in look_dict.items() if ikey in val} for (key, val) in test_dict.items()}  # printing resultprint("The mapped dictionary : " + str(res))
The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Create a Bar chart using Recharts in ReactJS

27 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).  
To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts';    const App = () => {  // Sample dataconst data = [  {name: 'Geeksforgeeks', students: 400},  {name: 'Technical scripter', students: 700},  {name: 'Geek-i-knack', students: 200},  {name: 'Geek-o-mania', students: 1000}];    return (<BarChart width={600} height={600} data={data}>    <Bar dataKey="students" fill="green" />    <CartesianGrid stroke="#ccc" />    <XAxis dataKey="name" />    <YAxis />  </BarChart>);}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
React-Questions
Recharts
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plot line graph from NumPy array

17 Dec, 2021
For plotting graphs in Python, we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot(), which is used to plot two-dimensional data.
Different functions used are explained below:
np.arange(start, end): This function returns equally spaced values from the interval [start, end).
plt.title(): It is used to give a title to the graph. Title is passed as the parameter to this function.
plt.xlabel(): It sets the label name at X-axis. Name of X-axis is passed as argument to this function.
plt.ylabel(): It sets the label name at Y-axis. Name of Y-axis is passed as argument to this function.
plt.plot(): It plots the values of parameters passed to it together.
plt.show(): It shows all the graph to the console.
Example 1 :
Python3
# importing the modulesimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = x * x # plottingplt.title("Line graph")plt.xlabel("X axis")plt.ylabel("Y axis")plt.plot(x, y, color ="red")plt.show()
 Output : 
Example 2 :
Python3
# importing the libraryimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = np.array([100, 10, 300, 20, 500, 60, 700, 80, 900, 100]) # plottingplt.title("Line graph")plt.xlabel("X axis")plt.ylabel("Y axis")plt.plot(x, y, color ="green")plt.show()
 Output : 
 
simmytarika5
saurabh1990aror
thordask
Python-matplotlib
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Runtime Polymorphism with multilevel inheritance

Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
We can override a method at any level of multilevel inheritance. See the example below to understand the concept −
 Live Demo
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
class Puppy extends Dog {
   public void move() {
      System.out.println("Puppy can move.");
   }
}
public class Tester {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Puppy(); // Animal reference but Puppy object
      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Puppy class
   }
}
Animals can move
Puppy can move.
Python Program to Select the nth Smallest Element from a List in Expected Linear Time

When it is required to select the nth smallest element from a list in linear time complexity, two methods are required. One method to find the smallest element, and another method that divides the list into two parts. This division depends on the ‘i’ value that is given by user. Based on this value, the list is split, and the smallest element is determined.
Below is a demonstration of the same −
 Live Demo
def select_smallest(my_list, beg, end, i):
   if end - beg <= 1:
      return my_list[beg]
   pivot_val = start_partition(my_list, beg, end)

   k = pivot_val - beg + 1

   if i < k:
      return select_smallest(my_list, beg, pivot_val, i)
   elif i > k:
      return select_smallest(my_list, pivot_val + 1, end, i - k)

   return my_list[pivot_val]

def start_partition(my_list, beg, end):
   pivot_val = my_list[beg]
   i = beg + 1
   j = end - 1

   while True:
      while (i <= j and my_list[i] <= pivot_val):
         i = i + 1
      while (i <= j and my_list[j] >= pivot_val):
         j = j - 1

   if i <= j:
      my_list[i], my_list[j] = my_list[j], my_list[i]
   else:
      my_list[beg], my_list[j] = my_list[j], my_list[beg]
      return j

my_list = input('Enter the list of numbers.. ')
my_list = my_list.split()
my_list = [int(x) for x in my_list]
i = int(input('Enter the value for i.. '))

ith_smallest = select_smallest(my_list, 0, len(my_list), i)
print('The result is {}.'.format(ith_smallest))
Enter the list of numbers.. 43 12 67 89 99 0
Enter the value for i.. 3
The result is 43.
A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter.
A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter.
Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’.
Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’.
This method is called in the ‘select_smallest’ method.
This method is called in the ‘select_smallest’ method.
The ‘select_smallest’ is also called again inside the same function- this is how recursion works.
The ‘select_smallest’ is also called again inside the same function- this is how recursion works.
The numbers are taken as input from the user.
The numbers are taken as input from the user.
It is split based on default value.
It is split based on default value.
It is iterated over.
It is iterated over.
A value for ‘i’ is taken from the user.
A value for ‘i’ is taken from the user.
Based on this ‘i’ value, the list is divided into two parts.
Based on this ‘i’ value, the list is divided into two parts.
The ‘select_smallest’ method is called on one of the lists.
The ‘select_smallest’ method is called on one of the lists.
The output is displayed on the console.
The output is displayed on the console.
Python os.pipe() Method

Python method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively
Following is the syntax for pipe() method −
os.pipe()

NA
NA
This method returns a pair of file descriptors.
The following example shows the usage of pipe() method.
#!/usr/bin/python

import os, sys

print "The child will write text to a pipe and "
print "the parent will read the text written by child..."

# file descriptors r, w for reading and writing
r, w = os.pipe() 

processid = os.fork()
if processid:
   # This is the parent process 
   # Closes file descriptor w
   os.close(w)
   r = os.fdopen(r)
   print "Parent reading"
   str = r.read()
   print "text =", str   
   sys.exit(0)
else:
   # This is the child process
   os.close(r)
   w = os.fdopen(w, 'w')
   print "Child writing"
   w.write("Text written by child...")
   w.close()
   print "Child closing"
   sys.exit(0)
When we run above program, it produces following result −
The child will write text to a pipe and
the parent will read the text written by child...
Parent reading
Child writing
Child closing
text = Text written by child...


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Difference between Traditional and Reactive Computer System - GeeksforGeeks

04 May, 2020
1. Traditional Computer System :Traditional Computer System takes the input from the user and computes the output as the function of the input. It basically computes function on the input.
Output data = f(input data) 
Example:If x is input and f is some function, y(output) = f(x)
2. Reactive Computer System :Reactive Computer System takes the input from the user but does not produce the output as a function of input but it interacts with the environment. In this interaction, the results computed are used to perform some action on environment.
Example:Real-time Systems
Difference between Traditional and Reactive System :
Difference Between
Operating Systems
Operating Systems
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1