code-rag-bench/online-tutorials huggingface dataset:
MySQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criterion.
The AVG() function returns the average value of a numeric column. 
The SUM() function returns the total sum of a numeric column. 
Below is a selection from the "Products" table in the Northwind sample database:
The following SQL statement finds the number of products:
Note: NULL values are not counted.
The following SQL statement finds the average price of all products:
Note: NULL values are ignored.
Below is a selection from the "OrderDetails" table in the Northwind 
sample database:
The following SQL statement finds the sum of the "Quantity" fields 
in the "OrderDetails" table:
Note: NULL values are ignored.
Use the correct function to return the number of records that have the Price value set to 18.
SELECT (*)
FROM Products
 Price = 18;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
fgets() and gets() in C

The function fgets() is used to read the string till the new line character. It checks array bound and it is safe too.
Here is the syntax of fgets() in C language,
char *fgets(char *string, int value, FILE *stream)
Here,
string − This is a pointer to the array of char.
value − The number of characters to be read.
stream − This is a pointer to a file object.
Here is an example of fgets() in C language,
 Live Demo
#include <stdio.h>
#define FUNC 8
int main() {
   char b[FUNC];
   fgets(b, FUNC, stdin);
   printf("The string is: %s\n", b);
   return 0;
}
The input string is “Hello World!” in stdin stream.
The string is: Hello W
In the above program, an array of char type is declared. The function fgets() reads the characters till the given number from STDIN stream.
char b[FUNC];
fgets(b, FUNC, stdin);
The function gets() is used to read the string from standard input device. It does not check array bound and it is insecure too.
Here is the syntax of gets() in C language,
char *gets(char *string);
Here,
string − This is a pointer to the array of char.
Here is an example of gets() in C language,
#include <stdio.h>
#include <string.h>
int main() {
   char s[100];
   int i;
   printf("\nEnter a string : ");
   gets(s);
   for (i = 0; s[i]!='\0'; i++) {
      if(s[i] >= 'a' && s[i] <= 'z') {
         s[i] = s[i] - 32;
      }
   }
   printf("\nString in Upper Case = %s", s);
   return 0;
}
Enter a string : hello world!
String in Upper Case = HELLO WORLD!
In the above program, the string s of char array is converted into upper case string. The function gets() is used to read the string from the stdin stream.
char s[100];
int i;
printf("\nEnter a string : ");
gets(s);
What are the differences between length and length () in Java?


The length is an instance variable of an array in Java whereas length() is a method of String class.
An array is an object that holds a fixed number of values of the same type.
The length variable in an array returns the length of an array i.e. a number of elements stored in an array.
Once arrays are initialized, its length cannot be changed, so the length variable can directly be used to get the length of an array.
The length variable is used only for an array.
Live Demo
public class ArrayLengthTest {
   public static void main(String args[]) {
      int array[] = {1, 2, 3, 4, 5, 6, 7};
      System.out.println("Length of an array is: " + array.length);
   }
}
Length of an array is: 7

The length() method is a static method of String class.
The length() returns the length of a string object i.e. the number of characters stored in an object.
String class uses this method because the length of a string can be modified using the various operations on an object.
The String class internally uses a char[] array that it does not expose to the outside world.
Live Demo
public class StringLengthMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to Tutorials Point";
      System.out.println("Length of String using length() method is: " + str.length());
   }
}
Length of String using length() method is: 26
How to change the color spaces of an image using Java OpenCV library?

Using color space protocol you can represent the colors in an image. There are several color spaces available in OpenCV some of them are −
BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR.
BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR.
HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness.
HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness.
CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white.
CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white.
Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards.
Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards.
You can convert the representation of an image from one color space to another using the cvtColor() method of the org.opencv.imgproc.Imgproc class. This method accepts a source image, destination image and the code representing the color of the destination image.
To change the color space from BGR to HSV you need to pass COLOR_BGR2HSV as the color code value. Similarly to change the color space from BGR to YUV you need to pass COLOR_BGR2YUV as the color code.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ChangingColorSpaces {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the image
      Mat src = Imgcodecs.imread("D:\\images\\elephant.jpg");
      //Creating the empty destination matrix
      Mat dst = new Mat();
      //Converting From BGR to Gray
      Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY);
      HighGui.imshow("BGR to Gray", dst);
      dst = new Mat();
      //Converting From BGR to HSV
      Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2HSV);
      HighGui.imshow("BGR to HSV", dst);
      dst = new Mat();
      //Converting From BGR to HSV
      Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2YUV);
      HighGui.imshow("BGR to YUV", dst);
      HighGui.waitKey();
   }
}
On executing, the above program generates the following windows −
BGR to Gray − 
BGR to HSV − 
BGR to YUV −
Selenium and iframe in html.

We can work with iframe in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document.
Selenium by default has access to the parent browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift to frames −
switchTo().frame(id) - The id or name of frame is passed as an argument.Syntax −
driver.switchTo().frame("id"), switching to the frame with id.
switchTo().frame(id) - The id or name of frame is passed as an argument.
Syntax −
driver.switchTo().frame("id"), switching to the frame with id.
switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.Syntax −
driver.switchTo().frame(0), switching to the first frame in the page.
switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.
Syntax −
driver.switchTo().frame(0), switching to the first frame in the page.
switchTo().frame(webelement n) - The webelement of frame is passed as an argument.Syntax −
driver.switchTo().frame(l), switching to the frame with webelement l.
switchTo().frame(webelement n) - The webelement of frame is passed as an argument.
Syntax −
driver.switchTo().frame(l), switching to the frame with webelement l.
switchTo().defaultContent() – Switching focus from frame to the main page.Syntax −
driver.switchTo().defaultContent()
switchTo().defaultContent() – Switching focus from frame to the main page.
Syntax −
driver.switchTo().defaultContent()
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class iFrameMethods{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://the-internet.herokuapp.com/frames");
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      // identify element and click
      driver.findElement(By.partialLinkText("Nested")).click();
      // switching to frame with frame name
      driver.switchTo().frame("frame-bottom");
      WebElement m = driver.findElement(By.cssSelector("body"));
      System.out.println("Frame text: " +m.getText());
      driver.close();
   }
}
Automata Theory | Set 8 - GeeksforGeeks

25 Feb, 2019
These questions for practice purpose for GATE CS Exam.
Ques-1: Which one of the following language is Regular?
(A) {wxwR | w,x ∈ (a+b)+}(B) {wxwR | w ∈ (a+b)*, x ∈ {a,b}}(C) {wwRx | w,x ∈ (a+b)+}(D) {wwR | w ∈ (a+b)*}
Explanation:
(A) It is correct, since this language can form regular expression which is {{ a(a + b)+a } + {b(a + b)+b}}, i.e., start and end with same symbol.
(B) It is deterministic context free language since, string before and and after ‘x’ are same so, it is matched.
(C) It cannot be regular since, wwR is done at first which requires comparison which cannot be done via finite automata.
(D) It is also not regular since, comparison is required.
Option (A) is true.
Ques-2: Let w be any string of length n in {a, b}*. Consider ‘L’ be the set of all strings ending with at least n a’s. What is the minimum number of states in non deterministic finite automata that accept ‘L’?
(A) (n+3)(B) (n+1)(C) n(D) 2n
Explanation:It is correct since, the minimum number of states required for NFA for ending with at least 2 a’s is (2 + 1) i.e., regular expression will be (a + b)*aaHence, Number of states required for at least n a’s will be (n+1).
Option (B) is true.
Ques-3: What is the minimum number of states in deterministic finite automata (DFA) for string starting with ba2 and ending with ‘a’ over alphabet {a, b}?
(A) Ten(B) Nine(C) Eight(D) Six
Explanation:In the above DFA, minimum number of states required is six.
Option (D) is correct.
Ques-4: Consider the following statements:
S1 = {(an)m | n = 0}
S2 = {anbn | n>=1} U {anbm | n>=1, m>=1} 
Which one of the following is regular?
(A) only S1(B) only S2(C) both S1 and S2(D) none
Explanation:Both given languages are regular. Option (C) is correct.
Ques-5: What is the number of states in minimal NFA(non deterministic finite automata), which accepts set of all strings in which the third last symbol is ‘a’ over alphabet {a, b}?
(A) three(B) four(C) six(D) five
Explanation:In the above NFA, minimum number of states required is four.
Option (B) is true.
GATE
GATE CS
Theory of Computation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 2) | Question 48
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
C# program to count upper and lower case characters in a given string

To count uppercase characters in a string, check the following condition −
myStr[i]>='A' &amp;&amp; myStr[i]<='Z'
To count lower case characters in a string, check the following condition −
myStr[i]>='a' &amp;&amp; myStr[i]<='z'
You can try to run the following code to count upper and lower case characters in a given string.
Live Demo
using System;
public class Demo {
   public static void Main() {
      string myStr;
      int i, len, lower_case, upper_case;
      myStr = "Hello";
      Console.Write("String: "+myStr);
      lower_case = 0;
      upper_case = 0;
      len = myStr.Length;
      for(i=0; i<len; i++) {
         if(myStr[i]>='a' &amp;&amp; myStr[i]<='z') {
            lower_case++;
         } else if(myStr[i]>='A' &amp;&amp; myStr[i]<='Z') {
            upper_case++;
         }
      }
      Console.Write("\nCharacters in lowecase: {0}\n", lower_case);
      Console.Write("Characters in uppercase: {0}\n\n", upper_case);
   }
}
String: Hello
Characters in lowecase: 4
Characters in uppercase: 1
What is a static class in Java?

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
class MyOuter {
   static class Nested_Demo {
   }
}
Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class.
Live Demo
public class Outer {
   Java Arrays with Answers
   static class Nested_Demo {
      public void my_method() {
         System.out.println("This is my nested class");
      }
   }
   public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}
If you compile and execute the above program, you will get the following result −
This is my nested class
java.util.zip.Inflater.inflate() Method Example

The java.util.zip.Inflater.inflate(byte[] b) method uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the latter case, getAdler() can be used to get the Adler-32 value of the dictionary required.
Following is the declaration for java.util.zip.Inflater.inflate(byte[] b) method.
public int inflate(byte[] b)
   throws DataFormatException

b − the buffer for the uncompressed data.
b − the buffer for the uncompressed data.
the actual number of uncompressed bytes.
DataFormatException − if the compressed data format is invalid.
DataFormatException − if the compressed data format is invalid.
The following example shows the usage of java.util.zip.Inflater.inflate(byte[] b) method.
package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}
Let us compile and run the above program, this will produce the following result −
Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

 Print
 Add Notes
 Bookmark this page
How to initialize an empty DateTime in C#

Set a DateTime to its minimum value.
DateTime.MinValue;
The above will display the minimum value i.e.
1/1/0001
Let us see how to display the minimum value and avoid adding null to a date to initialize it as empty.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      DateTime dt = DateTime.MinValue;
      Console.WriteLine(dt);
   }
}
1/1/0001 12:00:00 AM
GATE | GATE CS 2021 | Set 1 | Question 43 - GeeksforGeeks

24 May, 2021
Consider the relation R(P,Q,S,T,X,Y,Z,W) with the following functional dependencies.
Consider the decomposition of the relation R into the constituent relations according to the following two decomposition schemes.
Which one of the following options is correct?(A) D1 is a lossless decomposition, but D2 is a lossy decomposition(B) D1 is a lossy decomposition, but D2 is a lossless decomposition(C) Both D1 and D2 are lossless decompositions(D) Both D1 and D2 are lossy decompositionsAnswer: (A)Explanation: Lossless-Join Decomposition:Lossless-Join Decomposition:Decomposition of R into R1, R2, R3, R4 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies):
R1 ∩ R2 → R1
   OR
R1 ∩ R2 → R2
For decomposition D1: 
R1(PQST)
R2(PTX)
R3(QY)
R4(YZW)
R1 ∩ R2 = (PT)+ = PTYXZW , it is a super key, so we can merge R1 and R2.
combined table T1 is PQSTX
 similarly,
R3 ∩ R4 =(Y)+ = YZW, it is a super key,  so we can merge R3 and R4.
another combined table T2 is QYZW.
now, Q is common in both T1 and T2.
 T1 ∩ T2 = Q+ = QYZW, it is a super key, so we can merge T1 and T2.
after combining, we get original table PQSTXYZW,
Hence D1 is lossless join decomposition.
For decomposition D2: 
R1(PQS)
R2(TX)
R3(QY)
R4(YZW)
since R2 has no common attributes as the primary key, so R2 cannot be merge with any other table, 
Hence D2 is lossy decomposition.
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
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-2015 (Set 1) | Question 42
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2009 | Question 60
Redis - Connections

Redis connection commands are basically used to manage client connections with Redis server.
Following example explains how a client authenticates itself to Redis server and checks whether the server is running or not.
redis 127.0.0.1:6379> AUTH "password" 
OK 
redis 127.0.0.1:6379> PING 
PONG 

Following table lists some basic commands related to Redis connections.
Authenticates to the server with the given password
Prints the given string
Checks whether the server is running or not
Closes the current connection
Changes the selected database for the current connection

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to create Time Picker in ReactJS ? - GeeksforGeeks

22 Jan, 2021
Time pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Time Picker in ReactJS using the following approach:
Creating React Application And Installing Module:
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 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import TextField from '@material-ui/core/TextField';  const App = () => {    return (    <div style={{      margin: 'auto',      display: 'block',      width: 'fit-content'    }}>      <h3>How to create Time Picker in ReactJS?</h3>      <TextField        label="Choose Time"        defaultValue="04:20"        type="time"        InputLabelProps={{          shrink: true,        }}        // 5 minutes        inputProps={{          step: 300,        }}      />    </div>  );}  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:
Supported Browser: This module is supported by the following browsers: 
Chrome
Microsoft Edge
Explorer
JavaScript
ReactJS
Web Technologies
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 PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
PyQt5 - QSlider Widget & Signal

QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and the upper bounds of the control.
A slider control can be displayed in horizontal or vertical manner by mentioning the orientation in the constructor.
self.sp = QSlider(Qt.Horizontal)
self.sp = QSlider(Qt.Vertical)

The following table lists some of the frequently used methods of QSlider class −
setMinimum()
Sets the lower bound of the slider
setMaximum()
Sets the upper bound of the slider
setSingleStep()
Sets the increment/decrement step
setValue()
Sets the value of the control programmatically
value()
Returns the current value
setTickInterval()
Puts the number of ticks on the groove
setTickPosition()
Places the ticks on the groove. Values are −
The following are the methods in QSlider Signals −
valueChanged()
When the slider's value has changed
sliderPressed()
When the user starts to drag the slider
sliderMoved()
When the user drags the slider
sliderReleased()
When the user releases the slider
valueChanged() signal is the one which is most frequently used.
The following example demonstrates the above functionality. A Label and a horizontal slider is placed in a vertical layout. Slider’s valueChanged() signal is connected to valuechange() method.
self.sl.valueChanged.connect(self.valuechange)

The slot function valuechange() reads current value of the slider and uses it as the size of font for label’s caption.
size = self.sl.value()
self.l1.setFont(QFont("Arial",size))

The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class sliderdemo(QWidget):
   def __init__(self, parent = None):
      super(sliderdemo, self).__init__(parent)

      layout = QVBoxLayout()
      self.l1 = QLabel("Hello")
      self.l1.setAlignment(Qt.AlignCenter)
      layout.addWidget(self.l1)
		
      self.sl = QSlider(Qt.Horizontal)
      self.sl.setMinimum(10)
      self.sl.setMaximum(30)
      self.sl.setValue(20)
      self.sl.setTickPosition(QSlider.TicksBelow)
      self.sl.setTickInterval(5)
		
      layout.addWidget(self.sl)
      self.sl.valueChanged.connect(self.valuechange)
      self.setLayout(layout)
      self.setWindowTitle("SpinBox demo")

   def valuechange(self):
      size = self.sl.value()
      self.l1.setFont(QFont("Arial",size))
		
def main():
   app = QApplication(sys.argv)
   ex = sliderdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
The font size of the label changes as handle of the slider is moved across the handle.

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: Template 3
Store mouse click event coordinates with Matplotlib

To store mouse event coordinates with matplotlib, we can use "button_press_event" event.−
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Plot a line in the range of 10
Bind the function *onclick* to the event *button_press_event*.
Print the x and y data of the event.
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams['backend'] = 'TkAgg'
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Function to print mouse click event coordinates
def onclick(event):
   print([event.xdata, event.ydata])

# Create a figure and a set of subplots
fig, ax = plt.subplots()

# Plot a line in the range of 10
ax.plot(range(10))

# Bind the button_press_event with the onclick() method
fig.canvas.mpl_connect('button_press_event', onclick)

# Display the plot
plt.show()
On execution, it will produce the following output:
Now, click anywhere on the plot and it will display that particular point's coordinates on the console:
[6.277811659536052 6.218189947945731]
[4.9416949672083685 3.7079096112932475]
[8.221254287227506 3.4145010811941963]
How to find the number of NA’s in each column of an R data frame?

Sometimes the data frame is filled with too many missing values/ NA’s and each column of the data frame contains at least one NA. In this case, we might want to find out how many missing values exists in each of the columns. Therefore, we can use colSums function along with is.na in the following manner: colSums(is.na(df)) #here df refers to data frame name.
Consider the below data frame −
 Live Demo
set.seed(109)
x1<-sample(c(0:1,NA),20,replace=TRUE)
x2<-sample(c(rpois(5,2),NA),20,replace=TRUE)df1<-data.frame(x1,x2)
df1
   x1   x2
1   0   1
2  1   NA
3  NA   0
4  NA   0
5  1   1
6  1   1
7  NA  NA
8  NA  NA
9  0   1
10 NA 1
11  1 1
12 0 1
13 NA 1
14 0 0
15 1 1
16 NA 0
17 1 1
18 1 NA
19 NA NA
20 0 0
Finding the number of NA’s in each column of the data frame df1 −
colSums(is.na(df1))
x1 x2
6 4
Let’s have a look at another example −
 Live Demo
y1<-sample(c(100,105,NA,115,120),20,replace=TRUE)
y2<-sample(c(rnorm(3,1,0.04),NA),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
y1 y2
1 NA NA
2 NA NA
3 105 NA
4 115 0.9910075
5 120 NA
6 120 0.9547570
7 105 0.9547570
8 105 1.0468139
9 120 0.9910075
10 115 0.9547570
11 115 0.9910075
12 100 0.9910075
13 NA 1.0468139
14 120 1.0468139
15 NA 1.0468139
16 115 NA
17 115 1.0468139
18 100 NA
19 120 0.9910075
20 120 0.9910075
Finding the number of NA’s in each column of the data frame df2 −
colSums(is.na(df2))
y1 y2
3 3
Round off a number to the next multiple of 5 using JavaScript - GeeksforGeeks

27 Aug, 2019
Given a positive integer n and the task is to round the number to the next whole number having divisible by 5.
Examples:
Input : 46 
Output : 50

Input : 21
Output : 25

Input : 30 
Output : 30

Approach 1:
Take the number in a variable.
Divide it by 5 and get the decimal value.
Take the ceil value of the decimal value by using math.ceil().
Multiply it by 5 to get the result.
<script>    function round(x) {        return Math.ceil(x / 5) * 5;    }  var n = 34;console.log(round(n)); </script>
Output:
35

Approach 2:
Take the number in a variable.
If it is divisible by 5, return the same number.
Else divide it by 5, take floor value and again multiply it by 5 and add 5 as well.
<script>    function round(x) {        if (x % 5 == 0) {            return int(Math.floor(x / 5)) * 5;        } else {            return (int(Math.floor(x / 5)) * 5) + 5;        }    }  var n = 34;console.log(round(n)); </script>
Output:
35

javascript-math
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Shell Sort Program in C

Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left.
#include <stdio.h>
#include <stdbool.h>

#define MAX 7

int intArray[MAX] = {4,6,3,2,1,9,7};

void printline(int count) {
   int i;
	
   for(i = 0;i < count-1;i++) {
      printf("=");
   }
	
   printf("=\n");
}

void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf("%d ",intArray[i]);
   }
	
   printf("]\n");
}

void shellSort() {
   int inner, outer;
   int valueToInsert;
   int interval = 1;   
   int elements = MAX;
   int i = 0;
   
   while(interval <= elements/3) {
      interval = interval*3 +1;
   }

   while(interval > 0) {
      printf("iteration %d#:",i); 
      display();
      
      for(outer = interval; outer < elements; outer++) {
         valueToInsert = intArray[outer];
         inner = outer;
			
         while(inner > interval -1 && intArray[inner - interval] 
            >= valueToInsert) {
            intArray[inner] = intArray[inner - interval];
            inner -=interval;
            printf(" item moved :%d\n",intArray[inner]);
         }
         
         intArray[inner] = valueToInsert;
         printf(" item inserted :%d, at position :%d\n",valueToInsert,inner);
      }
		
      interval = (interval -1) /3;
      i++;
   }          
}

int main() {
   printf("Input Array: ");
   display();
   printline(50);
   shellSort();
   printf("Output Array: ");
   display();
   printline(50);
   return 1;
}
If we compile and run the above program, it will produce the following result −
Input Array: [4 6 3 2 1 9 7 ]
==================================================
iteration 0#:[4 6 3 2 1 9 7 ]
 item moved :4
 item inserted :1, at position :0
 item inserted :9, at position :5
 item inserted :7, at position :6
iteration 1#:[1 6 3 2 4 9 7 ]
 item inserted :6, at position :1
 item moved :6
 item inserted :3, at position :1
 item moved :6
 item moved :3
 item inserted :2, at position :1
 item moved :6
 item inserted :4, at position :3
 item inserted :9, at position :5
 item moved :9
 item inserted :7, at position :5
Output Array: [1 2 3 4 6 7 9 ]
Python – Unpacking Values in Strings

29 Aug, 2020
Given a dictionary, unpack its values into a string.
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “Gfg”, 9 : “Best”}Output : First value is Gfg Second is BestExplanation : After substitution, we get Gfg and Best as values.
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “G”, 9 : “f”}Output : First value is G Second is f.Explanation : After substitution, we get G and f as values.
Method : Using format() +  * operator + values()
The combination of above functions can be used to solve this problem. In this, we use format to map required value with braces in string. The * operator is used to unpack and assign. The values are extracted using values().
Python3
# Python3 code to demonstrate working of # Unpacking Integer Keys in Strings# Using format() + * operator + values()  # initializing stringtest_str = "First value is {} Second is {} Third {}"  # printing original stringprint("The original string is : " + str(test_str))  # initializing dictionary test_dict = {3 : "Gfg", 4 : "is", 9 : "Best"}  # using format() for mapping required values res = test_str.format(*test_dict.values())      # printing result print("String after unpacking dictionary : " + str(res)) 
The original string is : First value is {} Second is {} Third {}
String after unpacking dictionary : First value is Gfg Second is is Third Best


Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.uniqueId() Method

09 Sep, 2020
The Lodash _.uniqueId() method is used to create an unique id for some element each time. This method will work for the purpose of assigning a unique id for most use cases, but not with complex projects that require a unique id always even if the project restarts. 
Syntax:
_.uniqueId(prefix)
Parameters: This method accepts a single parameter as mentioned above and described below:
prefix: The value to prefix the ID with.
Return Value: This method returns the string unique ID.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");              // Use of _.uniqueId()  // Method without the prefixlet gfg = _.uniqueId();         // Printing the output  console.log(gfg);
Output:
1

Example 2:
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.uniqueId()  // Method with prefixlet ans = _.uniqueId("gfg_");   // Printing the output  console.log(ans);   let ans1 = _.uniqueId("gfg_");   // Printing the output  console.log(ans1);
Output:
gfg_1
gfg_2

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Date setDate() Method

Javascript date setDate() method sets the day of the month for a specified date according to local time.
Its syntax is as follows −
Date.setDate( dayValue )

dayValue  − An integer from 1 to 31, representing the day of the month.
Try the following example.
<html>
   <head>
      <title>JavaScript setDate Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date( "Aug 28, 2008 23:30:00" );
         dt.setDate( 24 );
         document.write( dt );
      </script>   
   </body>
</html>
Sun Aug 24 2008 23:30:00 GMT+0530 (India Standard Time) 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Comparator function of qsort() in C

In C, we get the qsort() function. This is used to sort some array using quicksort technique. In this function we have to pass the comparator function. This comparator function takes two arguments. Then compares them and get the relative order between them. These two arguments are pointers, and type casted to const void*. The syntax is like below −
int comparator(const void* p1, const void* p2);
The return values are of three types −
Less than 0. The element pointed by p1 will go before the second one.
Equal to 0. Two values are same.
Greater than 0. The element pointed by p1 will go after the second one
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
   char title[50];
   int pages;
   float price;
}
book;
int compareBook(book b1, book b2){
   if(b1.price < b2.price){
      return 0;
   }
   return 1;
}
main() {
   int i;
   book book_arr[5];
   strcpy(book_arr[0].title, "C Programming");
   book_arr[0].pages = 260;
   book_arr[0].price = 450;
   strcpy(book_arr[1].title, "DBMS Guide");
   book_arr[1].pages = 850;
   book_arr[1].price = 775;
   strcpy(book_arr[2].title, "Learn C++");
   book_arr[2].pages = 350;
   book_arr[2].price = 520;
   strcpy(book_arr[3].title, "Data Structures");
   book_arr[3].pages = 380;
   book_arr[3].price = 430;
   strcpy(book_arr[4].title, "Learn Python");
   book_arr[4].pages = 500;
   book_arr[4].price = 300;
   qsort((void*)book_arr, 5, sizeof(book_arr[0]), compareBook);
   for(i = 0; i<5; i++) {
      printf("%s\t\t%d\t\t%f\n",book_arr[i].title, book_arr[i].pages, book_arr[i].price);
   }
}
Learn Python             500       300.000000
Data Structures          380       430.000000
C Programming            260       450.000000
Learn C++                350       520.000000
DBMS Guide               850       775.000000
Gamma Distribution in R Programming – dgamma(), pgamma(), qgamma(), and rgamma() Functions

30 Jun, 2020
The Gamma distribution in R Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is the implementation of functions of gamma distribution.
dgamma() function is used to create gamma density plot which is basically used due to exponential and normal distributions factors.
Syntax:dgamma(x_dgamma, shape)
Parameters:x_dgamma: defines gamma functionshape: gamma density of input values
Returns: Plot dgamma values
Example :
# R program to plot gamma distribution  # Specify x-values for gamma functionx_dgamma <- seq(0, 2, by = 0.04)     # Apply dgamma functiony_dgamma <- dgamma(x_dgamma, shape = 6)   # Plot dgamma valuesplot(y_dgamma)
Output :
pgamma() function is used in cumulative distribution function (CDF) of the gamma distribution.
Syntax:pgamma(x_pgamma, shape)
Parameters:x_pgamma: defines gamma functionshape: gamma density of input values
Returns: Plot pgamma values
Example:
# R program to plot gamma distribution  # Specify x-values for gamma functionx_pgamma <- seq(0, 2, by = 0.04)     # Apply pgamma functiony_pgamma <- pgamma(x_pgamma, shape = 6)   # Plot pgamma valuesplot(y_pgamma)
Output:
It is known as gamma quantile function of the gamma distribution and used to plot qgamma distribution.
Syntax:qgamma(x_qgamma, shape)
Parameters:x_qgamma: defines gamma functionshape: gamma density of input values
Returns: Plot qgamma values with gamma density
Example :
# R program to plot gamma distribution  # Specify x-values for gamma functionx_qgamma <- seq(0, 1, by = 0.03)     # Apply qgamma functiony_qgamma <- qgamma(x_qgamma, shape = 6)   # Plot qgamma valuesplot(y_qgamma)
Output:
This function is basically used for generating random number in gamma distribution.
Syntax:rgamma(N, shape)
Parameters:N: gamma distributed valuesshape: gamma density of input values
Returns: Plot rgamma values with gamma density
Example :
# R program to plot gamma distribution  # Set seed for reproducibilityset.seed(1200)   # Specify sample sizeN <- 800    # Draw N gamma distributed valuesy_rgamma <- rgamma(N, shape = 5)   # Print values to RStudio consoley_rgamma   # Plot of randomly drawn gamma densityhist(y_rgamma, breaks = 500, main = "")
Output:
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
How to handle Frames/iFrames in Selenium with Python

08 Jul, 2022
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python.
HTML outlines are utilized to isolate your program window into numerous segments where each part can stack a different HTML report. An assortment of edges in the program window is known as a frame set. The window is partitioned into outlines likewise the tables are composed: into lines and segments.
Requirement: You need to install chromedriver and set path. Click here to download.for more information follows this link.
 Handle Frames/iFrames:-
switch_to.frame(name)
Process:
This web page is divided into three frames, left top (1st frame) and left bottom(2nd frame) and the third frame. All the frames interconnected. Then we perform these actions by selenium:
First of all, switch to the default frame to the first frame.
Then find the element using link text method
Go back to the default frame.
Then go to the 2nd frame
Find element using the link text method
Go back to the default frame
Then switch to the 3rd frame.
Then find element by x path.
Implementation:
Python3
# importing the modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time # using chrome driverdriver = webdriver.Chrome() # web page urldriver.get("https://www.selenium.dev/selenium/docs/api/java/index.html") # switch to 1st framedriver.switch_to.frame("packageListFrame") # click on 1st framedriver.find_element_by_link_text("org.openqa.selenium.opera").click() # back to default web page framedriver.switch_to.default_content() # switch to 2nd framedriver.switch_to.frame("packageFrame") # click on  2nd framedriver.find_element_by_link_text("OperaOptions").click() # back to default web page framedriver.switch_to.default_content() # switch to 3rd framedriver.switch_to.frame("classFrame") # click on  2nd framedriver.find_element_by_xpath('/html/body/div[1]/ul/li[4]/a').click()time.sleep(4)
Output:–
mitalibhola94
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
SQL | DELETE Statement

28 Jun, 2021
The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause.
Basic Syntax:
DELETE FROM table_name WHERE some_condition;

table_name: name of the table
some_condition: condition to choose particular record.

Note: We can delete single as well as multiple records depending on the condition we provide in WHERE clause. If we omit the WHERE clause then all of the records will be deleted and the table will be empty.
Sample Table:
Example Queries:
Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the first row.DELETE FROM Student WHERE NAME = 'Ram';
Output:The above query will delete only the first row and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX204SURESHDelhiXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX202RAMESHGURGAONXXXXXXXXXX18
DELETE FROM Student WHERE NAME = 'Ram';

Output:The above query will delete only the first row and the table Student will now look like,
Deleting multiple records: Delete the rows from the table Student where Age is 20. This will delete 2 rows(third row and fifth row).DELETE FROM Student WHERE Age = 20;
Output:The above query will delete two rows(third row and fifth row) and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX184SURESHDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18
DELETE FROM Student WHERE Age = 20;

Output:The above query will delete two rows(third row and fifth row) and the table Student will now look like,
Delete all of the records: There are two queries to do this as shown below,query1: "DELETE FROM Student";

query2: "DELETE * FROM Student";
Output:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty!
query1: "DELETE FROM Student";

query2: "DELETE * FROM Student";

Output:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty!
SQL Quiz
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Generate Random Numbers From The Uniform Distribution using NumPy

05 Sep, 2020
Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. 
Syntax:
numpy.random.uniform(low = 0.0, high = 1.0, size = None)  
In uniform distribution samples are uniformly distributed over the half-open interval [low, high) it includes low but excludes high interval.
Examples:
Python3
# importing moduleimport numpy as np    # numpy.random.uniform() methodr = np.random.uniform(size=4)  # printing numbersprint(r)
Output:
[0.3829765  0.50958636 0.42844207 0.4260992  0.3513896 ]

Example 2:
Python3
# importing moduleimport numpy as np    # numpy.random.uniform() methodrandom_array = np.random.uniform(0.0, 1.0, 5)  # printing 1D array with random numbersprint("1D Array with random values : \n", random_array)
Output:
1D Array with random values :
[0.2167103  0.07881761 0.89666672 0.31143605 0.31481039]

Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to stop the Azure VM using Azure CLI in PowerShell?

To stop the azure VM using Azure CLI we can use the az vm stop command. Before running this command make sure that you are connected to the Azure account and the proper Azure subscription.
When we run this command, we need to provide the Azure VM name (-n) and the resource group name (-g).
PS C:\> az vm stop -n Win2k16VM1 -g TESTVMRG --verbose
The above command will stop the Azure VM Win2k16VM1 from the resource group TestVMRG. Alternatively, you can also use the full parameter name as shown below.
PS C:\> az vm stop --name win2k16vm1 --resource-group testvmrg
This command will wait until the Azure VM stops. To stop the Azure VM without waiting for the VM to stop and move the execution to the next step, we can use -- no-wait parameter.
PS C:\> az vm stop --name win2k16vm1 --resource-group testvmrg --no-wait