code-rag-bench/online-tutorials huggingface dataset:
PyQt5 – How to add action to a button ?

22 Apr, 2020
In this article we will see how to set action to a push button. QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used.
When the button is pressed it should perform some action, in order to add action to a button we will use clicked.connect method.
Syntax : button.clicked.connect(function)
Argument : It takes function as a argument.
Action performed: When button will be clicked it will call the passes function.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 30)          # adding action to a button        button.clicked.connect(self.clickme)      # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :When we tap on the button.
pressed
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
Python | os.path.join() method
Elias Gamma Decoding in Python

28 Nov, 2021
The Elias gamma code is a universal code that is used to encode a sequence of positive integers. It is developed by Peter Elias. It is most useful when the upper-bound of integers cannot be determined beforehand.
Formula:
Elias Gamma Coding=Unary(1+floor(log2(x)))+Binary representation of ‘x’ without MSB
Example: Let’s consider an example where we want to decode 0001001,
Apply Step 1:
Count the number of '0's from MSB until you reach the first '1' and store the count in K.
In our example(0001001) K=3 

Apply Step 2:
Read 3 more bits including the first '1'=1001

Apply Step 3:
Convert the final binary into integer which gives us the original number.
Decimal(1001)=9
Step 1: Count the number of ‘0’s from MSB until you reach the first ‘1’ and store the count in K.
Python3
# define the functiondef Elias_Gamma_Decoding(x):        # convert to list    x = list(x)          # initialize k to 0    K = 0    while True:                # check if k is not 0 in through        # list index        if not x[K] == '0':            break                  # increment k value        K = K + 1
Step 2: Consider that ‘1’ as the first digit and read ‘K’ more bits from the current ‘1’
Python3
x = x[K:2*K+1]  # Reading K more bits from '1'
Step 3: Convert the final binary into an integer which gives us the original number.
Python3
# Converting binary to integerfor i in range(len(x)):    if x[i] == '1':        n = n+math.pow(2, i)return int(n)
Below is the complete implementation of the above approach.
Python3
# import the math moduleimport math  # functiondef Elias_Gamma_Decoding(x):    x = list(x)    K = 0    while True:        if not x[K] == '0':            break        K = K + 1          # Reading K more bits from '1'    x = x[K:2*K+1]      n = 0    x.reverse()          # Converting binary to integer    for i in range(len(x)):        if x[i] == '1':            n = n+math.pow(2, i)    return int(n)    # value inputx = '0001001'  # call the functionprint(Elias_Gamma_Decoding(x))
Output:
9
Picked
python-utility
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
Java Program to Open Input URL in System Default Browser in Windows

19 Jan, 2021
URL is the URL you want to display in the default Web browser. For example, wire http://www.site.com/report.html to this input to display the HTML file report.html on the Web Server www.site.com in the browser.
Our problem is to write a java program to open Input URL in System Default Browser in Windows.
To open any URL we use different predefine files of java to operate with our Desktop.
java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc.java.net.URI: java.net.URI is used to Represent User Resource Identifier reference.
java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc.
java.net.URI: java.net.URI is used to Represent User Resource Identifier reference.
Algorithm:
Firstly, we create an Object of our-defined class that we import by java.awt.Desktop.
During the creation of an object, we use getDesktop() method that returns the Desktop instance of the current desktop context. On some platforms the Desktop API may not be supported, in that case we use isDesktopSupported() method to determine if the current desktop is supported.
  Desktop desk=Desktop.getDesktop();
Then we use browse() method where we enter our URL that we want to open on our desktop by new URI().
  desk.browse(new URI("http://xyz.com"));
Java
// Java Program to Open Input URL in // System Default Browser in Windows  import java.awt.Desktop;import java.io.*;import java.net.URI;  class GFG {    public static void main(String[] args)             throws Exception    {        Desktop desk = Desktop.getDesktop();                // now we enter our URL that we want to open in our        // default browser        desk.browse(new URI("http://xyz.com"));    }}
Output
(Our URL "http://xyz.com" will open in our desktop default browser)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.path.exists() method

21 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in python used for common path name manipulation.
os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not.
Syntax: os.path.exists(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False.
# Python program to explain os.path.exists() method     # importing os module import os  # Specify pathpath = '/usr/local/bin/'  # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist)    # Specify pathpath = '/home/User/Desktop/file.txt'  # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist)
True
False

Note: os.path.exists() function may return False, if permission is not granted to execute os.stat() on the requested file, even if the path exists.
Reference: https://docs.python.org/3/library/os.path.html
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to limit character input in textarea including count in jQuery ?

18 Jan, 2021
In this article, we will set the limit character input in the textarea including count in the jQuery. To set the limit character in the input textarea, we use length property.
Approach:
We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to reduce the textarea character limit by 1 when we click the button and display the count on the screen.
Syntax:
var max_length = 25;
$('textarea').keyup(function () {
    var len = max_length - $(this).val().length;
    $('.GFG').text(len);
});
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        How to limit character input        in the textarea including        count in jQuery?    </title>      <!-- Import jQuery cdn library -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>      <script>        $(document).ready(function () {            var max_length = 25;            $('textarea').keyup(function () {                var len = max_length - $(this).val().length;                $('.GFG').text(len);            });          });    </script></head>  <body style="text-align: center;">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h3>        How to limit character input        in the textarea <br>including        count in jQuery?    </h3>      <form>          <p>Maximum input characters: 25</p>            <textarea maxlength="25"></textarea>            <p>            <span class="GFG">25</span>             Characters Remaining        </p>      </form></body>  </html>
Output:
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
Creating a view of parent array in Julia - view(), @view and @views Methods - GeeksforGeeks

21 Apr, 2020
The view() is an inbuilt function in julia which is used to return a view into the given parent array A with the given indices instead of making a copy.
Syntax: view(A, inds...)
Parameters:
A: Specified parent array.
inds: Specified indices.
Returns: It returns a view into the given parent array A with the given indices instead of making a copy.
Example:
# Julia program to illustrate # the use of view() method   # Getting a view into the given parent# array A with the given indices # instead of making a copy.A = [5, 10, 15, 20];println(view(A, 2))  B = [5 10; 15 20];println(view(B, :, 1))  C = cat([1 2; 3 4], [5 6; 7 8], dims = 3);println(view(C, :, :, 1))
Output:
The @view() is an inbuilt function in julia which is used to create a sub array from the given indexing expression.
Syntax:@view A[inds...]
Parameters:
A: Specified parent array.
inds: Specified indices.
Returns: It returns the created sub array from the given indexing expression.
Example:
# Julia program to illustrate # the use of @view() method   # Getting the created sub array # from the given indexing expression.A = [5, 10, 15, 20];println(@view A[3])  B = [5 10; 15 20];println(@view B[:, 1])  C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3);println(@view(C[:, :, 2]))
Output:
The @views() is an inbuilt function in julia which is used to convert every given array-slicing operation in the given expression.
Syntax:@views expression
Parameters:
expression: Specified expression.
Returns: It returns the desired view.
Example:
# Julia program to illustrate # the use of @views() method   # Getting the created sub array # from the given indexing expression.A = zeros(4, 4);@views for row in 2:4    b = A[row, :]    b[:] .= rowendprintln(A)
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get number of elements of array in Julia - length() Method
Find maximum element along with its index in Julia - findmax() Method
Getting the maximum value from a list in Julia - max() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia
Python 3 - String rjust() Method

The rjust() method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Following is the syntax for rjust() method −
str.rjust(width[, fillchar])

width − This is the string length in total after padding.
width − This is the string length in total after padding.
fillchar − This is the filler character, default is a space.
fillchar − This is the filler character, default is a space.
This method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
The following example shows the usage of rjust() method.
#!/usr/bin/python3

str = "this is string example....wow!!!"
print (str.rjust(50, '*'))
When we run above program, it produces the following result −
******************this is string example....wow!!!


    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
URL getRef() method in Java with Examples - GeeksforGeeks

31 Dec, 2018
The getRef() function is a part of URL class. The function getRef() returns the Reference or anchor part of a specified URL.
Function Signature:
public String getRef()
Syntax:
url.getRef()
Parameter: This function does not require any parameter
Return Type: The function returns String Type
Below programs illustrates the use of getRef() function:
Example 1: Given a URL we will get the Reference or anchor using the getRef() function.
// Java program to show the// use of the function getRef()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {              // create a URL            url= new URL("https:// www.geeksforgeeks.org#Arnab_Kundu");              // get the  Reference or anchor            String _Ref=url.getRef();                           // display the URL            System.out.println("URL = "+url);                           // display the  Reference or anchor            System.out.println(" Reference or anchor="+_Ref);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org#Arnab_Kundu
 Reference or anchor=Arnab_Kundu

Example 2: Now we will not provide any anchor and use the function to get the Reference or anchor and see the results.
// Java program to show the// use of the function getRef()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {              // create a URL            url = new URL("https:// www.geeksforgeeks.org");              // get the  Reference or anchor            String _Ref = url.getRef();              // display the URL            System.out.println("URL = " + url);              // display the  Reference or anchor            System.out.println(" Reference or anchor= "                               + _Ref);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org
 Reference or anchor= null

Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
PriorityQueue in Java
How to iterate any Map in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java
Topological sorting using Javascript DFS

A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex u to vertex v, u comes before v in the ordering. This only makes sense in directed graphs.
There are many places where topological sort makes a lot of sense. For example, let's say you're following a recipe, in this, there are some steps that are must for going to the next steps. But some of these can be performed in parallel. In a similar fashion, during college when selecting courses, there are some prerequisites for more advanced courses which themselves may be prerequisites for further courses. For example −
 /**
   *       CS101  CS102
   *       /       \ /
   *      CS204    CS340
   *       \      /| \
   *       CS380   | CS410
   *          \    | /
   *           CS540
*/
In the above graph, consider if you want to take the course on one level, You'll have to first take all courses it is connected to with from the level above it. Following are some possible topological sorts for the above graph −
CS101 -> CS204 -> CS102 -> CS340 -> CS410 -> CS380 -> CS540
CS102 -> CS101 -> CS340 -> CS204 -> CS410 -> CS380 -> CS540
Let us implement this in JavaScript. We'll write 2 functions, topological sort, and topologicalSortHelper to help recursively mark and explore the graph. 
topologicalSortHelper(node, explored, s) {
   explored.add(node);
   // Marks this node as visited and goes on to the nodes
   // that are dependent on this node, the edge is node ----> n
   this.edges[node].forEach(n => {
      if (!explored.has(n)) {
         this.topologicalSortHelper(n, explored, s);
      }
   });
   // All dependencies are resolved for this node, we can now add
   // This to the stack.
   s.push(node);
}

topologicalSort() {
   // Create a Stack to keep track of all elements in sorted order
   let s = new Stack(this.nodes.length);
   let explored = new Set();

   // For every unvisited node in our graph, call the helper.
   this.nodes.forEach(node => {
      if (!explored.has(node)) {
         this.topologicalSortHelper(node, explored, s);
      }
   });

   while (!s.isEmpty()) {
      console.log(s.pop());
   }
}
You can test this using − 
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addDirectedEdge("A", "C");
g.addDirectedEdge("A", "B");
g.addDirectedEdge("A", "D");
g.addDirectedEdge("C", "D");
g.addDirectedEdge("D", "E");
g.addDirectedEdge("E", "F");
g.addDirectedEdge("B", "G");

g.topologicalSort();
The graph we created looks like − 
/**
   *         A
   *       / | \
   *       C | B
   *       \ | |
   *         D G
   *         |
   *         E
   *         |
   *         F
*/
This will give the output −
A
B
G
C
D
E
F
SQLite - CREATE Table

SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column's data type.
Following is the basic syntax of CREATE TABLE statement.
CREATE TABLE database_name.table_name(
   column1 datatype PRIMARY KEY(one or more columns),
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype
);

CREATE TABLE is the keyword telling the database system to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Optionally, you can specify  database_name along with table_name.
Following is an example which creates a COMPANY table with ID as the primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table.
sqlite> CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);
Let us create one more table, which we will use in our exercises in subsequent chapters.
sqlite> CREATE TABLE DEPARTMENT(
   ID INT PRIMARY KEY      NOT NULL,
   DEPT           CHAR(50) NOT NULL,
   EMP_ID         INT      NOT NULL
);
You can verify if your table has been created successfully using SQLite command .tables command, which will be used to list down all the tables in an attached database.
sqlite>.tables
COMPANY     DEPARTMENT
Here, you can see the COMPANY table twice because its showing COMPANY table for main database and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete information about a table using the following SQLite .schema command.
sqlite>.schema COMPANY
CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2000 | Question 35 - GeeksforGeeks

19 Nov, 2018
The following arrangement of master-slave flip flops has the initial state of P, Q as 0, 1 (respectively). After three clock cycles the output state P, Q is (re­spectively),
(A) 1, 0(B) 1, 1(C) 0, 0(D) 0,1Answer: (A)Explanation: Given P = 0 ,  J = 1 and k = 1
JK flipflop toggles the input in ‘11’ state. Therefore, output of first flipflop at P is ‘1’.
Initial value of P is input for D flipflop. So, D = 0 .Therefore, output of second flipflop at Q is ‘0’.Thus, option (A) is the answer.Please comment below if you find anything wrong in the above post.
Thus, option (A) is the answer.
Please comment below if you find anything wrong in the above post.
Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
How can a simple bivariate distribution be shown using ‘imshow’ in Matplotlib Python?

Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations.
It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on.
It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.
Python can be installed on Windows using the below command −
pip install matplotlib
The dependencies of Matplotlib are −
Python ( greater than or equal to version 3.4)
NumPy
Setuptools
Pyparsing
Libpng
Pytz
Free type
Six
Cycler
Dateutil
Bivariate distribution is the probability that a certain event would occur when two independent random variables are present.
The ‘imshow’ function is generally used to display images as well as plots in Matplotlib.
Let us understand how Matplotlib can be used to plot a bivariate distribution −
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
np.random.seed(9654241)

delta = 0.025
x = y = np.arange(−4.5, 4.5, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(−X**2 − Y**2)
Z2 = np.exp(−(X − 1)**2 − (Y − 1)**2)
Z = (Z1 − Z2) * 2

fig, ax = plt.subplots()
plt.title('A bivariate distribution')
plt.xlabel('x−axis')
plt.ylabel('y−axis')

im = ax.imshow(Z, interpolation='bilinear',
origin='lower', extent=[−3, 3, −3, 3],
vmax=abs(Z).max(), vmin=−abs(Z).max())
plt.show()
The required packages are imported and its alias is defined for ease of use.
The required packages are imported and its alias is defined for ease of use.
The data is created using the ‘random’ library’s ‘seed’ function.
The data is created using the ‘random’ library’s ‘seed’ function.
The data is created using the ‘Numpy’ library for two different data sets.
The data is created using the ‘Numpy’ library for two different data sets.
An empty figure is created using the ‘figure’ function.
An empty figure is created using the ‘figure’ function.
The ‘subplot’ function is used to create 2 separate plots within the same plot.
The ‘subplot’ function is used to create 2 separate plots within the same plot.
The data is plotted using the ‘plot’ function.
The data is plotted using the ‘plot’ function.
The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.
The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.
The figure is assigned to a variable using ‘imshow’ function.
The figure is assigned to a variable using ‘imshow’ function.
It is shown on the console using the ‘show’ function.
It is shown on the console using the ‘show’ function.
Scala String compareTo() method with example - GeeksforGeeks

03 Oct, 2019
The compareTo() method is utilized to compare a string with another string.Some points to remember:
Here, If a string(S1) is same as string(S2) in comparison then this method returns zero.
If S1 is less than S2 then a negative number is returned which is the difference of character value.
If S1 is greater than S2 then a positive number is returned.
Method Definition: int compareTo(String another String)Return Type: It returns an integer.
Example #1:
// Scala program of compareTo()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1 = "Nidhi"                  // Applying compareTo() method        val result = m1.compareTo("Nidhi")                  // Displays output        println(result)          }} 
0

It returns zero as both the strings are same.Example #2:
// Scala program of compareTo()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1 = "Nidhi"                  // Applying compareTo() method        val result = m1.compareTo("Nidh")                  // Displays output        println(result)          }} 
1

It returns a positive number as S1 is greater than S2 here.Example #3:
// Scala program of compareTo()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1 = "Nidhi"                  // Applying compareTo() method        val result = m1.compareTo("nidh")                  // Displays output        println(result)          }} 
-32

It returns a negative number as S1 is less than S2 here.
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Inheritance in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
How to change radio button state programmatically in jQuery ? - GeeksforGeeks

25 Jul, 2021
In this article, we will change the selected option of the radio button using jQuery. To select the value of the radio button we can set the “checked” to set to the desired option. For setting the property, we can use the prop() method in jQuery.
Syntax:
$(selector).prop("checked", true); 
Note: Selector, is the desired radio option element to be selected.
Example: Let us create a radio button group to select a favorite cricket player. We have created a radio option. By default, “Sachin” will be selected. When we click the button, the “Dhoni” option will be selected as given in the program.
HTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8" />    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">    </script>  </head>  <body>    <fieldset>      <legend>Who is Your Favorite Cricketer?</legend>      <input type="radio"              name="favorite"              value="Dhoni" />Dhoni<br />      <input type="radio"              name="favorite"              value="Shewag" />Shewag<br />      <input type="radio"              name="favorite" checked              value="Sachin" />Sachin<br />      <br />      <button id="selectID">Select option</button>    </fieldset>      <script>      $("#selectID").on("click", function () {        selectRadio();      });      function selectRadio() {        let radioOption = jQuery("input:radio[value=Dhoni]");          // This will select the radio button        radioOption.prop("checked", true);      }    </script>  </body></html>
Output:
change radio state
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
jQuery-Questions
jQuery-Selectors
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
Node.js Stream readable.resume() Method - GeeksforGeeks

12 Oct, 2021
The readable.resume() method in a Readable Stream is used to paused data that can be resumed again and data starts flowing again.
Syntax:
readable.resume()
Parameters: This method doesn’t accept any parameters.
Return Value: If this method is used then the data that was paused, starts flowing again.
Below examples illustrate the use of readable.resume() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // readable.resume() method    // Including fs moduleconst fs = require('fs');  // Constructing readable streamconst readable = fs.createReadStream("input.text");readable.on('data', (chunk) => {  console.log(`${chunk}`);});  // Calling pause methodreadable.pause();  // Calling resume methodreadable.resume();  console.log("Data starts flowing again!!");
Output:
Data starts flowing again!!
Hello!!!

Example 2:
// Node.js program to demonstrate the     // readable.resume() method    // Include fs moduleconst fs = require('fs');  // Create readable streamconst readable = fs.createReadStream("input.text");  // Handling data eventreadable.on('data', (chunk) => {  console.log(`${chunk}`);    // Calling pause method  readable.pause();    // After this any data will be displayed   // after 3 sec.  console.log('No additional data will be '             + 'displayed for 3 seconds.');    // Using setTimeout function  setTimeout(() => {    console.log('Now data starts flowing again.');      // Calling resume method    readable.resume();  }, 3000);});  // Displays that program // is endedconsole.log("Program ends!!");
Output:
Program ends!!
Hello!!!
No additional data will be displayed for 3 seconds.
Now data starts flowing again.

However, you can see while running, that after the execution of pause() method, no further data will be displayed for 3 seconds.
Reference: https://nodejs.org/api/stream.html#stream_readable_resume
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Integrating Facebook Like & Share Plugin Using Django - GeeksforGeeks

16 Feb, 2021
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc.  In this article we will learn to integrate facebook comment plugin in django.
How to Integrate Facebook Like & Share Plugin in Django ?
Installation
pip install django
1) Create new project
django-admin startproject Test_prj
2) Navigate to Test_prj directory
cd Test_prj
3) Create new app
python manage.py startapp main
Folder Structure :
Then add the app name inside the  INSTALLED_APPS (settings.py).
views.py
Python3
from django.shortcuts import render  # Create your views here.def home(request):    return render(request,"main/index.html")
Create new file urls.py inside the main directory
Python3
from django.urls import pathfrom .views import *  urlpatterns = [    path('',home,name="home")]
Add the main/urls.py inside the urls.py
Python3
from django.contrib import adminfrom django.urls import path,include  urlpatterns = [    path('admin/', admin.site.urls),    path('',include("main.urls")),]
https://developers.facebook.com/docs/plugins/like-button/
Go to this link to get code
Click on get code
Create new directory  templates inside the main app inside that create main directory
index.html
HTML
<!DOCTYPE html><html><head>    <title>GFG</title>    <div id="fb-root"></div>    <script async defer crossorigin="anonymous"             src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0"             nonce="8E6OZDVx"></script></head><body>    <h1>Welcome To GFG</h1>    <div class="fb-like" data-href="http://127.0.0.1:8000/8000" data-width=""         data-layout="button_count" data-action="like" data-size="large"          data-share="true"></div></body></html>
Open cmd or terminal to run this app
python manage.py runserver
OUTPUT :-
Python Django
Python Framework
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create a Junit report in Cypress?

We can create a Junit report in Cypress. To install the package for the JUnit report, run the command −
   npm install cypress-junit-reporter --save-dev
Implementation in cypress.json
{
   "reporter": "junit",
   "reporterOptions": {
      "mochaFile": "cypress/results/results.xml",
      "toConsole": true
   }
}
If we run multiple tests in a run and wish to have a unique report for individual spec files, we have to add [hash] in the mochaFile parameter in cypress.json.
Implementation in cypress.json to avoid overriding report
{
   "reporter": "junit",
   "reporterOptions": {
      "mochaFile": "cypress/results/results-[hash].xml",
      "toConsole": true
   }
}
To generate a report for all specs in the integration folder of the Cypress project, run the command −
   npx cypress run --reporter junit
After execution is completed, the results folder gets generated within the Cypress project containing reports in xml format.
Java atan() method with Examples

08 Apr, 2018
The java.lang.Math.atan() returns the arc tangent of an angle in between -pi/2 through pi/2. If the argument is NaN, then the result is NaN.
Note:If the argument is zero, then the result is a zero with the same sign as the argument.
Syntax :
public static double atan(double a)
Parameter :
a : the value whose arc tangent is to be returned.
Return :
This method returns the arc tangent of the argument.
Example :To show working of java.lang.Math.atan() method.
// Java program to demonstrate working// of java.lang.Math.atan() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = Math.PI;          System.out.println(Math.atan(a));          double c = 344.0;        double d = 0.0;        double e = -0.0;        double f = 1.5;          System.out.println(Math.atan(c));          // Input positive zero        // Output positive zero        System.out.println(Math.atan(d));          // Input negative zero        // Output negative zero        System.out.println(Math.atan(e));          System.out.println(Math.atan(f));    }}
Output:
1.2626272556789115
1.5678893582391513
0.0
-0.0
0.982793723247329

Java-Library
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
MongoDB NOT operator ( $not )

22 Apr, 2020
MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don’t contain the field. You can use this operator in methods like find(), update(), etc. according to your requirements.
Always use the $not operator with other operators because it cannot check the fields and documents independently and only affects other operators.
You can use the $not operator with regular expressions.
This operation of this operator is consistent with the behavior of other operators, but it may give some unexpected results with some data types like arrays.
Syntax:
{ field: { $not: { operator-expression } } }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000.
db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()
In this example, we are retrieving only those employee’s documents whose age is not equal to 24.
db.contributor.find({"personal.age": {$not: {$eq: 24}}}).pretty()
In this example, we are retrieving only those employee’s documents that does not match the given array.
db.contributor.find({language: {$not: {$in: ["Java", "Perl"]}}}).pretty()
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Mounting a Volume Inside Docker Container
Fuzzy Logic | Introduction
Python program to Reverse a range in list - GeeksforGeeks

07 Apr, 2021
Given a List, our task is to write a Python program to reverse a range in the list.
Example:
Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 3, 9
Output : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]
Explanation : 8, 9, 2, 10, 12, 7 are reversed in list to 7, 12, 10, 2, 9, 8.
Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 8, 9
Output : [6, 3, 1, 8, 9, 2, 10, 7, 12, 4, 11]
Explanation : 12, 7 are reversed in list to 7, 12.
Method #1 : Using reverse() + loop
In this example, sublist is extracted and reversed using reverse(). The loop is used next to replace range elements with reversed elements. 
Python3
# Python3 code to demonstrate working of# Reversing a range# Using reverse() + loop  # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]               # printing original listprint("The original list is : " + str(test_list))  # initializing range strt, end = 3, 9  # reversing list and assigning the rangetemp = test_list[strt:end]temp.reverse()for idx in range(strt, end):    test_list[idx] = temp[idx - strt]          # printing resultprint("Range reversed range list : " + str(test_list))
Output:
The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]
Method #2 : Using list split() + slicing
The compact approach to solve this problem is to perform a reversal of range list using list split way of reversing slicing only the required range. 
Python3
# Python3 code to demonstrate working of# Reversing a range# Using list split + slicing  # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]               # printing original listprint("The original list is : " + str(test_list))  # initializing range strt, end = 3, 9  # Third arg. of split with -1 performs reverse test_list[strt:end] = test_list[strt:end][::-1]  # printing resultprint("Range reversed range list : " + str(test_list))
Output:
The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How do we display a text area in HTML?

Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows.
The following are the attributes −
You can try to run the following code to display a text area in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML textarea Tag</title>
   </head>
   <body>
      <form action = "/cgi-bin/hello_get.cgi" method = "get">
         Enter subjects
         <br />

         <textarea rows = "5" cols = "50" name = "description">
         </textarea>

         <input type = "submit" value = "submit" />
      </form>
   </body>
</html>
What is the use of ‘Using’ statement in C#?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations.
The main goal is to manage resources and release all the resources automatically.
Let us see an example wherein “A” would print first since the SystemResource is allocated first.
 Live Demo
using System;
using System.Text;

class Demo {
   static void Main() {
      using (SystemResource res = new SystemResource()) {
         Console.WriteLine("A");
      }
      Console.WriteLine("B");
   }
}

class SystemResource : IDisposable {
   public void Dispose() {
      Console.WriteLine("C");
   }
}
A
C
B
How to compare two images using Java OpenCV library?

To compare two images −
Read Both of them using the Image.IO.read() method.
Read Both of them using the Image.IO.read() method.
Get the height and width of both of them to make sure they are equal.
Get the height and width of both of them to make sure they are equal.
Get the pixel values and, get the RGB values of both of the images.
Get the pixel values and, get the RGB values of both of the images.
Get the sum of the differences between the RGB values of these two images.
Get the sum of the differences between the RGB values of these two images.
Calculate the percentage of the difference using the following formula −
Calculate the percentage of the difference using the following formula −
Average = difference/weight*height*3;
Percentage = (Average/255)*100;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class ComparingImages {
   public static void main(String[] args) throws Exception {
      BufferedImage img1 = ImageIO.read(new File("D:\\Images\\test1.jpg"));
      BufferedImage img2 = ImageIO.read(new File("D:\\Images\\test2.jpg"));
      int w1 = img1.getWidth();
      int w2 = img2.getWidth();
      int h1 = img1.getHeight();
      int h2 = img2.getHeight();
      if ((w1!=w2)||(h1!=h2)) {
         System.out.println("Both images should have same dimwnsions");
      } else {
         long diff = 0;
         for (int j = 0; j < h1; j++) {
            for (int i = 0; i < w1; i++) {
               //Getting the RGB values of a pixel
               int pixel1 = img1.getRGB(i, j);
               Color color1 = new Color(pixel1, true);
               int r1 = color1.getRed();
               int g1 = color1.getGreen();
               int b1 = color1.getBlue();
               int pixel2 = img2.getRGB(i, j);
               Color color2 = new Color(pixel2, true);
               int r2 = color2.getRed();
               int g2 = color2.getGreen();
               int b2= color2.getBlue();
               //sum of differences of RGB values of the two images
               long data = Math.abs(r1-r2)+Math.abs(g1-g2)+ Math.abs(b1-b2);
               diff = diff+data;
            }
         }
         double avg = diff/(w1*h1*3);
         double percentage = (avg/255)*100;
         System.out.println("Difference: "+percentage);
      }
   }
}
Difference: 92.54901960784314