title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to create an ordered list with list items numbered with lowercase roman numbers in HTML?
|
To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, lowercase letters uppercase letters, roman letters, etc. The default numbers for list items.
For creating an ordered list with lowercase roman numbers, use the <ol> tag attribute type. This attribute will assign a lowercase roman number i.e. <ol type = “i”> to create ordered list numbered with lowercase roman numbers.
You can try to run the following code to create an ordered list with list items numbered with lowercase roman numbers in HTML −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>World Cup Teams</title>
</head>
<body>
<h1>List of teams for World Cup</h1>
<ol type = "i">
<li>India</li>
<li>Australia</li>
<li>South Africa</li>
<li>New Zealand</li>
<li>Pakistan</li>
<li>Srilanka</li>
<li>West Indies</li>
<li>Bangladesh</li>
</ol>
</body>
</html>
|
[
{
"code": null,
"e": 1439,
"s": 1187,
"text": "To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, lowercase letters uppercase letters, roman letters, etc. The default numbers for list items."
},
{
"code": null,
"e": 1666,
"s": 1439,
"text": "For creating an ordered list with lowercase roman numbers, use the <ol> tag attribute type. This attribute will assign a lowercase roman number i.e. <ol type = “i”> to create ordered list numbered with lowercase roman numbers."
},
{
"code": null,
"e": 1794,
"s": 1666,
"text": "You can try to run the following code to create an ordered list with list items numbered with lowercase roman numbers in HTML −"
},
{
"code": null,
"e": 1804,
"s": 1794,
"text": "Live Demo"
},
{
"code": null,
"e": 2217,
"s": 1804,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>World Cup Teams</title>\n </head>\n <body>\n <h1>List of teams for World Cup</h1>\n <ol type = \"i\">\n <li>India</li>\n <li>Australia</li>\n <li>South Africa</li>\n <li>New Zealand</li>\n <li>Pakistan</li>\n <li>Srilanka</li>\n <li>West Indies</li>\n <li>Bangladesh</li>\n </ol>\n </body>\n</html>"
}
] |
How to write an empty function in Python – pass statement?
|
07 Jun, 2022
In C/C++ and Java, we can write empty function as following
// An empty function in C/C++/Java
void fun() { }
In Python, if we write something like following in Python, it would produce compiler error.
# Incorrect empty function in Pythondef fun():
Output :
IndentationError: expected an indented block
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement.
# Correct way of writing empty function # in Pythondef fun(): pass
We can use pass in empty while statement also.
# Empty loop in Pythonmutex = Truewhile (mutex == True) : pass
We can use pass in empty if else statements.
# Empty in if/else in Pythonmutex = Trueif (mutex == True) : passelse : print("False")
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 113,
"s": 53,
"text": "In C/C++ and Java, we can write empty function as following"
},
{
"code": null,
"e": 165,
"s": 113,
"text": "// An empty function in C/C++/Java\nvoid fun() { }\n"
},
{
"code": null,
"e": 257,
"s": 165,
"text": "In Python, if we write something like following in Python, it would produce compiler error."
},
{
"code": "# Incorrect empty function in Pythondef fun(): ",
"e": 305,
"s": 257,
"text": null
},
{
"code": null,
"e": 314,
"s": 305,
"text": "Output :"
},
{
"code": null,
"e": 359,
"s": 314,
"text": "IndentationError: expected an indented block"
},
{
"code": null,
"e": 512,
"s": 359,
"text": "In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement."
},
{
"code": "# Correct way of writing empty function # in Pythondef fun(): pass",
"e": 583,
"s": 512,
"text": null
},
{
"code": null,
"e": 630,
"s": 583,
"text": "We can use pass in empty while statement also."
},
{
"code": "# Empty loop in Pythonmutex = Truewhile (mutex == True) : pass",
"e": 696,
"s": 630,
"text": null
},
{
"code": null,
"e": 741,
"s": 696,
"text": "We can use pass in empty if else statements."
},
{
"code": "# Empty in if/else in Pythonmutex = Trueif (mutex == True) : passelse : print(\"False\")",
"e": 834,
"s": 741,
"text": null
},
{
"code": null,
"e": 841,
"s": 834,
"text": "Python"
}
] |
Maximum value in an array after m range increment operations
|
08 Jul, 2022
Consider an array of size n with all initial values as 0. We need to perform the following m range increment operations.
increment(a, b, k) : Increment values from 'a'
to 'b' by 'k'.
After m operations, we need to calculate the maximum of the values in the array.
Examples:
Input : n = 5 m = 3
a = 0, b = 1, k = 100
a = 1, b = 4, k = 100
a = 2, b = 3, k = 100
Output : 200
Explanation:
Initially array = {0, 0, 0, 0, 0}
After first operation:
array = {100, 100, 0, 0, 0}
After second operation:
array = {100, 200, 100, 100, 100}
After third operation:
array = {100, 200, 200, 200, 100}
Maximum element after m operations
is 200.
Input : n = 4 m = 3
a = 1, b = 2, k = 603
a = 0, b = 0, k = 286
a = 3, b = 3, k = 882
Output : 882
Explanation:
Initially array = {0, 0, 0, 0}
After first operation:
array = {0, 603, 603, 0}
After second operation:
array = {286, 603, 603, 0}
After third operation:
array = {286, 603, 603, 882}
Maximum element after m operations
is 882.
A naive method is to perform each operation on the given range and then, at last, find the maximum number.
C++
Java
Python3
C#
Javascript
// C++ implementation of simple approach to// find maximum value after m range increments.#include<bits/stdc++.h>using namespace std; // Function to find the maximum element after// m operationsint findMax(int n, int a[], int b[], int k[], int m){ int arr[n]; memset(arr, 0, sizeof(arr)); // start performing m operations for (int i = 0; i< m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for (int j=lowerbound; j<=upperbound; j++) arr[j] += k[i]; } // Find maximum value after all operations and // return int res = INT_MIN; for (int i=0; i<n; i++) res = max(res, arr[i]); return res;} // Driver codeint main(){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; // value of k to be added at each operation int k[] = {100, 100, 100}; int m = sizeof(a)/sizeof(a[0]); cout << "Maximum value after 'm' operations is " << findMax(n, a, b, k, m); return 0;}
// Java implementation of simple approach// to find maximum value after m range// increments.import java.util.*; class GFG{ // Function to find the maximum element after// m operationsstatic int findMax(int n, int a[], int b[], int k[], int m){ int[] arr = new int[n]; // Start performing m operations for(int i = 0; i < m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(int j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return int res = Integer.MIN_VALUE; for(int i = 0; i < n; i++) res = Math.max(res, arr[i]); return res;} // Driver Codepublic static void main (String[] args){ // Number of values int n = 5; int a[] = { 0, 1, 2 }; int b[] = { 1, 4, 3 }; // Value of k to be added at // each operation int k[] = { 100, 100, 100 }; int m = a.length; System.out.println("Maximum value after 'm' " + "operations is " + findMax(n, a, b, k, m));}} // This code is contributed by offbeat
# Python3 program of# simple approach to# find maximum value# after m range increments.import sys # Function to find the# maximum element after# m operationsdef findMax(n, a, b, k, m): arr = [0] * n # Start performing m operations for i in range(m): # Store lower and upper # index i.e. range lowerbound = a[i] upperbound = b[i] # Add 'k[i]' value at # this operation to whole range for j in range (lowerbound, upperbound + 1): arr[j] += k[i] # Find maximum value after # all operations and return res = -sys.maxsize - 1 for i in range(n): res = max(res, arr[i]) return res # Driver codeif __name__ == "__main__": # Number of values n = 5 a = [0, 1, 2] b = [1, 4, 3] # Value of k to be added # at each operation k = [100, 100, 100] m = len(a) print ("Maximum value after 'm' operations is ", findMax(n, a, b, k, m)) # This code is contributed by Chitranayal
// C# implementation of simple approach// to find maximum value after m range// increments.using System;public class GFG{ // Function to find the maximum element after // m operations static int findMax(int n, int[] a, int[] b, int[] k, int m) { int[] arr = new int[n]; // Start performing m operations for(int i = 0; i < m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(int j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return int res = Int32.MinValue; for(int i = 0; i < n; i++) res = Math.Max(res, arr[i]); return res; } // Driver Code static public void Main () { // Number of values int n = 5; int[] a = { 0, 1, 2 }; int[] b = { 1, 4, 3 }; // Value of k to be added at // each operation int[] k = { 100, 100, 100 }; int m = a.Length; Console.WriteLine("Maximum value after 'm' " + "operations is " + findMax(n, a, b, k, m)); }} // This code is contributed by avanitrachhadiya2155
<script> // Javascript implementation of simple approach // to find maximum value after m range // increments. // Function to find the maximum element after // m operations function findMax(n, a, b, k, m) { let arr = new Array(n); arr.fill(0); // Start performing m operations for(let i = 0; i < m; i++) { // Store lower and upper index i.e. range let lowerbound = a[i]; let upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(let j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return let res = Number.MIN_VALUE; for(let i = 0; i < n; i++) res = Math.max(res, arr[i]); return res; } // Number of values let n = 5; let a = [ 0, 1, 2 ]; let b = [ 1, 4, 3 ]; // Value of k to be added at // each operation let k = [ 100, 100, 100 ]; let m = a.length; document.write("Maximum value after 'm' " + "operations is " + findMax(n, a, b, k, m)); // This code is contributed by rameshtravel07.</script>
Maximum value after 'm' operations is 200
Time Complexity: O(m * max(range)). Here max(range) means maximum elements to which k is added in a single operation.Efficient method: The idea is similar to this post.
Perform two things in a single operation:
Add k-value to the only lower_bound of a range. Reduce the upper_bound + 1 index by a k-value.
Add k-value to the only lower_bound of a range.
Reduce the upper_bound + 1 index by a k-value.
After all operations, add all values, check the maximum sum, and print the maximum sum.
C++
Java
Python3
C#
Javascript
// C++ implementation of simple approach to// find maximum value after m range increments.#include<bits/stdc++.h>using namespace std; // Function to find maximum value after 'm' operationsint findMax(int n, int m, int a[], int b[], int k[]){ int arr[n+1]; memset(arr, 0, sizeof(arr)); // Start performing 'm' operations for (int i=0; i<m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 indexed value by k arr[upperbound+1] -= k[i]; } // Find maximum sum possible from all values long long sum = 0, res = INT_MIN; for (int i=0; i < n; ++i) { sum += arr[i]; res = max(res, sum); } // return maximum value return res;} // Driver codeint main(){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; int k[] = {100, 100, 100}; // m is number of operations. int m = sizeof(a)/sizeof(a[0]); cout << "Maximum value after 'm' operations is " << findMax(n, m, a, b, k); return 0;}
// Java implementation of// simple approach to// find maximum value after// m range increments.import java.io.*; class GFG{ // Function to find maximum// value after 'm' operationsstatic long findMax(int n, int m, int a[], int b[], int k[]){ int []arr = new int[n + 1]; //memset(arr, 0, sizeof(arr)); // Start performing 'm' operations for (int i = 0; i < m; i++) { // Store lower and upper // index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values long sum = 0, res = Integer.MIN_VALUE; for (int i = 0; i < n; ++i) { sum += arr[i]; res = Math.max(res, sum); } // return maximum value return res;} // Driver codepublic static void main (String[] args){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; int k[] = {100, 100, 100}; // m is number of operations. int m = a.length; System.out.println("Maximum value after "+ "'m' operations is " + findMax(n, m, a, b, k)); }} // This code is contributed by anuj_67.
# Java implementation of# simple approach to# find maximum value after# m range increments.import sysdef findMax(n, m, a, b, k): arr = [ 0 for i in range(n + 1)] for i in range(m): lowerbound = a[i] upperbound = b[i] arr[lowerbound] += k[i] arr[upperbound + 1] -= k[i] sum = 0 res = -1-sys.maxsize for i in range(n): sum += arr[i] res = max(res, sum) return res n = 5a = [0, 1, 2]b = [1, 4, 3]k = [100, 100, 100] m = len(a) print("Maximum value after","'m' operations is", findMax(n, m, a, b, k)) # This code is contributed by rag2127
// c# implementation of// simple approach to// find maximum value after// m range increments.using System.Collections.Generic;using System;class GFG{ // Function to find maximum// value after 'm' operationsstatic long findMax(int n, int m, int []a, int []b, int []k){ int []arr = new int[n + 1]; // Start performing 'm' // operations for (int i = 0; i < m; i++) { // Store lower and upper // index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values long sum = 0, res = -10000000; for (int i = 0; i < n; ++i) { sum += arr[i]; res = Math.Max(res, sum); } // return maximum value return res;} // Driver codepublic static void Main (){ // Number of values int n = 5; int []a = {0, 1, 2}; int []b = {1, 4, 3}; int []k = {100, 100, 100}; // m is number of operations. int m = a.Length; Console.WriteLine("Maximum value after " + "'m' operations is " + findMax(n, m, a, b, k));}} // This code is contributed by Stream_Cipher
<script> // Javascript implementation of // simple approach to // find maximum value after // m range increments. // Function to find maximum // value after 'm' operations function findMax(n, m, a, b, k) { let arr = new Array(n + 1); arr.fill(0); // Start performing 'm' // operations for (let i = 0; i < m; i++) { // Store lower and upper // index i.e. range let lowerbound = a[i]; let upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values let sum = 0, res = -10000000; for (let i = 0; i < n; ++i) { sum += arr[i]; res = Math.max(res, sum); } // return maximum value return res; } // Number of values let n = 5; let a = [0, 1, 2]; let b = [1, 4, 3]; let k = [100, 100, 100]; // m is number of operations. let m = a.length; document.write("Maximum value after " + "'m' operations is " + findMax(n, m, a, b, k)); </script>
Maximum value after 'm' operations is 200
Time complexity: O(m + n)
This article is contributed by Sahil Chhabra. 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.
vt_m
offbeat
ukasp
Stream_Cipher
avanitrachhadiya2155
rag2127
rameshtravel07
decode2207
kk9826225
hardikkoriintern
FactSet
Arrays
Mathematical
FactSet
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 173,
"s": 52,
"text": "Consider an array of size n with all initial values as 0. We need to perform the following m range increment operations."
},
{
"code": null,
"e": 260,
"s": 173,
"text": "increment(a, b, k) : Increment values from 'a'\n to 'b' by 'k'. "
},
{
"code": null,
"e": 341,
"s": 260,
"text": "After m operations, we need to calculate the maximum of the values in the array."
},
{
"code": null,
"e": 351,
"s": 341,
"text": "Examples:"
},
{
"code": null,
"e": 1094,
"s": 351,
"text": "Input : n = 5 m = 3\n a = 0, b = 1, k = 100\n a = 1, b = 4, k = 100\n a = 2, b = 3, k = 100\nOutput : 200\nExplanation:\nInitially array = {0, 0, 0, 0, 0}\nAfter first operation:\narray = {100, 100, 0, 0, 0}\nAfter second operation:\narray = {100, 200, 100, 100, 100}\nAfter third operation:\narray = {100, 200, 200, 200, 100}\nMaximum element after m operations \nis 200.\n\nInput : n = 4 m = 3\n a = 1, b = 2, k = 603\n a = 0, b = 0, k = 286\n a = 3, b = 3, k = 882\nOutput : 882\nExplanation:\nInitially array = {0, 0, 0, 0}\nAfter first operation:\narray = {0, 603, 603, 0}\nAfter second operation:\narray = {286, 603, 603, 0}\nAfter third operation:\narray = {286, 603, 603, 882}\nMaximum element after m operations \nis 882."
},
{
"code": null,
"e": 1201,
"s": 1094,
"text": "A naive method is to perform each operation on the given range and then, at last, find the maximum number."
},
{
"code": null,
"e": 1205,
"s": 1201,
"text": "C++"
},
{
"code": null,
"e": 1210,
"s": 1205,
"text": "Java"
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Python3"
},
{
"code": null,
"e": 1221,
"s": 1218,
"text": "C#"
},
{
"code": null,
"e": 1232,
"s": 1221,
"text": "Javascript"
},
{
"code": "// C++ implementation of simple approach to// find maximum value after m range increments.#include<bits/stdc++.h>using namespace std; // Function to find the maximum element after// m operationsint findMax(int n, int a[], int b[], int k[], int m){ int arr[n]; memset(arr, 0, sizeof(arr)); // start performing m operations for (int i = 0; i< m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for (int j=lowerbound; j<=upperbound; j++) arr[j] += k[i]; } // Find maximum value after all operations and // return int res = INT_MIN; for (int i=0; i<n; i++) res = max(res, arr[i]); return res;} // Driver codeint main(){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; // value of k to be added at each operation int k[] = {100, 100, 100}; int m = sizeof(a)/sizeof(a[0]); cout << \"Maximum value after 'm' operations is \" << findMax(n, a, b, k, m); return 0;}",
"e": 2348,
"s": 1232,
"text": null
},
{
"code": "// Java implementation of simple approach// to find maximum value after m range// increments.import java.util.*; class GFG{ // Function to find the maximum element after// m operationsstatic int findMax(int n, int a[], int b[], int k[], int m){ int[] arr = new int[n]; // Start performing m operations for(int i = 0; i < m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(int j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return int res = Integer.MIN_VALUE; for(int i = 0; i < n; i++) res = Math.max(res, arr[i]); return res;} // Driver Codepublic static void main (String[] args){ // Number of values int n = 5; int a[] = { 0, 1, 2 }; int b[] = { 1, 4, 3 }; // Value of k to be added at // each operation int k[] = { 100, 100, 100 }; int m = a.length; System.out.println(\"Maximum value after 'm' \" + \"operations is \" + findMax(n, a, b, k, m));}} // This code is contributed by offbeat",
"e": 3617,
"s": 2348,
"text": null
},
{
"code": "# Python3 program of# simple approach to# find maximum value# after m range increments.import sys # Function to find the# maximum element after# m operationsdef findMax(n, a, b, k, m): arr = [0] * n # Start performing m operations for i in range(m): # Store lower and upper # index i.e. range lowerbound = a[i] upperbound = b[i] # Add 'k[i]' value at # this operation to whole range for j in range (lowerbound, upperbound + 1): arr[j] += k[i] # Find maximum value after # all operations and return res = -sys.maxsize - 1 for i in range(n): res = max(res, arr[i]) return res # Driver codeif __name__ == \"__main__\": # Number of values n = 5 a = [0, 1, 2] b = [1, 4, 3] # Value of k to be added # at each operation k = [100, 100, 100] m = len(a) print (\"Maximum value after 'm' operations is \", findMax(n, a, b, k, m)) # This code is contributed by Chitranayal",
"e": 4597,
"s": 3617,
"text": null
},
{
"code": "// C# implementation of simple approach// to find maximum value after m range// increments.using System;public class GFG{ // Function to find the maximum element after // m operations static int findMax(int n, int[] a, int[] b, int[] k, int m) { int[] arr = new int[n]; // Start performing m operations for(int i = 0; i < m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(int j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return int res = Int32.MinValue; for(int i = 0; i < n; i++) res = Math.Max(res, arr[i]); return res; } // Driver Code static public void Main () { // Number of values int n = 5; int[] a = { 0, 1, 2 }; int[] b = { 1, 4, 3 }; // Value of k to be added at // each operation int[] k = { 100, 100, 100 }; int m = a.Length; Console.WriteLine(\"Maximum value after 'm' \" + \"operations is \" + findMax(n, a, b, k, m)); }} // This code is contributed by avanitrachhadiya2155",
"e": 5832,
"s": 4597,
"text": null
},
{
"code": "<script> // Javascript implementation of simple approach // to find maximum value after m range // increments. // Function to find the maximum element after // m operations function findMax(n, a, b, k, m) { let arr = new Array(n); arr.fill(0); // Start performing m operations for(let i = 0; i < m; i++) { // Store lower and upper index i.e. range let lowerbound = a[i]; let upperbound = b[i]; // Add 'k[i]' value at this operation to // whole range for(let j = lowerbound; j <= upperbound; j++) arr[j] += k[i]; } // Find maximum value after all // operations and return let res = Number.MIN_VALUE; for(let i = 0; i < n; i++) res = Math.max(res, arr[i]); return res; } // Number of values let n = 5; let a = [ 0, 1, 2 ]; let b = [ 1, 4, 3 ]; // Value of k to be added at // each operation let k = [ 100, 100, 100 ]; let m = a.length; document.write(\"Maximum value after 'm' \" + \"operations is \" + findMax(n, a, b, k, m)); // This code is contributed by rameshtravel07.</script>",
"e": 7039,
"s": 5832,
"text": null
},
{
"code": null,
"e": 7081,
"s": 7039,
"text": "Maximum value after 'm' operations is 200"
},
{
"code": null,
"e": 7250,
"s": 7081,
"text": "Time Complexity: O(m * max(range)). Here max(range) means maximum elements to which k is added in a single operation.Efficient method: The idea is similar to this post."
},
{
"code": null,
"e": 7293,
"s": 7250,
"text": "Perform two things in a single operation: "
},
{
"code": null,
"e": 7388,
"s": 7293,
"text": "Add k-value to the only lower_bound of a range. Reduce the upper_bound + 1 index by a k-value."
},
{
"code": null,
"e": 7437,
"s": 7388,
"text": "Add k-value to the only lower_bound of a range. "
},
{
"code": null,
"e": 7484,
"s": 7437,
"text": "Reduce the upper_bound + 1 index by a k-value."
},
{
"code": null,
"e": 7572,
"s": 7484,
"text": "After all operations, add all values, check the maximum sum, and print the maximum sum."
},
{
"code": null,
"e": 7576,
"s": 7572,
"text": "C++"
},
{
"code": null,
"e": 7581,
"s": 7576,
"text": "Java"
},
{
"code": null,
"e": 7589,
"s": 7581,
"text": "Python3"
},
{
"code": null,
"e": 7592,
"s": 7589,
"text": "C#"
},
{
"code": null,
"e": 7603,
"s": 7592,
"text": "Javascript"
},
{
"code": "// C++ implementation of simple approach to// find maximum value after m range increments.#include<bits/stdc++.h>using namespace std; // Function to find maximum value after 'm' operationsint findMax(int n, int m, int a[], int b[], int k[]){ int arr[n+1]; memset(arr, 0, sizeof(arr)); // Start performing 'm' operations for (int i=0; i<m; i++) { // Store lower and upper index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 indexed value by k arr[upperbound+1] -= k[i]; } // Find maximum sum possible from all values long long sum = 0, res = INT_MIN; for (int i=0; i < n; ++i) { sum += arr[i]; res = max(res, sum); } // return maximum value return res;} // Driver codeint main(){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; int k[] = {100, 100, 100}; // m is number of operations. int m = sizeof(a)/sizeof(a[0]); cout << \"Maximum value after 'm' operations is \" << findMax(n, m, a, b, k); return 0;}",
"e": 8764,
"s": 7603,
"text": null
},
{
"code": "// Java implementation of// simple approach to// find maximum value after// m range increments.import java.io.*; class GFG{ // Function to find maximum// value after 'm' operationsstatic long findMax(int n, int m, int a[], int b[], int k[]){ int []arr = new int[n + 1]; //memset(arr, 0, sizeof(arr)); // Start performing 'm' operations for (int i = 0; i < m; i++) { // Store lower and upper // index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values long sum = 0, res = Integer.MIN_VALUE; for (int i = 0; i < n; ++i) { sum += arr[i]; res = Math.max(res, sum); } // return maximum value return res;} // Driver codepublic static void main (String[] args){ // Number of values int n = 5; int a[] = {0, 1, 2}; int b[] = {1, 4, 3}; int k[] = {100, 100, 100}; // m is number of operations. int m = a.length; System.out.println(\"Maximum value after \"+ \"'m' operations is \" + findMax(n, m, a, b, k)); }} // This code is contributed by anuj_67.",
"e": 10137,
"s": 8764,
"text": null
},
{
"code": "# Java implementation of# simple approach to# find maximum value after# m range increments.import sysdef findMax(n, m, a, b, k): arr = [ 0 for i in range(n + 1)] for i in range(m): lowerbound = a[i] upperbound = b[i] arr[lowerbound] += k[i] arr[upperbound + 1] -= k[i] sum = 0 res = -1-sys.maxsize for i in range(n): sum += arr[i] res = max(res, sum) return res n = 5a = [0, 1, 2]b = [1, 4, 3]k = [100, 100, 100] m = len(a) print(\"Maximum value after\",\"'m' operations is\", findMax(n, m, a, b, k)) # This code is contributed by rag2127",
"e": 10777,
"s": 10137,
"text": null
},
{
"code": "// c# implementation of// simple approach to// find maximum value after// m range increments.using System.Collections.Generic;using System;class GFG{ // Function to find maximum// value after 'm' operationsstatic long findMax(int n, int m, int []a, int []b, int []k){ int []arr = new int[n + 1]; // Start performing 'm' // operations for (int i = 0; i < m; i++) { // Store lower and upper // index i.e. range int lowerbound = a[i]; int upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values long sum = 0, res = -10000000; for (int i = 0; i < n; ++i) { sum += arr[i]; res = Math.Max(res, sum); } // return maximum value return res;} // Driver codepublic static void Main (){ // Number of values int n = 5; int []a = {0, 1, 2}; int []b = {1, 4, 3}; int []k = {100, 100, 100}; // m is number of operations. int m = a.Length; Console.WriteLine(\"Maximum value after \" + \"'m' operations is \" + findMax(n, m, a, b, k));}} // This code is contributed by Stream_Cipher",
"e": 12028,
"s": 10777,
"text": null
},
{
"code": "<script> // Javascript implementation of // simple approach to // find maximum value after // m range increments. // Function to find maximum // value after 'm' operations function findMax(n, m, a, b, k) { let arr = new Array(n + 1); arr.fill(0); // Start performing 'm' // operations for (let i = 0; i < m; i++) { // Store lower and upper // index i.e. range let lowerbound = a[i]; let upperbound = b[i]; // Add k to the lower_bound arr[lowerbound] += k[i]; // Reduce upper_bound+1 // indexed value by k arr[upperbound + 1] -= k[i]; } // Find maximum sum // possible from all values let sum = 0, res = -10000000; for (let i = 0; i < n; ++i) { sum += arr[i]; res = Math.max(res, sum); } // return maximum value return res; } // Number of values let n = 5; let a = [0, 1, 2]; let b = [1, 4, 3]; let k = [100, 100, 100]; // m is number of operations. let m = a.length; document.write(\"Maximum value after \" + \"'m' operations is \" + findMax(n, m, a, b, k)); </script>",
"e": 13264,
"s": 12028,
"text": null
},
{
"code": null,
"e": 13306,
"s": 13264,
"text": "Maximum value after 'm' operations is 200"
},
{
"code": null,
"e": 13332,
"s": 13306,
"text": "Time complexity: O(m + n)"
},
{
"code": null,
"e": 13629,
"s": 13332,
"text": "This article is contributed by Sahil Chhabra. 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."
},
{
"code": null,
"e": 13634,
"s": 13629,
"text": "vt_m"
},
{
"code": null,
"e": 13642,
"s": 13634,
"text": "offbeat"
},
{
"code": null,
"e": 13648,
"s": 13642,
"text": "ukasp"
},
{
"code": null,
"e": 13662,
"s": 13648,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 13683,
"s": 13662,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 13691,
"s": 13683,
"text": "rag2127"
},
{
"code": null,
"e": 13706,
"s": 13691,
"text": "rameshtravel07"
},
{
"code": null,
"e": 13717,
"s": 13706,
"text": "decode2207"
},
{
"code": null,
"e": 13727,
"s": 13717,
"text": "kk9826225"
},
{
"code": null,
"e": 13744,
"s": 13727,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 13752,
"s": 13744,
"text": "FactSet"
},
{
"code": null,
"e": 13759,
"s": 13752,
"text": "Arrays"
},
{
"code": null,
"e": 13772,
"s": 13759,
"text": "Mathematical"
},
{
"code": null,
"e": 13780,
"s": 13772,
"text": "FactSet"
},
{
"code": null,
"e": 13787,
"s": 13780,
"text": "Arrays"
},
{
"code": null,
"e": 13800,
"s": 13787,
"text": "Mathematical"
},
{
"code": null,
"e": 13898,
"s": 13800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13966,
"s": 13898,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14010,
"s": 13966,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 14042,
"s": 14010,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14090,
"s": 14042,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 14104,
"s": 14090,
"text": "Linear Search"
},
{
"code": null,
"e": 14134,
"s": 14104,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 14177,
"s": 14134,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 14237,
"s": 14177,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 14252,
"s": 14237,
"text": "C++ Data Types"
}
] |
Webcam QR code scanner using OpenCV
|
02 Mar, 2022
In this article, we’re going to see how to perform QR code scanning using a webcam.
Webcam QR CODE Scanner
Before starting, You need to know how this process is going to work. Firstly you need to open your webcam, and you’ve to run your python program to make it ready to scan the QR code. You can take the Qr code picture on your mobile and show the picture in front of your webcam. It correctly identifies the QR code that presents on your screen. And this program redirects you to a link hidden in the QR code.
Requirements:
pip install OpenCV
pip install webbrowser ( built in )
Step 1: For creating the QR code scanner you need to install the OpenCV library on your command prompt. First, you need to import the cv2 and browser library.Cv2 is used for scanning the QR code through a webcam and a web browser is used to take the URL into the browser.
Python3
import cv2import webbrowser
Step 2: Next, we need to start the camera for capturing the QR code. For that declare a variable called a cap and in this variable pass the instance cv2.VideoCapture(0). The next process is we need to create a variable called detector and in this variable call the object cv2.QRCodeDetector(). This object is a very helpful one for capturing QR codes in real-time.
Python3
cap = cv2.VideoCapture(0)# initialize the cv2 QRCode detectordetector = cv2.QRCodeDetector()
Step 3: This step is very important you need to create a while loop and in this loop create a variable called an img and this loop will read your webcam screen continuously until this loop breaks
Python3
while True: _, img = cap.read()
Step 4:
Next, create a variable called data, and this variable is to be used to decode the QR code, and if any data is present in the QR code image it will break the loop and it open the link in your browser. So this is the condition that I inserted here.
Python3
# detect and decode data, bbox, _ = detector.detectAndDecode(img) # check if there is a QRCode in the image if data: a=data break
Step 5:
Finally, call the object cv2.imshow this will produce the output and you’ve to assign the key to break the loop. Here I assigned the key that is called q, when we press the q it will stop the video streaming.
And then you’ve to create the variable, in this variable you need to call the object webbrowser.open( pass the variable an in this object )
Python3
cv2.imshow("QRCODEscanner", img) if cv2.waitKey(1) == ord("q"): break b=webbrowser.open(str(a))cap.release()cv2.destroyAllWindows()
Output :
ddeevviissaavviittaa
OpenCV
Misc
Python
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of OOP
Introduction to Electronic Mail
Hypervisor
Cloud Computing
Analog to Digital Conversion
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 138,
"s": 53,
"text": "In this article, we’re going to see how to perform QR code scanning using a webcam. "
},
{
"code": null,
"e": 161,
"s": 138,
"text": "Webcam QR CODE Scanner"
},
{
"code": null,
"e": 568,
"s": 161,
"text": "Before starting, You need to know how this process is going to work. Firstly you need to open your webcam, and you’ve to run your python program to make it ready to scan the QR code. You can take the Qr code picture on your mobile and show the picture in front of your webcam. It correctly identifies the QR code that presents on your screen. And this program redirects you to a link hidden in the QR code."
},
{
"code": null,
"e": 582,
"s": 568,
"text": "Requirements:"
},
{
"code": null,
"e": 637,
"s": 582,
"text": "pip install OpenCV\npip install webbrowser ( built in )"
},
{
"code": null,
"e": 909,
"s": 637,
"text": "Step 1: For creating the QR code scanner you need to install the OpenCV library on your command prompt. First, you need to import the cv2 and browser library.Cv2 is used for scanning the QR code through a webcam and a web browser is used to take the URL into the browser."
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Python3"
},
{
"code": "import cv2import webbrowser",
"e": 945,
"s": 917,
"text": null
},
{
"code": null,
"e": 1311,
"s": 945,
"text": "Step 2: Next, we need to start the camera for capturing the QR code. For that declare a variable called a cap and in this variable pass the instance cv2.VideoCapture(0). The next process is we need to create a variable called detector and in this variable call the object cv2.QRCodeDetector(). This object is a very helpful one for capturing QR codes in real-time. "
},
{
"code": null,
"e": 1319,
"s": 1311,
"text": "Python3"
},
{
"code": "cap = cv2.VideoCapture(0)# initialize the cv2 QRCode detectordetector = cv2.QRCodeDetector()",
"e": 1412,
"s": 1319,
"text": null
},
{
"code": null,
"e": 1608,
"s": 1412,
"text": "Step 3: This step is very important you need to create a while loop and in this loop create a variable called an img and this loop will read your webcam screen continuously until this loop breaks"
},
{
"code": null,
"e": 1616,
"s": 1608,
"text": "Python3"
},
{
"code": "while True: _, img = cap.read()",
"e": 1651,
"s": 1616,
"text": null
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Step 4:"
},
{
"code": null,
"e": 1907,
"s": 1659,
"text": "Next, create a variable called data, and this variable is to be used to decode the QR code, and if any data is present in the QR code image it will break the loop and it open the link in your browser. So this is the condition that I inserted here."
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Python3"
},
{
"code": "# detect and decode data, bbox, _ = detector.detectAndDecode(img) # check if there is a QRCode in the image if data: a=data break",
"e": 2063,
"s": 1915,
"text": null
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Step 5:"
},
{
"code": null,
"e": 2280,
"s": 2071,
"text": "Finally, call the object cv2.imshow this will produce the output and you’ve to assign the key to break the loop. Here I assigned the key that is called q, when we press the q it will stop the video streaming."
},
{
"code": null,
"e": 2420,
"s": 2280,
"text": "And then you’ve to create the variable, in this variable you need to call the object webbrowser.open( pass the variable an in this object )"
},
{
"code": null,
"e": 2428,
"s": 2420,
"text": "Python3"
},
{
"code": "cv2.imshow(\"QRCODEscanner\", img) if cv2.waitKey(1) == ord(\"q\"): break b=webbrowser.open(str(a))cap.release()cv2.destroyAllWindows()",
"e": 2573,
"s": 2428,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2573,
"text": " Output :"
},
{
"code": null,
"e": 2604,
"s": 2583,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 2611,
"s": 2604,
"text": "OpenCV"
},
{
"code": null,
"e": 2616,
"s": 2611,
"text": "Misc"
},
{
"code": null,
"e": 2623,
"s": 2616,
"text": "Python"
},
{
"code": null,
"e": 2628,
"s": 2623,
"text": "Misc"
},
{
"code": null,
"e": 2633,
"s": 2628,
"text": "Misc"
},
{
"code": null,
"e": 2731,
"s": 2633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2767,
"s": 2731,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 2799,
"s": 2767,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 2810,
"s": 2799,
"text": "Hypervisor"
},
{
"code": null,
"e": 2826,
"s": 2810,
"text": "Cloud Computing"
},
{
"code": null,
"e": 2855,
"s": 2826,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 2883,
"s": 2855,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2933,
"s": 2883,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2955,
"s": 2933,
"text": "Python map() function"
},
{
"code": null,
"e": 2973,
"s": 2955,
"text": "Python Dictionary"
}
] |
Locally weighted linear Regression using Python
|
27 Jan, 2022
Locally weighted linear regression is the nonparametric regression methods that combine k-nearest neighbor based machine learning. It is referred to as locally weighted because for a query point the function is approximated on the basis of data near that and weighted because the contribution is weighted by its distance from the query point.
Locally Weighted Regression (LWR) is a non-parametric, memory-based algorithm, which means it explicitly retains training data and used it for every time a prediction is made.
To explain the locally weighted linear regression, we first need to understand the linear regression. The linear regression can be explained with the following equations:
Let (xi, yi) be the query point, then for minimizing the cost function in the linear regression:
by calculating so, that it minimize the above cost function.
Our output will be:
Thus, the formula for calculating \theta can also be:
where, beta is the vector of linear vector, X, Y is the matrix, and vector of all observations.
For locally weighted linear regression:
by calculating
so, that it minimize the above cost function.
Our output will be:
Here, w(i) is the weight associated with each observation of training data. It can be calculated by the given formula:
Or this can be represented in the form of a matrix calculation:
Impact of Bandwidth
where x(i) is the observation from the training data and x is a particular point from which the distance is calculated and T(tau) is the bandwidth. Here, T(tau) decides the amount of fitness in the function, if the function is closely fitted, its value will be small. Therefore,
then, we can calculate \theta with the following equation:
For this implementation, we will be using bokeh. If you want to know bokeh functionalities in details please check this article
Python3
# Necessary importsimport numpy as npfrom ipywidgets import interactfrom bokeh.plotting import figure, show, output_notebookfrom bokeh.layouts import gridplot%matplotlib inlineoutput_notebook()plt.style.use('seaborn-dark') # function to perform locally weighted linear regressiondef local_weighted_regression(x0, X, Y, tau): # add bias term x0 = np.r_[1, x0] X = np.c_[np.ones(len(X)), X] # fit model: normal equations with kernel xw = X.T * weights_calculate(x0, X, tau) theta = np.linalg.pinv(xw @ X) @ xw @ Y # "@" is used to # predict value return x0 @ theta # function to perform weight calculationdef weights_calculate(x0, X, tau): return np.exp(np.sum((X - x0) ** 2, axis=1) / (-2 * (tau **2) )) # plot locally weighted regression for different bandwidth valuesdef plot_lwr(tau): # prediction domain = np.linspace(-3, 3, num=300) prediction = [local_regression(x0, X, Y, tau) for x0 in domain] plot = figure(plot_width=400, plot_height=400) plot.title.text = 'tau=%g' % tau plot.scatter(X, Y, alpha=.3) plot.line(domain, prediction, line_width=2, color='red') return plot #define distributionn = 1000 # generate datasetX = np.linspace(-3, 3, num=n)Y = np.abs(X ** 3 - 1) # jitter XX += np.random.normal(scale=.1, size=n) # show the plots for different values of Taushow(gridplot([ [plot_lwr(10.), plot_lwr(1.)], [plot_lwr(0.1), plot_lwr(0.01)]]))
LWR plot with different values of bandwidth
As we can notice from the above plot that with small values of bandwidth, the model fits better but sometimes it will lead to overfitting.
Stanford CS 229
simmytarika5
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 395,
"s": 52,
"text": "Locally weighted linear regression is the nonparametric regression methods that combine k-nearest neighbor based machine learning. It is referred to as locally weighted because for a query point the function is approximated on the basis of data near that and weighted because the contribution is weighted by its distance from the query point."
},
{
"code": null,
"e": 571,
"s": 395,
"text": "Locally Weighted Regression (LWR) is a non-parametric, memory-based algorithm, which means it explicitly retains training data and used it for every time a prediction is made."
},
{
"code": null,
"e": 742,
"s": 571,
"text": "To explain the locally weighted linear regression, we first need to understand the linear regression. The linear regression can be explained with the following equations:"
},
{
"code": null,
"e": 841,
"s": 744,
"text": "Let (xi, yi) be the query point, then for minimizing the cost function in the linear regression:"
},
{
"code": null,
"e": 927,
"s": 841,
"text": "\n\nby calculating so, that it minimize the above cost function.\n\nOur output will be: "
},
{
"code": null,
"e": 981,
"s": 927,
"text": "Thus, the formula for calculating \\theta can also be:"
},
{
"code": null,
"e": 1077,
"s": 981,
"text": "where, beta is the vector of linear vector, X, Y is the matrix, and vector of all observations."
},
{
"code": null,
"e": 1117,
"s": 1077,
"text": "For locally weighted linear regression:"
},
{
"code": null,
"e": 1203,
"s": 1117,
"text": "\n\nby calculating\n\nso, that it minimize the above cost function.\n\nOur output will be: "
},
{
"code": null,
"e": 1322,
"s": 1203,
"text": "Here, w(i) is the weight associated with each observation of training data. It can be calculated by the given formula:"
},
{
"code": null,
"e": 1386,
"s": 1322,
"text": "Or this can be represented in the form of a matrix calculation:"
},
{
"code": null,
"e": 1406,
"s": 1386,
"text": "Impact of Bandwidth"
},
{
"code": null,
"e": 1685,
"s": 1406,
"text": "where x(i) is the observation from the training data and x is a particular point from which the distance is calculated and T(tau) is the bandwidth. Here, T(tau) decides the amount of fitness in the function, if the function is closely fitted, its value will be small. Therefore,"
},
{
"code": null,
"e": 1744,
"s": 1685,
"text": "then, we can calculate \\theta with the following equation:"
},
{
"code": null,
"e": 1872,
"s": 1744,
"text": "For this implementation, we will be using bokeh. If you want to know bokeh functionalities in details please check this article"
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Python3"
},
{
"code": "# Necessary importsimport numpy as npfrom ipywidgets import interactfrom bokeh.plotting import figure, show, output_notebookfrom bokeh.layouts import gridplot%matplotlib inlineoutput_notebook()plt.style.use('seaborn-dark') # function to perform locally weighted linear regressiondef local_weighted_regression(x0, X, Y, tau): # add bias term x0 = np.r_[1, x0] X = np.c_[np.ones(len(X)), X] # fit model: normal equations with kernel xw = X.T * weights_calculate(x0, X, tau) theta = np.linalg.pinv(xw @ X) @ xw @ Y # \"@\" is used to # predict value return x0 @ theta # function to perform weight calculationdef weights_calculate(x0, X, tau): return np.exp(np.sum((X - x0) ** 2, axis=1) / (-2 * (tau **2) )) # plot locally weighted regression for different bandwidth valuesdef plot_lwr(tau): # prediction domain = np.linspace(-3, 3, num=300) prediction = [local_regression(x0, X, Y, tau) for x0 in domain] plot = figure(plot_width=400, plot_height=400) plot.title.text = 'tau=%g' % tau plot.scatter(X, Y, alpha=.3) plot.line(domain, prediction, line_width=2, color='red') return plot #define distributionn = 1000 # generate datasetX = np.linspace(-3, 3, num=n)Y = np.abs(X ** 3 - 1) # jitter XX += np.random.normal(scale=.1, size=n) # show the plots for different values of Taushow(gridplot([ [plot_lwr(10.), plot_lwr(1.)], [plot_lwr(0.1), plot_lwr(0.01)]]))",
"e": 3305,
"s": 1880,
"text": null
},
{
"code": null,
"e": 3349,
"s": 3305,
"text": "LWR plot with different values of bandwidth"
},
{
"code": null,
"e": 3488,
"s": 3349,
"text": "As we can notice from the above plot that with small values of bandwidth, the model fits better but sometimes it will lead to overfitting."
},
{
"code": null,
"e": 3504,
"s": 3488,
"text": "Stanford CS 229"
},
{
"code": null,
"e": 3517,
"s": 3504,
"text": "simmytarika5"
},
{
"code": null,
"e": 3534,
"s": 3517,
"text": "Machine Learning"
},
{
"code": null,
"e": 3551,
"s": 3534,
"text": "Machine Learning"
}
] |
Audio AI: isolating vocals from stereo music using Convolutional Neural Networks | by Ale Koretzky | Towards Data Science
|
What if we could go back to 1965, knock on Abbey Road Studios’ front door holding an ‘All Access’ badge, and have the privilege of listening to those signature Lennon-McCartney harmonies A-Capella? Our input here is a medium quality mp3 of We Can Work it Out by The Beatles. The top track is the input mix and the bottom track, the isolated vocals coming out of our model.
Clip ID: 305275806
Delivery:application/vnd.vimeo.dash+json
Embed Size:692×284
Separate AV:true
Dropped Frames:0 / 0 - 0
Playhead / Buffer:0 / 0 / 0
Bandwidth:0(0 Kbps0 Kbps)
Formally known as Audio Source Separation, the problem we are trying to solve here consists in recovering or reconstructing one or more source signals that, through some -linear or convolutive- process, have been mixed with other signals. The field has many practical applications including but not limited to speech denoising and enhancement, music remixing, spatial audio, remastering, etc. In the context of music production, it is sometimes referred to as unmixing or demixing. There’s a good amount of resources on the subject, going from ICA-based -blind- Source Separation, to semi-supervised Non-negative Matrix Factorization techniques, to more recent neural network-based approaches. For a nice walkthrough on the first two, you can check out these tutorial mini-series from CCRMA, which I found very useful back in the day.
But before jumping into design stuff.. a liiittle bit of Applied Machine Learning philosophy...
As someone who’s been working in signal & image processing for a while and prior to the ‘deep-learning-solves-it-all’ boom, I will introduce the solution as a Feature Engineering journey and show you why, for this particular problem, an artificial neural network ends up being the best approach. Why? Very often I find people writing things like:
“with deep learning you don’t have to worry about feature engineering anymore; it does it for you”
or worst...
“the difference between machine learning and deep learning < let me stop you right there... Deep Learning is still Machine Learning! > is that in ML you do the feature extraction and in deep learning it happens automatically inside the network”.
These generalizations, probably coming from the fact that DNNs can be pretty effective at learning good latent spaces, are just wrong. It frustrates me to see recent grads and practitioners being sold on the above misconceptions and going for the ‘deep-learning-solves-it-all’ approach as something you just throw a bunch of raw data at (yes, even after doing some pre-processing you can still be a sinner :)), and expect things to just work as desired. In the real world, where your data is not as simple, clean and pretty as the MNIST dataset and where you have to care about things like real-time, memory and so on, these misconceptions can leave you stuck in experimentation mode for a very long time...
Feature Engineering not only remains a very important discipline when designing artificial neural networks; in most cases and just like with any other ML technique, it separates production-ready solutions from failing or underperforming experiments. A deep understanding of your data and its domain can still get you very far...
Ok, now that I’m done preaching, let’s get into what you came for! Just like with every other data problem that I’ve worked on in my career, I’ll begin by asking the question “how does the data look like”?. Let’s take a look at the following fragment of singing voice from an original studio recording.
Clip ID: 305288385
Delivery:application/vnd.vimeo.dash+json
Embed Size:692×284
Separate AV:true
Dropped Frames:0 / 0 - 0
Playhead / Buffer:0 / 0 / 0
Bandwidth:0(0 Kbps0 Kbps)
Not too interesting right? Well, this is because we are visualizing the waveform or time-domain signal, where all we have access to are the amplitude values of the signal over time. We could extract things such as envelopes, RMS values, zero-crossing rate, etc, but these features are too primitive and not discriminative enough for helping us solve the problem. If we want to extract vocal content from a mix we should somehow expose the structure of human speech, to begin with. Luckily, the Short-Time Fourier Transform (STFT) comes to the rescue.
Clip ID: 305391461
Delivery:application/vnd.vimeo.dash+json
Embed Size:692×356
Separate AV:true
Dropped Frames:0 / 0 - 0
Playhead / Buffer:0 / 0 / 0
Bandwidth:0(0 Kbps0 Kbps)
Although I love Speech Processing and I would definitely enjoy going through source-filter modeling, cepstrum, quefrencies, LPC, MFCC and so on, I’ll skip all that stuff and focus on the core elements related to our problem, so that the article is digestible by as many people as possible and not exclusively by the Audio Signal Processing / Speech community.
So, what does the structure of human speech tell us?
Well, there are 3 main elements that we can identify here:
A fundamental frequency (f0), determined by the frequency of vibration of our vocal cords. In this case, Ariana is singing in the 300–500 Hz range.
A number of harmonics above f0, following a similar shape or pattern. These harmonics happen at integer multiples of f0.
unvoiced speech, which includes consonants like ‘t’, ‘p’, ‘k’, ‘s’ (which are not produced by the vibration of our vocal cords), breaths, etc. They manifest as short bursts in the high-frequency region.
Let’s forget for a second about this thing called Machine Learning. Based on our knowledge about the data, can we come up with a method to extract our vocals? Let me give it a try...
Naive vocal isolation V1.0:
Identify vocal sections. There’s a lot going on within a mix. We want to focus on the sections that actually contain vocal content and ignore the rest.Distinguish between voiced and unvoiced sections. As we saw, voiced speech looks very different from unvoiced speech, therefore they probably need different treatment.Estimate the frequency of the fundamental over time.Based on the output of 3, apply some sort of mask to capture the harmonic content.Do something else about the unvoiced sections...
Identify vocal sections. There’s a lot going on within a mix. We want to focus on the sections that actually contain vocal content and ignore the rest.
Distinguish between voiced and unvoiced sections. As we saw, voiced speech looks very different from unvoiced speech, therefore they probably need different treatment.
Estimate the frequency of the fundamental over time.
Based on the output of 3, apply some sort of mask to capture the harmonic content.
Do something else about the unvoiced sections...
If we do a decent job, the output of this process should be a soft or binary mask that, when applied (element-wise multiplication) to the magnitude STFT of the mix, gives us an approximate reconstruction of the magnitude STFT of the vocals. From there, we then combine this vocal STFT estimate with the phase information of the original mix, compute an inverse STFT, and obtain the time-domain signal of the reconstructed vocals.
Doing this from scratch is already a lot of work. But for the sake of the demonstration, we’re going to use an implementation of the pYIN algorithm. Even though it’s meant for solving step 3, with the right constraints it takes care of 1 and 2 pretty decently, while tracking the vocal fundamental even in the presence of music. The example below contains the output from this approach, without addressing the unvoiced sections.
Clip ID: 305636014
Delivery:application/vnd.vimeo.dash+json
Embed Size:692×306
Separate AV:true
Dropped Frames:0 / 0 - 0
Playhead / Buffer:0 / 0 / 0
Bandwidth:0(0 Kbps0 Kbps)
Well...? It sort of did the trick but the quality of the recovered vocal is not there yet. Maybe with additional time, energy and budget we can improve this method and get it to a better place.
Now let me ask you...
What happens when you have multiple vocals, which is definitely the case in at least 50% of today’s professionally produced tracks?
What happens when the vocals have been processed with reverberation, delays and other effects? Let’s take a look at the last chorus of Ariana Grande’s One Last Time.
Are you feeling the pain already...? I am.
Very soon, ad-hoc methods like the one described above become a house of cards. The problem is just too complex. There are too many rules, too many exceptions to the rules and too many varying conditions (effects and different mixing settings). The multi-step approach also implies that errors in one step propagate issues to the step that comes after. Improving each step would be very costly, it would require a large number of iterations to get right and last but not least, we would probably end up with a computationally expensive pipeline, something that by itself can be a deal-breaker.
These are the kind of scenarios where we need to start thinking of a more end-to-end approach and let ML figure out -PART- of the underlying processes and operations required to solve the problem. However, we are not throwing the towel when it comes to feature engineering and you’ll see why.
Inspired by the achievements with CNNs on natural images, why not apply the same reasoning here?
At the end of the day, we know we can represent an audio signal ‘as an image’ using the Short-Time Fourier Transform right? Even though these audio images don’t follow the statistical distribution of natural images, they still expose spatial patterns (in the time vs frequency space) that we should be able to learn from.
At the time, validating this experiment was a costly endeavor, because obtaining or generating the training data required was already a big investment. One of the practices I always try to implement in applied research is to first identify a simpler problem that validates the same principles as the original one, but that does not require as much work. This allows you to keep your hypotheses smaller, iterate faster and pivot with minimum impact when things don’t work as expected.
An implied condition for the original solution to work is that a CNN must be capable of understanding the structure of human speech. A simpler problem can then be: given a mix fragment, let’s see if a CNN can classify these fragments as containing vocal content or not. We are looking at a music-robust Vocal Activity Detector (VAD), implemented as a binary classifier.
We know that audio signals such as music and human speech embed temporal dependencies. In simpler terms, nothing happens in isolation at a given time-frame. If I want to know whether a given section of audio contains human speech or not, I should probably look at the neighbor regions as well. That temporal context can give me good information about what’s going on in the region of interest. At the same time, we want to perform our classification in very small time increments, so that we can capture the human voice with the highest temporal resolution possible.
Let’s do some numbers...
Sampling rate (fs): 22050 Hz (we are downsampling from 44100 to 22050)
STFT design: window size = 1024, hop size = 256, Mel scale interpolation for perceptual weighting. Since our input data is real, we can work with one half of the STFT (the why is out of the scope of this post...) while keeping the DC component (not a requirement), giving us 513 frequency bins.
Target classification resolution: a single STFT frame (~11.6 milliseconds = 256 / 22050)
Target temporal context: ~300 milliseconds = 25 STFT frames.
Target number of training examples: 0.5M
Assuming we are using a sliding window with a stride of 1 STFT time-frame to generate our training data, we need around 1.6 hours of labeled audio to generate our 0.5M data samples. [if you’d like to know more details about generating the actual dataset, please feel free to ask in the comments]
With the above requirements, the input/output data to our binary classifier looks like this:
Using Keras, we can build a small CNN model to validate our hypothesis.
import kerasfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2Dfrom keras.optimizers import SGDfrom keras.layers.advanced_activations import LeakyReLUmodel = Sequential()model.add(Conv2D(16, (3,3), padding='same', input_shape=(513, 25, 1)))model.add(LeakyReLU())model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(MaxPooling2D(pool_size=(3,3)))model.add(Dropout(0.25))model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(MaxPooling2D(pool_size=(3,3)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(64))model.add(LeakyReLU())model.add(Dropout(0.5))model.add(Dense(1, activation='sigmoid'))sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)model.compile(loss=keras.losses.binary_crossentropy, optimizer=sgd, metrics=['accuracy'])
With an 80/20 train-test split and after ~50 epochs we reach ~97% test accuracy, which means there’s enough evidence that our CNN model can discriminate between music sections containing vocal content and music sections without vocal content. By inspecting some of the feature maps coming out of our 4th convolutional layer, it looks like our network has optimized its kernels to perform 2 tasks: filtering out music and filtering out vocals...
Now that we’ve validated this simpler classification problem, how do we go from detecting vocal activity in music all the way to isolating vocals from music? Well, rescuing some ideas from our naive method described at the beginning, we still want to somehow end up with an estimate of the vocal’s magnitude spectrogram. This now becomes a regression problem. What we want to do is, given a time-frame from the STFT of the mix (with enough temporal context), estimate the corresponding vocal time-frame’s magnitude spectrum.
What about the training set? (you might be asking yourself at this point)
oh Lord... that was something. I’m gonna address this at the end of the article so that we don’t switch contexts yet!
If our model learns well, during inference, all we need to do is implement a simple sliding window over the STFT of the mix. After each prediction, we move our window to the right by 1 time-frame, predict the next vocal frame and concatenate it with the previous prediction. In regards to the model, we can start by using the same model we used for VAD as a baseline and by making some changes (output shape is now (513,1), linear activation at the output, MSE as loss function), we can begin our training.
Don’t claim victory yet...
Although the above input/output representation makes sense, after training our vocal separation model several times, with varying parameters and data normalizations, the results are not there yet. It seems like we are asking for too much...
We went from a binary classifier to trying to do regression on a 513-dimensional vector. Although the network learns the task to a degree, after reconstructing the vocal’s time domain signal, there are obvious artifacts and interferences from other sources. Even after adding more layers and increasing the number of model parameters, the results don’t change much.
So then the question became: can we trick the network into thinking it is solving a simpler problem and still achieve the desired results?
What if instead of trying to estimate the vocal’s magnitude STFT, we trained the network to learn a binary mask that, when applied to the STFT of the mix, gives us a simplified but perceptually-acceptable-upon-reconstruction estimate of the vocal’s magnitude spectrogram?
By experimenting with different heuristics, we came up with a relatively simple (and definitely unorthodox from a Signal Processing perspective) way to extract singing voice from mixes using binary masks. Without going too much into the details, we are going to think of the output as a binary image where, a value of ‘1’ indicates predominant presence of vocal content at a given frequency and timeframe location, and a value of ‘0’ indicates predominant presence of music at the given location. Visually, it looks pretty unattractive, but upon reconstructing the time domain signal, the results are surprisingly good.
Our problem now becomes some sort of regression-classification hybrid. We are asking the model to “classify pixels” at the output as vocal or non-vocal, although conceptually (and also in terms of the loss function used -MSE- ), the task is still a regression one.
Although the distinction might not seem relevant to some, it actually makes a huge difference in the model’s ability to learn the assigned task, the second one being way more simple and constrained. At the same time, it allows us to keep our model relatively small in terms of number of parameters considering the complexity of the task, something highly desired for real-time operation, which was a design requirement in this case. After some minor tweaks, the final model looks like this.
Basically, as described in the naive method section. In this case, for every inference pass that we do, we are predicting a single timeframe of the vocals’ binary mask. Again, by implementing a simple sliding window with a stride of one timeframe, we keep estimating and concatenating consecutive timeframes, which end up making up the whole vocal binary mask.
As you know, one of the biggest pain points in supervised Machine Learning (leave aside all those toy examples with available datasets out there) is having the right data (amount and quality) for the particular problem that you’re trying to solve. Based on the input/output representations described, in order to train our model, we first needed a significant number of mixes and their corresponding, perfectly aligned and normalized vocal tracks. There’s more than one way to build this dataset and here we used a combination of strategies, ranging from manually creating mix <> vocal pairs with some acapellas found online, to finding RockBand stems, to web-scraping Youtube. Just to give you an idea of what part of this time-consuming and painful process looked like, our “dataset project” involved creating a tool to automatically build mix <> vocal pairs as illustrated below:
We knew we needed a good amount of data for the network to learn the transfer function needed to map mixes into vocals. Our final dataset consisted of around 15M examples of ~300-millisecond fragments of mixes and their corresponding vocal binary masks.
Building a Machine Learning model for a given task is only part of the deal. In production environments, we need to think about software architecture, pipelines, and optimization strategies, especially when we’re dealing with real-time.
For this particular problem the reconstruction into the time-domain can be done all at once after predicting a full vocal binary mask (offline mode) or, more interestingly, as part of a multithreaded pipeline where we acquire, process, reconstruct and playback in small segments, allowing this to be streaming-friendly, and even capable of delivering real-time deconstruction on music that’s being recorded on the fly, with minimum latency. Given this is a whole topic on its own, I’m going to leave it for another article focused on real-time ML pipelines...
This article is extensive enough already but given you’ve made it this far I thought you deserved to see one last demo. With the exact same reasoning for extracting vocal content, we can try to split a stereo track into STEMs (drums, bassline, vocals, others) by making some modifications to our model and of course, by having the appropriate training set :)
Ready to go down the rabbit hole again? Here’s Part 2!
towardsdatascience.com
Thanks for reading and don’t hesitate in leaving questions. I will keep writing articles on Audio AI so stay tuned! As a final remark, you can see that the actual CNN model we ended up building is not that special. The success of this work has been driven by focusing on the Feature Engineering aspect and by implementing a lean process for hypotheses validations, something I’ll be writing about in the near future!
ps: shoutouts to Naveen Rajashekharappa and Karthiek Reddy Bokka for their contributions to this work!
|
[
{
"code": null,
"e": 544,
"s": 171,
"text": "What if we could go back to 1965, knock on Abbey Road Studios’ front door holding an ‘All Access’ badge, and have the privilege of listening to those signature Lennon-McCartney harmonies A-Capella? Our input here is a medium quality mp3 of We Can Work it Out by The Beatles. The top track is the input mix and the bottom track, the isolated vocals coming out of our model."
},
{
"code": null,
"e": 563,
"s": 544,
"text": "Clip ID: 305275806"
},
{
"code": null,
"e": 604,
"s": 563,
"text": "Delivery:application/vnd.vimeo.dash+json"
},
{
"code": null,
"e": 624,
"s": 604,
"text": "Embed Size:692×284 "
},
{
"code": null,
"e": 641,
"s": 624,
"text": "Separate AV:true"
},
{
"code": null,
"e": 666,
"s": 641,
"text": "Dropped Frames:0 / 0 - 0"
},
{
"code": null,
"e": 694,
"s": 666,
"text": "Playhead / Buffer:0 / 0 / 0"
},
{
"code": null,
"e": 720,
"s": 694,
"text": "Bandwidth:0(0 Kbps0 Kbps)"
},
{
"code": null,
"e": 1555,
"s": 720,
"text": "Formally known as Audio Source Separation, the problem we are trying to solve here consists in recovering or reconstructing one or more source signals that, through some -linear or convolutive- process, have been mixed with other signals. The field has many practical applications including but not limited to speech denoising and enhancement, music remixing, spatial audio, remastering, etc. In the context of music production, it is sometimes referred to as unmixing or demixing. There’s a good amount of resources on the subject, going from ICA-based -blind- Source Separation, to semi-supervised Non-negative Matrix Factorization techniques, to more recent neural network-based approaches. For a nice walkthrough on the first two, you can check out these tutorial mini-series from CCRMA, which I found very useful back in the day."
},
{
"code": null,
"e": 1651,
"s": 1555,
"text": "But before jumping into design stuff.. a liiittle bit of Applied Machine Learning philosophy..."
},
{
"code": null,
"e": 1998,
"s": 1651,
"text": "As someone who’s been working in signal & image processing for a while and prior to the ‘deep-learning-solves-it-all’ boom, I will introduce the solution as a Feature Engineering journey and show you why, for this particular problem, an artificial neural network ends up being the best approach. Why? Very often I find people writing things like:"
},
{
"code": null,
"e": 2097,
"s": 1998,
"text": "“with deep learning you don’t have to worry about feature engineering anymore; it does it for you”"
},
{
"code": null,
"e": 2109,
"s": 2097,
"text": "or worst..."
},
{
"code": null,
"e": 2355,
"s": 2109,
"text": "“the difference between machine learning and deep learning < let me stop you right there... Deep Learning is still Machine Learning! > is that in ML you do the feature extraction and in deep learning it happens automatically inside the network”."
},
{
"code": null,
"e": 3063,
"s": 2355,
"text": "These generalizations, probably coming from the fact that DNNs can be pretty effective at learning good latent spaces, are just wrong. It frustrates me to see recent grads and practitioners being sold on the above misconceptions and going for the ‘deep-learning-solves-it-all’ approach as something you just throw a bunch of raw data at (yes, even after doing some pre-processing you can still be a sinner :)), and expect things to just work as desired. In the real world, where your data is not as simple, clean and pretty as the MNIST dataset and where you have to care about things like real-time, memory and so on, these misconceptions can leave you stuck in experimentation mode for a very long time..."
},
{
"code": null,
"e": 3392,
"s": 3063,
"text": "Feature Engineering not only remains a very important discipline when designing artificial neural networks; in most cases and just like with any other ML technique, it separates production-ready solutions from failing or underperforming experiments. A deep understanding of your data and its domain can still get you very far..."
},
{
"code": null,
"e": 3695,
"s": 3392,
"text": "Ok, now that I’m done preaching, let’s get into what you came for! Just like with every other data problem that I’ve worked on in my career, I’ll begin by asking the question “how does the data look like”?. Let’s take a look at the following fragment of singing voice from an original studio recording."
},
{
"code": null,
"e": 3714,
"s": 3695,
"text": "Clip ID: 305288385"
},
{
"code": null,
"e": 3755,
"s": 3714,
"text": "Delivery:application/vnd.vimeo.dash+json"
},
{
"code": null,
"e": 3775,
"s": 3755,
"text": "Embed Size:692×284 "
},
{
"code": null,
"e": 3792,
"s": 3775,
"text": "Separate AV:true"
},
{
"code": null,
"e": 3817,
"s": 3792,
"text": "Dropped Frames:0 / 0 - 0"
},
{
"code": null,
"e": 3845,
"s": 3817,
"text": "Playhead / Buffer:0 / 0 / 0"
},
{
"code": null,
"e": 3871,
"s": 3845,
"text": "Bandwidth:0(0 Kbps0 Kbps)"
},
{
"code": null,
"e": 4422,
"s": 3871,
"text": "Not too interesting right? Well, this is because we are visualizing the waveform or time-domain signal, where all we have access to are the amplitude values of the signal over time. We could extract things such as envelopes, RMS values, zero-crossing rate, etc, but these features are too primitive and not discriminative enough for helping us solve the problem. If we want to extract vocal content from a mix we should somehow expose the structure of human speech, to begin with. Luckily, the Short-Time Fourier Transform (STFT) comes to the rescue."
},
{
"code": null,
"e": 4441,
"s": 4422,
"text": "Clip ID: 305391461"
},
{
"code": null,
"e": 4482,
"s": 4441,
"text": "Delivery:application/vnd.vimeo.dash+json"
},
{
"code": null,
"e": 4502,
"s": 4482,
"text": "Embed Size:692×356 "
},
{
"code": null,
"e": 4519,
"s": 4502,
"text": "Separate AV:true"
},
{
"code": null,
"e": 4544,
"s": 4519,
"text": "Dropped Frames:0 / 0 - 0"
},
{
"code": null,
"e": 4572,
"s": 4544,
"text": "Playhead / Buffer:0 / 0 / 0"
},
{
"code": null,
"e": 4598,
"s": 4572,
"text": "Bandwidth:0(0 Kbps0 Kbps)"
},
{
"code": null,
"e": 4958,
"s": 4598,
"text": "Although I love Speech Processing and I would definitely enjoy going through source-filter modeling, cepstrum, quefrencies, LPC, MFCC and so on, I’ll skip all that stuff and focus on the core elements related to our problem, so that the article is digestible by as many people as possible and not exclusively by the Audio Signal Processing / Speech community."
},
{
"code": null,
"e": 5011,
"s": 4958,
"text": "So, what does the structure of human speech tell us?"
},
{
"code": null,
"e": 5070,
"s": 5011,
"text": "Well, there are 3 main elements that we can identify here:"
},
{
"code": null,
"e": 5218,
"s": 5070,
"text": "A fundamental frequency (f0), determined by the frequency of vibration of our vocal cords. In this case, Ariana is singing in the 300–500 Hz range."
},
{
"code": null,
"e": 5339,
"s": 5218,
"text": "A number of harmonics above f0, following a similar shape or pattern. These harmonics happen at integer multiples of f0."
},
{
"code": null,
"e": 5542,
"s": 5339,
"text": "unvoiced speech, which includes consonants like ‘t’, ‘p’, ‘k’, ‘s’ (which are not produced by the vibration of our vocal cords), breaths, etc. They manifest as short bursts in the high-frequency region."
},
{
"code": null,
"e": 5725,
"s": 5542,
"text": "Let’s forget for a second about this thing called Machine Learning. Based on our knowledge about the data, can we come up with a method to extract our vocals? Let me give it a try..."
},
{
"code": null,
"e": 5753,
"s": 5725,
"text": "Naive vocal isolation V1.0:"
},
{
"code": null,
"e": 6254,
"s": 5753,
"text": "Identify vocal sections. There’s a lot going on within a mix. We want to focus on the sections that actually contain vocal content and ignore the rest.Distinguish between voiced and unvoiced sections. As we saw, voiced speech looks very different from unvoiced speech, therefore they probably need different treatment.Estimate the frequency of the fundamental over time.Based on the output of 3, apply some sort of mask to capture the harmonic content.Do something else about the unvoiced sections..."
},
{
"code": null,
"e": 6406,
"s": 6254,
"text": "Identify vocal sections. There’s a lot going on within a mix. We want to focus on the sections that actually contain vocal content and ignore the rest."
},
{
"code": null,
"e": 6574,
"s": 6406,
"text": "Distinguish between voiced and unvoiced sections. As we saw, voiced speech looks very different from unvoiced speech, therefore they probably need different treatment."
},
{
"code": null,
"e": 6627,
"s": 6574,
"text": "Estimate the frequency of the fundamental over time."
},
{
"code": null,
"e": 6710,
"s": 6627,
"text": "Based on the output of 3, apply some sort of mask to capture the harmonic content."
},
{
"code": null,
"e": 6759,
"s": 6710,
"text": "Do something else about the unvoiced sections..."
},
{
"code": null,
"e": 7189,
"s": 6759,
"text": "If we do a decent job, the output of this process should be a soft or binary mask that, when applied (element-wise multiplication) to the magnitude STFT of the mix, gives us an approximate reconstruction of the magnitude STFT of the vocals. From there, we then combine this vocal STFT estimate with the phase information of the original mix, compute an inverse STFT, and obtain the time-domain signal of the reconstructed vocals."
},
{
"code": null,
"e": 7618,
"s": 7189,
"text": "Doing this from scratch is already a lot of work. But for the sake of the demonstration, we’re going to use an implementation of the pYIN algorithm. Even though it’s meant for solving step 3, with the right constraints it takes care of 1 and 2 pretty decently, while tracking the vocal fundamental even in the presence of music. The example below contains the output from this approach, without addressing the unvoiced sections."
},
{
"code": null,
"e": 7637,
"s": 7618,
"text": "Clip ID: 305636014"
},
{
"code": null,
"e": 7678,
"s": 7637,
"text": "Delivery:application/vnd.vimeo.dash+json"
},
{
"code": null,
"e": 7698,
"s": 7678,
"text": "Embed Size:692×306 "
},
{
"code": null,
"e": 7715,
"s": 7698,
"text": "Separate AV:true"
},
{
"code": null,
"e": 7740,
"s": 7715,
"text": "Dropped Frames:0 / 0 - 0"
},
{
"code": null,
"e": 7768,
"s": 7740,
"text": "Playhead / Buffer:0 / 0 / 0"
},
{
"code": null,
"e": 7794,
"s": 7768,
"text": "Bandwidth:0(0 Kbps0 Kbps)"
},
{
"code": null,
"e": 7988,
"s": 7794,
"text": "Well...? It sort of did the trick but the quality of the recovered vocal is not there yet. Maybe with additional time, energy and budget we can improve this method and get it to a better place."
},
{
"code": null,
"e": 8010,
"s": 7988,
"text": "Now let me ask you..."
},
{
"code": null,
"e": 8142,
"s": 8010,
"text": "What happens when you have multiple vocals, which is definitely the case in at least 50% of today’s professionally produced tracks?"
},
{
"code": null,
"e": 8308,
"s": 8142,
"text": "What happens when the vocals have been processed with reverberation, delays and other effects? Let’s take a look at the last chorus of Ariana Grande’s One Last Time."
},
{
"code": null,
"e": 8351,
"s": 8308,
"text": "Are you feeling the pain already...? I am."
},
{
"code": null,
"e": 8945,
"s": 8351,
"text": "Very soon, ad-hoc methods like the one described above become a house of cards. The problem is just too complex. There are too many rules, too many exceptions to the rules and too many varying conditions (effects and different mixing settings). The multi-step approach also implies that errors in one step propagate issues to the step that comes after. Improving each step would be very costly, it would require a large number of iterations to get right and last but not least, we would probably end up with a computationally expensive pipeline, something that by itself can be a deal-breaker."
},
{
"code": null,
"e": 9238,
"s": 8945,
"text": "These are the kind of scenarios where we need to start thinking of a more end-to-end approach and let ML figure out -PART- of the underlying processes and operations required to solve the problem. However, we are not throwing the towel when it comes to feature engineering and you’ll see why."
},
{
"code": null,
"e": 9335,
"s": 9238,
"text": "Inspired by the achievements with CNNs on natural images, why not apply the same reasoning here?"
},
{
"code": null,
"e": 9657,
"s": 9335,
"text": "At the end of the day, we know we can represent an audio signal ‘as an image’ using the Short-Time Fourier Transform right? Even though these audio images don’t follow the statistical distribution of natural images, they still expose spatial patterns (in the time vs frequency space) that we should be able to learn from."
},
{
"code": null,
"e": 10141,
"s": 9657,
"text": "At the time, validating this experiment was a costly endeavor, because obtaining or generating the training data required was already a big investment. One of the practices I always try to implement in applied research is to first identify a simpler problem that validates the same principles as the original one, but that does not require as much work. This allows you to keep your hypotheses smaller, iterate faster and pivot with minimum impact when things don’t work as expected."
},
{
"code": null,
"e": 10511,
"s": 10141,
"text": "An implied condition for the original solution to work is that a CNN must be capable of understanding the structure of human speech. A simpler problem can then be: given a mix fragment, let’s see if a CNN can classify these fragments as containing vocal content or not. We are looking at a music-robust Vocal Activity Detector (VAD), implemented as a binary classifier."
},
{
"code": null,
"e": 11078,
"s": 10511,
"text": "We know that audio signals such as music and human speech embed temporal dependencies. In simpler terms, nothing happens in isolation at a given time-frame. If I want to know whether a given section of audio contains human speech or not, I should probably look at the neighbor regions as well. That temporal context can give me good information about what’s going on in the region of interest. At the same time, we want to perform our classification in very small time increments, so that we can capture the human voice with the highest temporal resolution possible."
},
{
"code": null,
"e": 11103,
"s": 11078,
"text": "Let’s do some numbers..."
},
{
"code": null,
"e": 11174,
"s": 11103,
"text": "Sampling rate (fs): 22050 Hz (we are downsampling from 44100 to 22050)"
},
{
"code": null,
"e": 11469,
"s": 11174,
"text": "STFT design: window size = 1024, hop size = 256, Mel scale interpolation for perceptual weighting. Since our input data is real, we can work with one half of the STFT (the why is out of the scope of this post...) while keeping the DC component (not a requirement), giving us 513 frequency bins."
},
{
"code": null,
"e": 11558,
"s": 11469,
"text": "Target classification resolution: a single STFT frame (~11.6 milliseconds = 256 / 22050)"
},
{
"code": null,
"e": 11619,
"s": 11558,
"text": "Target temporal context: ~300 milliseconds = 25 STFT frames."
},
{
"code": null,
"e": 11660,
"s": 11619,
"text": "Target number of training examples: 0.5M"
},
{
"code": null,
"e": 11956,
"s": 11660,
"text": "Assuming we are using a sliding window with a stride of 1 STFT time-frame to generate our training data, we need around 1.6 hours of labeled audio to generate our 0.5M data samples. [if you’d like to know more details about generating the actual dataset, please feel free to ask in the comments]"
},
{
"code": null,
"e": 12049,
"s": 11956,
"text": "With the above requirements, the input/output data to our binary classifier looks like this:"
},
{
"code": null,
"e": 12121,
"s": 12049,
"text": "Using Keras, we can build a small CNN model to validate our hypothesis."
},
{
"code": null,
"e": 13039,
"s": 12121,
"text": "import kerasfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2Dfrom keras.optimizers import SGDfrom keras.layers.advanced_activations import LeakyReLUmodel = Sequential()model.add(Conv2D(16, (3,3), padding='same', input_shape=(513, 25, 1)))model.add(LeakyReLU())model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(MaxPooling2D(pool_size=(3,3)))model.add(Dropout(0.25))model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(Conv2D(16, (3,3), padding='same'))model.add(LeakyReLU())model.add(MaxPooling2D(pool_size=(3,3)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(64))model.add(LeakyReLU())model.add(Dropout(0.5))model.add(Dense(1, activation='sigmoid'))sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)model.compile(loss=keras.losses.binary_crossentropy, optimizer=sgd, metrics=['accuracy'])"
},
{
"code": null,
"e": 13484,
"s": 13039,
"text": "With an 80/20 train-test split and after ~50 epochs we reach ~97% test accuracy, which means there’s enough evidence that our CNN model can discriminate between music sections containing vocal content and music sections without vocal content. By inspecting some of the feature maps coming out of our 4th convolutional layer, it looks like our network has optimized its kernels to perform 2 tasks: filtering out music and filtering out vocals..."
},
{
"code": null,
"e": 14009,
"s": 13484,
"text": "Now that we’ve validated this simpler classification problem, how do we go from detecting vocal activity in music all the way to isolating vocals from music? Well, rescuing some ideas from our naive method described at the beginning, we still want to somehow end up with an estimate of the vocal’s magnitude spectrogram. This now becomes a regression problem. What we want to do is, given a time-frame from the STFT of the mix (with enough temporal context), estimate the corresponding vocal time-frame’s magnitude spectrum."
},
{
"code": null,
"e": 14083,
"s": 14009,
"text": "What about the training set? (you might be asking yourself at this point)"
},
{
"code": null,
"e": 14201,
"s": 14083,
"text": "oh Lord... that was something. I’m gonna address this at the end of the article so that we don’t switch contexts yet!"
},
{
"code": null,
"e": 14708,
"s": 14201,
"text": "If our model learns well, during inference, all we need to do is implement a simple sliding window over the STFT of the mix. After each prediction, we move our window to the right by 1 time-frame, predict the next vocal frame and concatenate it with the previous prediction. In regards to the model, we can start by using the same model we used for VAD as a baseline and by making some changes (output shape is now (513,1), linear activation at the output, MSE as loss function), we can begin our training."
},
{
"code": null,
"e": 14735,
"s": 14708,
"text": "Don’t claim victory yet..."
},
{
"code": null,
"e": 14976,
"s": 14735,
"text": "Although the above input/output representation makes sense, after training our vocal separation model several times, with varying parameters and data normalizations, the results are not there yet. It seems like we are asking for too much..."
},
{
"code": null,
"e": 15342,
"s": 14976,
"text": "We went from a binary classifier to trying to do regression on a 513-dimensional vector. Although the network learns the task to a degree, after reconstructing the vocal’s time domain signal, there are obvious artifacts and interferences from other sources. Even after adding more layers and increasing the number of model parameters, the results don’t change much."
},
{
"code": null,
"e": 15481,
"s": 15342,
"text": "So then the question became: can we trick the network into thinking it is solving a simpler problem and still achieve the desired results?"
},
{
"code": null,
"e": 15753,
"s": 15481,
"text": "What if instead of trying to estimate the vocal’s magnitude STFT, we trained the network to learn a binary mask that, when applied to the STFT of the mix, gives us a simplified but perceptually-acceptable-upon-reconstruction estimate of the vocal’s magnitude spectrogram?"
},
{
"code": null,
"e": 16373,
"s": 15753,
"text": "By experimenting with different heuristics, we came up with a relatively simple (and definitely unorthodox from a Signal Processing perspective) way to extract singing voice from mixes using binary masks. Without going too much into the details, we are going to think of the output as a binary image where, a value of ‘1’ indicates predominant presence of vocal content at a given frequency and timeframe location, and a value of ‘0’ indicates predominant presence of music at the given location. Visually, it looks pretty unattractive, but upon reconstructing the time domain signal, the results are surprisingly good."
},
{
"code": null,
"e": 16638,
"s": 16373,
"text": "Our problem now becomes some sort of regression-classification hybrid. We are asking the model to “classify pixels” at the output as vocal or non-vocal, although conceptually (and also in terms of the loss function used -MSE- ), the task is still a regression one."
},
{
"code": null,
"e": 17129,
"s": 16638,
"text": "Although the distinction might not seem relevant to some, it actually makes a huge difference in the model’s ability to learn the assigned task, the second one being way more simple and constrained. At the same time, it allows us to keep our model relatively small in terms of number of parameters considering the complexity of the task, something highly desired for real-time operation, which was a design requirement in this case. After some minor tweaks, the final model looks like this."
},
{
"code": null,
"e": 17490,
"s": 17129,
"text": "Basically, as described in the naive method section. In this case, for every inference pass that we do, we are predicting a single timeframe of the vocals’ binary mask. Again, by implementing a simple sliding window with a stride of one timeframe, we keep estimating and concatenating consecutive timeframes, which end up making up the whole vocal binary mask."
},
{
"code": null,
"e": 18373,
"s": 17490,
"text": "As you know, one of the biggest pain points in supervised Machine Learning (leave aside all those toy examples with available datasets out there) is having the right data (amount and quality) for the particular problem that you’re trying to solve. Based on the input/output representations described, in order to train our model, we first needed a significant number of mixes and their corresponding, perfectly aligned and normalized vocal tracks. There’s more than one way to build this dataset and here we used a combination of strategies, ranging from manually creating mix <> vocal pairs with some acapellas found online, to finding RockBand stems, to web-scraping Youtube. Just to give you an idea of what part of this time-consuming and painful process looked like, our “dataset project” involved creating a tool to automatically build mix <> vocal pairs as illustrated below:"
},
{
"code": null,
"e": 18627,
"s": 18373,
"text": "We knew we needed a good amount of data for the network to learn the transfer function needed to map mixes into vocals. Our final dataset consisted of around 15M examples of ~300-millisecond fragments of mixes and their corresponding vocal binary masks."
},
{
"code": null,
"e": 18864,
"s": 18627,
"text": "Building a Machine Learning model for a given task is only part of the deal. In production environments, we need to think about software architecture, pipelines, and optimization strategies, especially when we’re dealing with real-time."
},
{
"code": null,
"e": 19424,
"s": 18864,
"text": "For this particular problem the reconstruction into the time-domain can be done all at once after predicting a full vocal binary mask (offline mode) or, more interestingly, as part of a multithreaded pipeline where we acquire, process, reconstruct and playback in small segments, allowing this to be streaming-friendly, and even capable of delivering real-time deconstruction on music that’s being recorded on the fly, with minimum latency. Given this is a whole topic on its own, I’m going to leave it for another article focused on real-time ML pipelines..."
},
{
"code": null,
"e": 19783,
"s": 19424,
"text": "This article is extensive enough already but given you’ve made it this far I thought you deserved to see one last demo. With the exact same reasoning for extracting vocal content, we can try to split a stereo track into STEMs (drums, bassline, vocals, others) by making some modifications to our model and of course, by having the appropriate training set :)"
},
{
"code": null,
"e": 19838,
"s": 19783,
"text": "Ready to go down the rabbit hole again? Here’s Part 2!"
},
{
"code": null,
"e": 19861,
"s": 19838,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 20278,
"s": 19861,
"text": "Thanks for reading and don’t hesitate in leaving questions. I will keep writing articles on Audio AI so stay tuned! As a final remark, you can see that the actual CNN model we ended up building is not that special. The success of this work has been driven by focusing on the Feature Engineering aspect and by implementing a lean process for hypotheses validations, something I’ll be writing about in the near future!"
}
] |
How to put a responsive clear button inside HTML input text field ? - GeeksforGeeks
|
03 Aug, 2021
The responsive button inside an input field will clear the text area on the click event. In this article, we will discuss how to put a responsive clear button inside an HTML input field using HTML, CSS, and JavaScript. In order to put the button inside the input field, we shall use CSS. Let us see the HTML first.Creating structure: In this section, we will create the basic structure for the input field.
HTML Code: By using the HTML, we will place the input field where we will add a resposive button to clear the field. We create a text field and a button and we place them inside the same division. In order to fit the button into input text field, the following css is required.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive clear field button</title></head> <body> <h1>GeeksoforGeeks</h1> <b>Responsive clear field button</b> <br><br> <div class="buttonIn"> <input type="text" id="enter"> <button id="clear">clear</button> </div></body> </html>
Designing structure: In this section, we will design the structure to make it attractive or meaningful.
CSS Code: Set the position attribute of parent division to relative. Set the position of the button as absolute inside the division. The above two actions makes it possible for us to shift the button to the top right position of the div which would move the button inside the input field and place it at the right end. To do this, we set top and right margins to 0px, however this value can be varied depending on the design requirement. We put a Z-Index greater than one to position the button at layer above the input field.
CSS
<style> h1 { color: green; } .buttonIn { width: 300px; position: relative; } input { margin: 0px; padding: 0px; width: 100%; outline: none; height: 30px; border-radius: 5px; } button { position: absolute; top: 0; border-radius: 5px; right: 0px; z-index: 2; border: none; top: 2px; height: 30px; cursor: pointer; color: white; background-color: #1e90ff; transform: translateX(2px); } </style>
Responsive structure: In this section, we can use any of the below code sections to make it responsive by using vanilla JavaScript or we can also use jQuery for that. In the two below methods, the basic approach is the same. We listen for the click event on the button and once it is triggered we set the value of the input field to a null string.
JavaScript Code: The javascript code for making the clear button responsive.
javascript
<script> window.addEventListener('load', () => { const button = document.querySelector('#clear'); button.addEventListener('click', () => { document.querySelector('#enter').value = ""; }); }); </script>
jQuery Code:
JQuery
$(document).ready(()=> { alert("nigge") $('#clear').on('click', () => { $('#enter').val(""); }) });
Final solution: In this section, we will combine all the sections together, but have to use CDN links if you want to achieve the task by using the jQuery section.
CDN jQuery link:
<script src=”https://code.jquery.com/jquery-3.4.1.min.js” integrity=”sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=” crossorigin=”anonymous”></script>
Program:
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive clear field button</title> <style> h1 { color: green; } .buttonIn { width: 300px; position: relative; } input { margin: 0px; padding: 0px; width: 100%; outline: none; height: 30px; border-radius: 5px; } button { position: absolute; top: 0; border-radius: 5px; right: 0px; z-index: 2; border: none; top: 2px; height: 30px; cursor: pointer; color: white; background-color: #1e90ff; transform: translateX(2px); } </style></head> <body><center> <h1>GeeksoforGeeks</h1> <b>Responsive clear field button</b> <br> <br> <div class="buttonIn"> <input type="text" id="enter"> <button id="clear">clear</button> </div><center> <script> window.addEventListener('load', () => { const button = document.querySelector('#clear'); button.addEventListener('click', () => { document.querySelector('#enter').value = ""; }); }); </script></body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
sweetyty
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Create a Responsive Navbar using ReactJS
Form validation using jQuery
Making a div vertically scrollable using CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
HTML Cheat Sheet - A Basic Guide to HTML
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
|
[
{
"code": null,
"e": 27329,
"s": 27301,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 27737,
"s": 27329,
"text": "The responsive button inside an input field will clear the text area on the click event. In this article, we will discuss how to put a responsive clear button inside an HTML input field using HTML, CSS, and JavaScript. In order to put the button inside the input field, we shall use CSS. Let us see the HTML first.Creating structure: In this section, we will create the basic structure for the input field. "
},
{
"code": null,
"e": 28016,
"s": 27737,
"text": "HTML Code: By using the HTML, we will place the input field where we will add a resposive button to clear the field. We create a text field and a button and we place them inside the same division. In order to fit the button into input text field, the following css is required. "
},
{
"code": null,
"e": 28021,
"s": 28016,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Responsive clear field button</title></head> <body> <h1>GeeksoforGeeks</h1> <b>Responsive clear field button</b> <br><br> <div class=\"buttonIn\"> <input type=\"text\" id=\"enter\"> <button id=\"clear\">clear</button> </div></body> </html>",
"e": 28444,
"s": 28021,
"text": null
},
{
"code": null,
"e": 28550,
"s": 28444,
"text": "Designing structure: In this section, we will design the structure to make it attractive or meaningful. "
},
{
"code": null,
"e": 29078,
"s": 28550,
"text": "CSS Code: Set the position attribute of parent division to relative. Set the position of the button as absolute inside the division. The above two actions makes it possible for us to shift the button to the top right position of the div which would move the button inside the input field and place it at the right end. To do this, we set top and right margins to 0px, however this value can be varied depending on the design requirement. We put a Z-Index greater than one to position the button at layer above the input field. "
},
{
"code": null,
"e": 29082,
"s": 29078,
"text": "CSS"
},
{
"code": "<style> h1 { color: green; } .buttonIn { width: 300px; position: relative; } input { margin: 0px; padding: 0px; width: 100%; outline: none; height: 30px; border-radius: 5px; } button { position: absolute; top: 0; border-radius: 5px; right: 0px; z-index: 2; border: none; top: 2px; height: 30px; cursor: pointer; color: white; background-color: #1e90ff; transform: translateX(2px); } </style>",
"e": 29668,
"s": 29082,
"text": null
},
{
"code": null,
"e": 30017,
"s": 29668,
"text": "Responsive structure: In this section, we can use any of the below code sections to make it responsive by using vanilla JavaScript or we can also use jQuery for that. In the two below methods, the basic approach is the same. We listen for the click event on the button and once it is triggered we set the value of the input field to a null string. "
},
{
"code": null,
"e": 30096,
"s": 30017,
"text": "JavaScript Code: The javascript code for making the clear button responsive. "
},
{
"code": null,
"e": 30107,
"s": 30096,
"text": "javascript"
},
{
"code": "<script> window.addEventListener('load', () => { const button = document.querySelector('#clear'); button.addEventListener('click', () => { document.querySelector('#enter').value = \"\"; }); }); </script>",
"e": 30347,
"s": 30107,
"text": null
},
{
"code": null,
"e": 30360,
"s": 30347,
"text": "jQuery Code:"
},
{
"code": null,
"e": 30367,
"s": 30360,
"text": "JQuery"
},
{
"code": "$(document).ready(()=> { alert(\"nigge\") $('#clear').on('click', () => { $('#enter').val(\"\"); }) });",
"e": 30540,
"s": 30367,
"text": null
},
{
"code": null,
"e": 30704,
"s": 30540,
"text": "Final solution: In this section, we will combine all the sections together, but have to use CDN links if you want to achieve the task by using the jQuery section. "
},
{
"code": null,
"e": 30723,
"s": 30704,
"text": "CDN jQuery link: "
},
{
"code": null,
"e": 30879,
"s": 30723,
"text": "<script src=”https://code.jquery.com/jquery-3.4.1.min.js” integrity=”sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=” crossorigin=”anonymous”></script>"
},
{
"code": null,
"e": 30892,
"s": 30881,
"text": "Program: "
},
{
"code": null,
"e": 30897,
"s": 30892,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Responsive clear field button</title> <style> h1 { color: green; } .buttonIn { width: 300px; position: relative; } input { margin: 0px; padding: 0px; width: 100%; outline: none; height: 30px; border-radius: 5px; } button { position: absolute; top: 0; border-radius: 5px; right: 0px; z-index: 2; border: none; top: 2px; height: 30px; cursor: pointer; color: white; background-color: #1e90ff; transform: translateX(2px); } </style></head> <body><center> <h1>GeeksoforGeeks</h1> <b>Responsive clear field button</b> <br> <br> <div class=\"buttonIn\"> <input type=\"text\" id=\"enter\"> <button id=\"clear\">clear</button> </div><center> <script> window.addEventListener('load', () => { const button = document.querySelector('#clear'); button.addEventListener('click', () => { document.querySelector('#enter').value = \"\"; }); }); </script></body> </html>",
"e": 32291,
"s": 30897,
"text": null
},
{
"code": null,
"e": 32301,
"s": 32293,
"text": "Output:"
},
{
"code": null,
"e": 32489,
"s": 32303,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 32757,
"s": 32489,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 32766,
"s": 32757,
"text": "sweetyty"
},
{
"code": null,
"e": 32775,
"s": 32766,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32785,
"s": 32775,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32801,
"s": 32785,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 32808,
"s": 32801,
"text": "Picked"
},
{
"code": null,
"e": 32812,
"s": 32808,
"text": "CSS"
},
{
"code": null,
"e": 32817,
"s": 32812,
"text": "HTML"
},
{
"code": null,
"e": 32828,
"s": 32817,
"text": "JavaScript"
},
{
"code": null,
"e": 32835,
"s": 32828,
"text": "JQuery"
},
{
"code": null,
"e": 32852,
"s": 32835,
"text": "Web Technologies"
},
{
"code": null,
"e": 32879,
"s": 32852,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32884,
"s": 32879,
"text": "HTML"
},
{
"code": null,
"e": 32982,
"s": 32884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33019,
"s": 32982,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33058,
"s": 33019,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 33099,
"s": 33058,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 33128,
"s": 33099,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 33173,
"s": 33128,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 33233,
"s": 33173,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33286,
"s": 33233,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 33327,
"s": 33286,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 33388,
"s": 33327,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Array in Python | Set 1 (Introduction and Functions) - GeeksforGeeks
|
22 Jan, 2022
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. The array can be handled in python by a module named “array“. They can be useful when we have to manipulate only specific data type values.
Operations on Array :
1. array(data type, value list):- This function is used to create an array with data type and value list specified in its arguments. Some data types are mentioned in the table below.
2. append():- This function is used to add the value mentioned in its arguments at the end of the array.3. insert(i,x) :- This function is used to add the value(x) at the ith position specified in its argument.
Python3
# Python code to demonstrate the working of# array(), append(), insert() # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3]) # printing original arrayprint ("The new created array is : ",end=" ")for i in range (0, 3): print (arr[i], end=" ") print("\r") # using append() to insert new value at endarr.append(4); # printing appended arrayprint("The appended array is : ", end="")for i in range (0, 4): print (arr[i], end=" ") # using insert() to insert value at specific position# inserts 5 at 2nd positionarr.insert(2, 5) print("\r") # printing array after insertionprint ("The array after insertion is : ", end="")for i in range (0, 5): print (arr[i], end=" ")
Output:
The new created array is : 1 2 3
The appended array is : 1 2 3 4
The array after insertion is : 1 2 5 3 4
4. pop():- This function removes the element at the position mentioned in its argument and returns it.5. remove():- This function is used to remove the first occurrence of the value mentioned in its arguments.
Python3
# Python code to demonstrate the working of# pop() and remove() # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 5]) # printing original arrayprint ("The new created array is : ",end="")for i in range (0,5): print (arr[i],end=" ") print ("\r") # using pop() to remove element at 2nd positionprint ("The popped element is : ",end="")print (arr.pop(2)); # printing array after poppingprint ("The array after popping is : ",end="")for i in range (0,4): print (arr[i],end=" ") print("\r") # using remove() to remove 1st occurrence of 1arr.remove(1) # printing array after removingprint ("The array after removing is : ",end="")for i in range (0,3): print (arr[i],end=" ")
Output:
The new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5
6. index():- This function returns the index of the first occurrence of value mentioned in arguments.7. reverse():- This function reverses the array.
Python3
# Python code to demonstrate the working of# index() and reverse() # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 2, 5]) # printing original arrayprint ("The new created array is : ",end="")for i in range (0,6): print (arr[i],end=" ") print ("\r") # using index() to print index of 1st occurrence of 2print ("The index of 1st occurrence of 2 is : ",end="")print (arr.index(2)) #using reverse() to reverse the arrayarr.reverse() # printing array after reversingprint ("The array after reversing is : ",end="")for i in range (0,6): print (arr[i],end=" ")
Output:
The new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
The array after reversing is : 5 2 1 3 2 1
Reference : https://docs.python.org/3/library/array.html#module-arrayThis article is contributed by Manjeet Singh. 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.
2018umt1750
anikaseth98
amartyaghoshgfg
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python Dictionary
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Interfaces in Java
|
[
{
"code": null,
"e": 25691,
"s": 25663,
"text": "\n22 Jan, 2022"
},
{
"code": null,
"e": 25956,
"s": 25691,
"text": "Other than some generic containers like list, Python in its definition can also handle containers with specified data types. The array can be handled in python by a module named “array“. They can be useful when we have to manipulate only specific data type values."
},
{
"code": null,
"e": 25978,
"s": 25956,
"text": "Operations on Array :"
},
{
"code": null,
"e": 26161,
"s": 25978,
"text": "1. array(data type, value list):- This function is used to create an array with data type and value list specified in its arguments. Some data types are mentioned in the table below."
},
{
"code": null,
"e": 26372,
"s": 26161,
"text": "2. append():- This function is used to add the value mentioned in its arguments at the end of the array.3. insert(i,x) :- This function is used to add the value(x) at the ith position specified in its argument."
},
{
"code": null,
"e": 26380,
"s": 26372,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# array(), append(), insert() # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3]) # printing original arrayprint (\"The new created array is : \",end=\" \")for i in range (0, 3): print (arr[i], end=\" \") print(\"\\r\") # using append() to insert new value at endarr.append(4); # printing appended arrayprint(\"The appended array is : \", end=\"\")for i in range (0, 4): print (arr[i], end=\" \") # using insert() to insert value at specific position# inserts 5 at 2nd positionarr.insert(2, 5) print(\"\\r\") # printing array after insertionprint (\"The array after insertion is : \", end=\"\")for i in range (0, 5): print (arr[i], end=\" \")",
"e": 27170,
"s": 26380,
"text": null
},
{
"code": null,
"e": 27179,
"s": 27170,
"text": "Output: "
},
{
"code": null,
"e": 27288,
"s": 27179,
"text": "The new created array is : 1 2 3 \nThe appended array is : 1 2 3 4 \nThe array after insertion is : 1 2 5 3 4 "
},
{
"code": null,
"e": 27498,
"s": 27288,
"text": "4. pop():- This function removes the element at the position mentioned in its argument and returns it.5. remove():- This function is used to remove the first occurrence of the value mentioned in its arguments."
},
{
"code": null,
"e": 27506,
"s": 27498,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# pop() and remove() # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 5]) # printing original arrayprint (\"The new created array is : \",end=\"\")for i in range (0,5): print (arr[i],end=\" \") print (\"\\r\") # using pop() to remove element at 2nd positionprint (\"The popped element is : \",end=\"\")print (arr.pop(2)); # printing array after poppingprint (\"The array after popping is : \",end=\"\")for i in range (0,4): print (arr[i],end=\" \") print(\"\\r\") # using remove() to remove 1st occurrence of 1arr.remove(1) # printing array after removingprint (\"The array after removing is : \",end=\"\")for i in range (0,3): print (arr[i],end=\" \")",
"e": 28299,
"s": 27506,
"text": null
},
{
"code": null,
"e": 28308,
"s": 28299,
"text": "Output: "
},
{
"code": null,
"e": 28447,
"s": 28308,
"text": "The new created array is : 1 2 3 1 5 \nThe popped element is : 3\nThe array after popping is : 1 2 1 5 \nThe array after removing is : 2 1 5 "
},
{
"code": null,
"e": 28597,
"s": 28447,
"text": "6. index():- This function returns the index of the first occurrence of value mentioned in arguments.7. reverse():- This function reverses the array."
},
{
"code": null,
"e": 28605,
"s": 28597,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# index() and reverse() # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr= array.array('i',[1, 2, 3, 1, 2, 5]) # printing original arrayprint (\"The new created array is : \",end=\"\")for i in range (0,6): print (arr[i],end=\" \") print (\"\\r\") # using index() to print index of 1st occurrence of 2print (\"The index of 1st occurrence of 2 is : \",end=\"\")print (arr.index(2)) #using reverse() to reverse the arrayarr.reverse() # printing array after reversingprint (\"The array after reversing is : \",end=\"\")for i in range (0,6): print (arr[i],end=\" \")",
"e": 29284,
"s": 28605,
"text": null
},
{
"code": null,
"e": 29293,
"s": 29284,
"text": "Output: "
},
{
"code": null,
"e": 29416,
"s": 29293,
"text": "The new created array is : 1 2 3 1 2 5 \nThe index of 1st occurrence of 2 is : 1\nThe array after reversing is : 5 2 1 3 2 1"
},
{
"code": null,
"e": 29907,
"s": 29416,
"text": "Reference : https://docs.python.org/3/library/array.html#module-arrayThis article is contributed by Manjeet Singh. 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. "
},
{
"code": null,
"e": 29919,
"s": 29907,
"text": "2018umt1750"
},
{
"code": null,
"e": 29931,
"s": 29919,
"text": "anikaseth98"
},
{
"code": null,
"e": 29947,
"s": 29931,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 29954,
"s": 29947,
"text": "Python"
},
{
"code": null,
"e": 29973,
"s": 29954,
"text": "School Programming"
},
{
"code": null,
"e": 30071,
"s": 29973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30089,
"s": 30071,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30124,
"s": 30089,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30156,
"s": 30124,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30178,
"s": 30156,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30220,
"s": 30178,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30238,
"s": 30220,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30257,
"s": 30238,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30282,
"s": 30257,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30306,
"s": 30282,
"text": "C++ Classes and Objects"
}
] |
Reshape the Matrix in C++
|
In different platform there is very useful function called 'reshape', that function is used to reshape a matrix into a new one with different size but data will be same. So, if we have a matrix and two values r and c for the row number and column number of the wanted reshaped matrix, respectively.
So, if the input is like [[5,10],[15,20]], row = 1 and col = 4, then the output will be [[5, 10, 15, 20]]
To solve this, we will follow these steps−
Define an array temp
Define an array temp
Define one 2D array res of size (r x c)
Define one 2D array res of size (r x c)
count := 0
count := 0
for initialize i := 0, when i < size of nums, update (increase i by 1), do −for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp
for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −
insert nums[i, j] at the end of temp
insert nums[i, j] at the end of temp
if r * c is not equal to size of nums, then −return nums
if r * c is not equal to size of nums, then −
return nums
return nums
for initialize i := 0, when i < r, update (increase i by 1), do −for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]
for initialize i := 0, when i < r, update (increase i by 1), do −
for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]
for initialize j := 0, when j < c, update (increase j by 1), do −
count = count + 1
count = count + 1
res[i, j] := temp[count]
res[i, j] := temp[count]
return res
return res
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto>> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<int> temp;
vector<vector<int> > res(r, vector<int>(c));
int count = 0;
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < nums[0].size(); j++) {
temp.push_back(nums[i][j]);
}
}
if (r * c != nums.size() * nums[0].size())
return nums;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
res[i][j] = temp[count++];
}
}
return res;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{5,10},{15,20}};
print_vector(ob.matrixReshape(v, 1, 4));
}
{{5,10},{15,20}}, 1, 4
[[5, 10, 15, 20, ],]
|
[
{
"code": null,
"e": 1361,
"s": 1062,
"text": "In different platform there is very useful function called 'reshape', that function is used to reshape a matrix into a new one with different size but data will be same. So, if we have a matrix and two values r and c for the row number and column number of the wanted reshaped matrix, respectively."
},
{
"code": null,
"e": 1467,
"s": 1361,
"text": "So, if the input is like [[5,10],[15,20]], row = 1 and col = 4, then the output will be [[5, 10, 15, 20]]"
},
{
"code": null,
"e": 1510,
"s": 1467,
"text": "To solve this, we will follow these steps−"
},
{
"code": null,
"e": 1531,
"s": 1510,
"text": "Define an array temp"
},
{
"code": null,
"e": 1552,
"s": 1531,
"text": "Define an array temp"
},
{
"code": null,
"e": 1592,
"s": 1552,
"text": "Define one 2D array res of size (r x c)"
},
{
"code": null,
"e": 1632,
"s": 1592,
"text": "Define one 2D array res of size (r x c)"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": "count := 0"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": "count := 0"
},
{
"code": null,
"e": 1846,
"s": 1654,
"text": "for initialize i := 0, when i < size of nums, update (increase i by 1), do −for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp"
},
{
"code": null,
"e": 1923,
"s": 1846,
"text": "for initialize i := 0, when i < size of nums, update (increase i by 1), do −"
},
{
"code": null,
"e": 2039,
"s": 1923,
"text": "for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp"
},
{
"code": null,
"e": 2119,
"s": 2039,
"text": "for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −"
},
{
"code": null,
"e": 2156,
"s": 2119,
"text": "insert nums[i, j] at the end of temp"
},
{
"code": null,
"e": 2193,
"s": 2156,
"text": "insert nums[i, j] at the end of temp"
},
{
"code": null,
"e": 2250,
"s": 2193,
"text": "if r * c is not equal to size of nums, then −return nums"
},
{
"code": null,
"e": 2296,
"s": 2250,
"text": "if r * c is not equal to size of nums, then −"
},
{
"code": null,
"e": 2308,
"s": 2296,
"text": "return nums"
},
{
"code": null,
"e": 2320,
"s": 2308,
"text": "return nums"
},
{
"code": null,
"e": 2492,
"s": 2320,
"text": "for initialize i := 0, when i < r, update (increase i by 1), do −for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]"
},
{
"code": null,
"e": 2558,
"s": 2492,
"text": "for initialize i := 0, when i < r, update (increase i by 1), do −"
},
{
"code": null,
"e": 2665,
"s": 2558,
"text": "for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]"
},
{
"code": null,
"e": 2731,
"s": 2665,
"text": "for initialize j := 0, when j < c, update (increase j by 1), do −"
},
{
"code": null,
"e": 2749,
"s": 2731,
"text": "count = count + 1"
},
{
"code": null,
"e": 2767,
"s": 2749,
"text": "count = count + 1"
},
{
"code": null,
"e": 2792,
"s": 2767,
"text": "res[i, j] := temp[count]"
},
{
"code": null,
"e": 2817,
"s": 2792,
"text": "res[i, j] := temp[count]"
},
{
"code": null,
"e": 2828,
"s": 2817,
"text": "return res"
},
{
"code": null,
"e": 2839,
"s": 2828,
"text": "return res"
},
{
"code": null,
"e": 2909,
"s": 2839,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2920,
"s": 2909,
"text": " Live Demo"
},
{
"code": null,
"e": 3917,
"s": 2920,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<vector<auto>> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] << \", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n vector<int> temp;\n vector<vector<int> > res(r, vector<int>(c));\n int count = 0;\n for (int i = 0; i < nums.size(); i++) {\n for (int j = 0; j < nums[0].size(); j++) {\n temp.push_back(nums[i][j]);\n }\n }\n if (r * c != nums.size() * nums[0].size())\n return nums;\n for (int i = 0; i < r; i++) {\n for (int j = 0; j < c; j++) {\n res[i][j] = temp[count++];\n }\n }\n return res;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{5,10},{15,20}};\n print_vector(ob.matrixReshape(v, 1, 4));\n}"
},
{
"code": null,
"e": 3940,
"s": 3917,
"text": "{{5,10},{15,20}}, 1, 4"
},
{
"code": null,
"e": 3961,
"s": 3940,
"text": "[[5, 10, 15, 20, ],]"
}
] |
C Program to Count ways to reach the n'th stair - GeeksforGeeks
|
05 Nov, 2021
There are n stairs and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top.
Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles Examples:
Input: n = 1
Output: 1
There is only one way to climb 1 stair
Input: n = 2
Output: 2
There are two ways: (1, 1) and (2)
Input: n = 4
Output: 5
There are five ways: (1, 1, 1, 1), (1, 1, 2),
(2, 1, 1), (1, 2, 1), (2, 2)
Method 1: Recursion.Approach: We can easily find the recursive nature in the above problem. The person can reach nth stair from either (n-1)th stair or from (n-2)th stair. Hence, for each stair n, we try to find out the number of ways to reach n-1th stair and n-2th stair and add them to give the answer for the nth stair. Therefore the expression for such an approach comes out to be :
ways(n) = ways(n-1) + ways(n-2)
The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1).
ways(1) = fib(2) = 1
ways(2) = fib(3) = 2
ways(3) = fib(4) = 3
For a better understanding, let’s refer to the recursion tree below -:
Input: N = 4
fib(5)
'3' / \ '2'
/ \
fib(4) fib(3)
'2' / \ '1' / \
/ \ / \
fib(3) fib(2)fib(2) fib(1)
/ \ '1' / \ '0'
'1' / '1'\ / \
/ \ fib(1) fib(0)
fib(2) fib(1)
So we can use the function for Fibonacci numbers to find the value of ways(n). Following is the implementation of the above idea.
CPP
// A C program to count number of// ways to reach n't stair when// a person can climb 1, 2, ..m stairs at a time.#include <stdio.h> // A simple recursive program to find// n'th fibonacci numberint fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} // Returns number of ways to reach s'th stairint countWays(int s){ return fib(s + 1);} // Driver program to test above functionsint main(){ int s = 4; printf("Number of ways = %d", countWays(s)); getchar(); return 0;}
Number of ways = 5
Complexity Analysis:
As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential.It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential.
It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
Generalization of the above problem How to count the number of ways if the person can climb up to m stairs for a given value m. For example, if m is 4, the person can climb 1 stair or 2 stairs or 3 stairs or 4 stairs at a time.Approach: For the generalization of above approach we can use the following recursive relation. We can write the recurrence as following.
ways(n, m) = ways(n-1, m) + ways(n-2, m) +
... + ways(n-m, m)
In this approach to reach a stair-‘n’ we try climbing all possible number of stairs lesser than equal to ‘n’ from present stair.
CPP
// A C program to count number of// ways to reach n't stair when// a person can climb either 1 or 2// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){ if (n <= 1) return n; int res = 0; for (int i = 1; i <= m && i <= n; i++) res += countWaysUtil(n - i, m); return res;} // Returns number of ways to reach s'th stairint countWays(int s, int m){ return countWaysUtil(s + 1, m);} // Driver program to test above functions-int main(){ int s = 4, m = 2; printf("Number of ways = %d", countWays(s, m)); return 0;}
Number of ways = 5
Complexity Analysis:
Time Complexity: O(2^n). As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.
It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
Auxiliary Space: O(1). o use of any data structure for storing values.
Method 2: Dynamic Programming.Approach: This method uses the technique of Dynamic Programming to arrive at the solution.Approach: We create a table res[] in bottom up manner using the following relation:
res[i] = res[i] + res[i-j] for every (i-j) >= 0
such that the ith index of the array will contain the number of ways required to reach the ith step considering all the possibilities of climbing (i.e. from 1 to i).Below code implements the above approach:
CPP
// A C program to count number// of ways to reach n't stair when// a person can climb 1, 2, ..m// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){ int res[n]; res[0] = 1; res[1] = 1; for (int i = 2; i < n; i++) { res[i] = 0; for (int j = 1; j <= m && j <= i; j++) res[i] += res[i - j]; } return res[n - 1];} // Returns number of ways to reach s'th stairint countWays(int s, int m){ return countWaysUtil(s + 1, m);} // Driver program to test above functionsint main(){ int s = 4, m = 2; printf("Number of ways = %d", countWays(s, m)); return 0;}
Number of ways = 5
Complexity Analysis:
Time Complexity: O(m*n). As for each stair we check all possibilities ‘m’ and number of stairs is ‘n’.
Auxiliary Space:O(n). Use of array for storing mid-way values.
Please refer complete article on Count ways to reach the n’th stair for more details!
bidibaaz123
AshokJaiswal
rajeev0719singh
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Lamport's logical clock
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 26370,
"s": 26175,
"text": "There are n stairs and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top. "
},
{
"code": null,
"e": 26528,
"s": 26370,
"text": "Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles Examples: "
},
{
"code": null,
"e": 26749,
"s": 26528,
"text": "Input: n = 1\nOutput: 1\nThere is only one way to climb 1 stair\n\nInput: n = 2\nOutput: 2\nThere are two ways: (1, 1) and (2)\n\nInput: n = 4\nOutput: 5\nThere are five ways: (1, 1, 1, 1), (1, 1, 2), \n(2, 1, 1), (1, 2, 1), (2, 2)"
},
{
"code": null,
"e": 27140,
"s": 26751,
"text": "Method 1: Recursion.Approach: We can easily find the recursive nature in the above problem. The person can reach nth stair from either (n-1)th stair or from (n-2)th stair. Hence, for each stair n, we try to find out the number of ways to reach n-1th stair and n-2th stair and add them to give the answer for the nth stair. Therefore the expression for such an approach comes out to be : "
},
{
"code": null,
"e": 27172,
"s": 27140,
"text": "ways(n) = ways(n-1) + ways(n-2)"
},
{
"code": null,
"e": 27328,
"s": 27172,
"text": "The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1). "
},
{
"code": null,
"e": 27391,
"s": 27328,
"text": "ways(1) = fib(2) = 1\nways(2) = fib(3) = 2\nways(3) = fib(4) = 3"
},
{
"code": null,
"e": 27464,
"s": 27391,
"text": "For a better understanding, let’s refer to the recursion tree below -: "
},
{
"code": null,
"e": 27808,
"s": 27464,
"text": "Input: N = 4\n\n fib(5)\n '3' / \\ '2'\n / \\\n fib(4) fib(3)\n '2' / \\ '1' / \\ \n / \\ / \\ \n fib(3) fib(2)fib(2) fib(1) \n / \\ '1' / \\ '0'\n'1' / '1'\\ / \\ \n / \\ fib(1) fib(0) \nfib(2) fib(1)"
},
{
"code": null,
"e": 27940,
"s": 27808,
"text": "So we can use the function for Fibonacci numbers to find the value of ways(n). Following is the implementation of the above idea. "
},
{
"code": null,
"e": 27944,
"s": 27940,
"text": "CPP"
},
{
"code": "// A C program to count number of// ways to reach n't stair when// a person can climb 1, 2, ..m stairs at a time.#include <stdio.h> // A simple recursive program to find// n'th fibonacci numberint fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} // Returns number of ways to reach s'th stairint countWays(int s){ return fib(s + 1);} // Driver program to test above functionsint main(){ int s = 4; printf(\"Number of ways = %d\", countWays(s)); getchar(); return 0;}",
"e": 28454,
"s": 27944,
"text": null
},
{
"code": null,
"e": 28473,
"s": 28454,
"text": "Number of ways = 5"
},
{
"code": null,
"e": 28498,
"s": 28475,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 28773,
"s": 28498,
"text": "As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential.It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations."
},
{
"code": null,
"e": 28940,
"s": 28773,
"text": "As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential."
},
{
"code": null,
"e": 29049,
"s": 28940,
"text": "It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations."
},
{
"code": null,
"e": 29416,
"s": 29049,
"text": "Generalization of the above problem How to count the number of ways if the person can climb up to m stairs for a given value m. For example, if m is 4, the person can climb 1 stair or 2 stairs or 3 stairs or 4 stairs at a time.Approach: For the generalization of above approach we can use the following recursive relation. We can write the recurrence as following. "
},
{
"code": null,
"e": 29493,
"s": 29416,
"text": "ways(n, m) = ways(n-1, m) + ways(n-2, m) + \n ... + ways(n-m, m) "
},
{
"code": null,
"e": 29624,
"s": 29493,
"text": "In this approach to reach a stair-‘n’ we try climbing all possible number of stairs lesser than equal to ‘n’ from present stair. "
},
{
"code": null,
"e": 29628,
"s": 29624,
"text": "CPP"
},
{
"code": "// A C program to count number of// ways to reach n't stair when// a person can climb either 1 or 2// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){ if (n <= 1) return n; int res = 0; for (int i = 1; i <= m && i <= n; i++) res += countWaysUtil(n - i, m); return res;} // Returns number of ways to reach s'th stairint countWays(int s, int m){ return countWaysUtil(s + 1, m);} // Driver program to test above functions-int main(){ int s = 4, m = 2; printf(\"Number of ways = %d\", countWays(s, m)); return 0;}",
"e": 30234,
"s": 29628,
"text": null
},
{
"code": null,
"e": 30253,
"s": 30234,
"text": "Number of ways = 5"
},
{
"code": null,
"e": 30276,
"s": 30253,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 30576,
"s": 30276,
"text": "Time Complexity: O(2^n). As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner."
},
{
"code": null,
"e": 30851,
"s": 30576,
"text": "As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner."
},
{
"code": null,
"e": 31021,
"s": 30851,
"text": "As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential."
},
{
"code": null,
"e": 31127,
"s": 31021,
"text": "It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner."
},
{
"code": null,
"e": 31200,
"s": 31127,
"text": "Auxiliary Space: O(1). o use of any data structure for storing values. "
},
{
"code": null,
"e": 31406,
"s": 31200,
"text": "Method 2: Dynamic Programming.Approach: This method uses the technique of Dynamic Programming to arrive at the solution.Approach: We create a table res[] in bottom up manner using the following relation: "
},
{
"code": null,
"e": 31454,
"s": 31406,
"text": "res[i] = res[i] + res[i-j] for every (i-j) >= 0"
},
{
"code": null,
"e": 31662,
"s": 31454,
"text": "such that the ith index of the array will contain the number of ways required to reach the ith step considering all the possibilities of climbing (i.e. from 1 to i).Below code implements the above approach: "
},
{
"code": null,
"e": 31666,
"s": 31662,
"text": "CPP"
},
{
"code": "// A C program to count number// of ways to reach n't stair when// a person can climb 1, 2, ..m// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){ int res[n]; res[0] = 1; res[1] = 1; for (int i = 2; i < n; i++) { res[i] = 0; for (int j = 1; j <= m && j <= i; j++) res[i] += res[i - j]; } return res[n - 1];} // Returns number of ways to reach s'th stairint countWays(int s, int m){ return countWaysUtil(s + 1, m);} // Driver program to test above functionsint main(){ int s = 4, m = 2; printf(\"Number of ways = %d\", countWays(s, m)); return 0;}",
"e": 32326,
"s": 31666,
"text": null
},
{
"code": null,
"e": 32345,
"s": 32326,
"text": "Number of ways = 5"
},
{
"code": null,
"e": 32368,
"s": 32345,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32471,
"s": 32368,
"text": "Time Complexity: O(m*n). As for each stair we check all possibilities ‘m’ and number of stairs is ‘n’."
},
{
"code": null,
"e": 32534,
"s": 32471,
"text": "Auxiliary Space:O(n). Use of array for storing mid-way values."
},
{
"code": null,
"e": 32621,
"s": 32534,
"text": "Please refer complete article on Count ways to reach the n’th stair for more details! "
},
{
"code": null,
"e": 32633,
"s": 32621,
"text": "bidibaaz123"
},
{
"code": null,
"e": 32646,
"s": 32633,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 32662,
"s": 32646,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 32673,
"s": 32662,
"text": "C Programs"
},
{
"code": null,
"e": 32771,
"s": 32673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32812,
"s": 32771,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 32843,
"s": 32812,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 32884,
"s": 32843,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 32918,
"s": 32884,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 33008,
"s": 32918,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 33033,
"s": 33008,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 33104,
"s": 33033,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33170,
"s": 33104,
"text": "Create n-child process from same parent process using fork() in C"
},
{
"code": null,
"e": 33217,
"s": 33170,
"text": "Conditional wait and signal in multi-threading"
}
] |
Check whether a number is semiprime or not - GeeksforGeeks
|
09 Apr, 2021
Given a positive integer n. Find whether a number is a semiprime or not. Print True if number is semiprime else False. A semiprime is a natural number that is a product of two prime numbers.Examples :
Input: 6
Output: True
Explanation
6 is a semiprime number as it is a
product of two prime numbers 2 and 3.
Input: 9
Output: True
Input: 8
Output: False
The approach is simple, factorize the given number by dividing it with the divisor of a number to remove the composite number. Meanwhile keep updating the count variable of prime number.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to check whether// number is semiprime or not#include <bits/stdc++.h>using namespace std; // Utility function to check whether// number is semiprime or notint checkSemiprime(int num){ int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0) num /= i, ++cnt; // Increment count // of prime numbers // If number is greater than 1, add it to // the count variable as it indicates the // number remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal to '2' else // return '0' return cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimevoid semiprime(int n){ if (checkSemiprime(n)) cout << "True\n"; else cout << "False\n";} // Driver codeint main(){ int n = 6; semiprime(n); n = 8; semiprime(n); return 0;} // This code is contributed by rutvik_56.
// C Program to check whether// number is semiprime or not#include <stdio.h> // Utility function to check whether// number is semiprime or notint checkSemiprime(int num){ int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0) num /= i, ++cnt; // Increment count // of prime numbers // If number is greater than 1, add it to // the count variable as it indicates the // number remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal to '2' else // return '0' return cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimevoid semiprime(int n){ if (checkSemiprime(n)) printf("True\n"); else printf("False\n");} // Driver codeint main(){ int n = 6; semiprime(n); n = 8; semiprime(n); return 0;}
// Java Program to check whether// number is semiprime or notclass GFG{ // Utility function to check whether // number is semiprime or not static int checkSemiprime(int num) { int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime static void semiprime(int n) { if (checkSemiprime(n) != 0) System.out.printf("True\n"); else System.out.printf("False\n"); } // Driver code public static void main(String[] args) { int n = 6; semiprime(n); n = 8; semiprime(n); }} // This code is contributed by// Smitha Dinesh Semwal
# Python Program to check whether# number is semiprime or notimport math# Utility function to check whether# number is semiprime or notdef checkSemiprime(num): cnt = 0 for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: num /= i cnt += 1 # Increment count # of prime number # If count is greater than 2, # break loop if cnt >= 2: break # If number is greater than 1, add it to # the count variable as it indicates the # number remain is prime number if(num > 1): cnt += 1 # Return '1' if count is equal to '2' else # return '0' return cnt == 2 # Function to print 'True' or 'False'# according to condition of semiprimedef semiprime(n): if checkSemiprime(n) == True: print("True") else: print("False") # Driver coden = 6semiprime(n) n = 8semiprime(n);
// C# Program to check whether// number is semiprime or notusing System;class GFG{ // Utility function to check whether // number is semiprime or not static int checkSemiprime(int num) { int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime static void semiprime(int n) { if (checkSemiprime(n) != 0) Console.WriteLine("True"); else Console.WriteLine("False"); } // Driver code public static void Main() { int n = 6; semiprime(n); n = 8; semiprime(n); }} // This code is contributed by vt_m.
<?php// PHP Program to check whether// number is semiprime or not // Utility function to check whether// number is semiprime or notfunction checkSemiprime($num){ $cnt = 0; for ( $i = 2; $cnt < 2 && $i * $i <= $num; ++$i) while ($num % $i == 0) $num /= $i; // Increment count of // prime numbers ++$cnt; // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if ($num > 1) ++$cnt; // Return '1' if count is // equal to '2' // else return '0' return $cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimefunction semiprime($n){ if (checkSemiprime($n)) echo "True\n"; else echo "False\n";} // Driver code$n = 6;semiprime($n); $n = 8;semiprime($n); // This code is contributed by anuj_67.?>
<script> // JavaScript Program to check whether// number is semiprime or not // Utility function to check whether // number is semiprime or not function checkSemiprime(num) { let cnt = 0; for (let i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime function semiprime(n) { if (checkSemiprime(n) != 0) document.write("True" + "<br/>"); else document.write("False" + "<br/>"); } // Driver code let n = 6; semiprime(n); n = 8; semiprime(n); </script>
Output :
True
False
Time complexity: O() Auxiliary space: O(1)Reference: https://en.wikipedia.org/wiki/Semiprime
vt_m
rutvik_56
splevel62
number-theory
Prime Number
prime-factor
Mathematical
number-theory
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Program to find sum of elements in a given array
Program to print prime numbers from 1 to N.
|
[
{
"code": null,
"e": 26045,
"s": 26017,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 26248,
"s": 26045,
"text": "Given a positive integer n. Find whether a number is a semiprime or not. Print True if number is semiprime else False. A semiprime is a natural number that is a product of two prime numbers.Examples : "
},
{
"code": null,
"e": 26402,
"s": 26248,
"text": "Input: 6\nOutput: True\nExplanation\n6 is a semiprime number as it is a\nproduct of two prime numbers 2 and 3.\n\nInput: 9\nOutput: True\n\nInput: 8\nOutput: False"
},
{
"code": null,
"e": 26593,
"s": 26404,
"text": "The approach is simple, factorize the given number by dividing it with the divisor of a number to remove the composite number. Meanwhile keep updating the count variable of prime number. "
},
{
"code": null,
"e": 26597,
"s": 26593,
"text": "C++"
},
{
"code": null,
"e": 26599,
"s": 26597,
"text": "C"
},
{
"code": null,
"e": 26604,
"s": 26599,
"text": "Java"
},
{
"code": null,
"e": 26612,
"s": 26604,
"text": "Python3"
},
{
"code": null,
"e": 26615,
"s": 26612,
"text": "C#"
},
{
"code": null,
"e": 26619,
"s": 26615,
"text": "PHP"
},
{
"code": null,
"e": 26630,
"s": 26619,
"text": "Javascript"
},
{
"code": "// C++ Program to check whether// number is semiprime or not#include <bits/stdc++.h>using namespace std; // Utility function to check whether// number is semiprime or notint checkSemiprime(int num){ int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0) num /= i, ++cnt; // Increment count // of prime numbers // If number is greater than 1, add it to // the count variable as it indicates the // number remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal to '2' else // return '0' return cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimevoid semiprime(int n){ if (checkSemiprime(n)) cout << \"True\\n\"; else cout << \"False\\n\";} // Driver codeint main(){ int n = 6; semiprime(n); n = 8; semiprime(n); return 0;} // This code is contributed by rutvik_56.",
"e": 27586,
"s": 26630,
"text": null
},
{
"code": "// C Program to check whether// number is semiprime or not#include <stdio.h> // Utility function to check whether// number is semiprime or notint checkSemiprime(int num){ int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0) num /= i, ++cnt; // Increment count // of prime numbers // If number is greater than 1, add it to // the count variable as it indicates the // number remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal to '2' else // return '0' return cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimevoid semiprime(int n){ if (checkSemiprime(n)) printf(\"True\\n\"); else printf(\"False\\n\");} // Driver codeint main(){ int n = 6; semiprime(n); n = 8; semiprime(n); return 0;}",
"e": 28473,
"s": 27586,
"text": null
},
{
"code": "// Java Program to check whether// number is semiprime or notclass GFG{ // Utility function to check whether // number is semiprime or not static int checkSemiprime(int num) { int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime static void semiprime(int n) { if (checkSemiprime(n) != 0) System.out.printf(\"True\\n\"); else System.out.printf(\"False\\n\"); } // Driver code public static void main(String[] args) { int n = 6; semiprime(n); n = 8; semiprime(n); }} // This code is contributed by// Smitha Dinesh Semwal",
"e": 29742,
"s": 28473,
"text": null
},
{
"code": "# Python Program to check whether# number is semiprime or notimport math# Utility function to check whether# number is semiprime or notdef checkSemiprime(num): cnt = 0 for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: num /= i cnt += 1 # Increment count # of prime number # If count is greater than 2, # break loop if cnt >= 2: break # If number is greater than 1, add it to # the count variable as it indicates the # number remain is prime number if(num > 1): cnt += 1 # Return '1' if count is equal to '2' else # return '0' return cnt == 2 # Function to print 'True' or 'False'# according to condition of semiprimedef semiprime(n): if checkSemiprime(n) == True: print(\"True\") else: print(\"False\") # Driver coden = 6semiprime(n) n = 8semiprime(n);",
"e": 30642,
"s": 29742,
"text": null
},
{
"code": "// C# Program to check whether// number is semiprime or notusing System;class GFG{ // Utility function to check whether // number is semiprime or not static int checkSemiprime(int num) { int cnt = 0; for (int i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime static void semiprime(int n) { if (checkSemiprime(n) != 0) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\"); } // Driver code public static void Main() { int n = 6; semiprime(n); n = 8; semiprime(n); }} // This code is contributed by vt_m.",
"e": 31886,
"s": 30642,
"text": null
},
{
"code": "<?php// PHP Program to check whether// number is semiprime or not // Utility function to check whether// number is semiprime or notfunction checkSemiprime($num){ $cnt = 0; for ( $i = 2; $cnt < 2 && $i * $i <= $num; ++$i) while ($num % $i == 0) $num /= $i; // Increment count of // prime numbers ++$cnt; // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if ($num > 1) ++$cnt; // Return '1' if count is // equal to '2' // else return '0' return $cnt == 2;} // Function to print 'True' or 'False'// according to condition of semiprimefunction semiprime($n){ if (checkSemiprime($n)) echo \"True\\n\"; else echo \"False\\n\";} // Driver code$n = 6;semiprime($n); $n = 8;semiprime($n); // This code is contributed by anuj_67.?>",
"e": 32811,
"s": 31886,
"text": null
},
{
"code": "<script> // JavaScript Program to check whether// number is semiprime or not // Utility function to check whether // number is semiprime or not function checkSemiprime(num) { let cnt = 0; for (let i = 2; cnt < 2 && i * i <= num; ++i) while (num % i == 0){ num /= i; // Increment count // of prime numbers ++cnt; } // If number is greater than 1, // add it to the count variable // as it indicates the number // remain is prime number if (num > 1) ++cnt; // Return '1' if count is equal // to '2' else return '0' return cnt == 2 ? 1 : 0; } // Function to print 'True' or 'False' // according to condition of semiprime function semiprime(n) { if (checkSemiprime(n) != 0) document.write(\"True\" + \"<br/>\"); else document.write(\"False\" + \"<br/>\"); } // Driver code let n = 6; semiprime(n); n = 8; semiprime(n); </script>",
"e": 34022,
"s": 32811,
"text": null
},
{
"code": null,
"e": 34032,
"s": 34022,
"text": "Output : "
},
{
"code": null,
"e": 34043,
"s": 34032,
"text": "True\nFalse"
},
{
"code": null,
"e": 34137,
"s": 34043,
"text": "Time complexity: O() Auxiliary space: O(1)Reference: https://en.wikipedia.org/wiki/Semiprime "
},
{
"code": null,
"e": 34142,
"s": 34137,
"text": "vt_m"
},
{
"code": null,
"e": 34152,
"s": 34142,
"text": "rutvik_56"
},
{
"code": null,
"e": 34162,
"s": 34152,
"text": "splevel62"
},
{
"code": null,
"e": 34176,
"s": 34162,
"text": "number-theory"
},
{
"code": null,
"e": 34189,
"s": 34176,
"text": "Prime Number"
},
{
"code": null,
"e": 34202,
"s": 34189,
"text": "prime-factor"
},
{
"code": null,
"e": 34215,
"s": 34202,
"text": "Mathematical"
},
{
"code": null,
"e": 34229,
"s": 34215,
"text": "number-theory"
},
{
"code": null,
"e": 34242,
"s": 34229,
"text": "Mathematical"
},
{
"code": null,
"e": 34255,
"s": 34242,
"text": "Prime Number"
},
{
"code": null,
"e": 34353,
"s": 34255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34377,
"s": 34353,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34420,
"s": 34377,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34434,
"s": 34420,
"text": "Prime Numbers"
},
{
"code": null,
"e": 34507,
"s": 34434,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 34528,
"s": 34507,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34562,
"s": 34528,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34615,
"s": 34562,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 34658,
"s": 34615,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34707,
"s": 34658,
"text": "Program to find sum of elements in a given array"
}
] |
Abstraction in Java - GeeksforGeeks
|
17 Sep, 2021
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
Abstract classes and Abstract methods :
An abstract class is a class that is declared with an abstract keyword.An abstract method is a method that is declared without implementation.An abstract class may or may not have all abstract methods. Some of them can be concrete methodsA method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make the subclass itself abstract.Any class that contains one or more abstract methods must also be declared with an abstract keyword.There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.An abstract class can have parameterized constructors and the default constructor is always present in an abstract class.
An abstract class is a class that is declared with an abstract keyword.
An abstract method is a method that is declared without implementation.
An abstract class may or may not have all abstract methods. Some of them can be concrete methods
A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make the subclass itself abstract.
Any class that contains one or more abstract methods must also be declared with an abstract keyword.
There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
An abstract class can have parameterized constructors and the default constructor is always present in an abstract class.
When to use abstract classes and abstract methods with an example
There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size, and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on — each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes.
Java
// Java program to illustrate the// concept of Abstractionabstract class Shape { String color; // these are abstract methods abstract double area(); public abstract String toString(); // abstract class can have the constructor public Shape(String color) { System.out.println("Shape constructor called"); this.color = color; } // this is a concrete method public String getColor() { return color; }}class Circle extends Shape { double radius; public Circle(String color, double radius) { // calling Shape constructor super(color); System.out.println("Circle constructor called"); this.radius = radius; } @Override double area() { return Math.PI * Math.pow(radius, 2); } @Override public String toString() { return "Circle color is " + super.getColor() + "and area is : " + area(); }}class Rectangle extends Shape { double length; double width; public Rectangle(String color, double length, double width) { // calling Shape constructor super(color); System.out.println("Rectangle constructor called"); this.length = length; this.width = width; } @Override double area() { return length * width; } @Override public String toString() { return "Rectangle color is " + super.getColor() + "and area is : " + area(); }}public class Test { public static void main(String[] args) { Shape s1 = new Circle("Red", 2.2); Shape s2 = new Rectangle("Yellow", 2, 4); System.out.println(s1.toString()); System.out.println(s2.toString()); }}
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
Encapsulation vs Data Abstraction
Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding).While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation.
Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding).
While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation.
Advantages of Abstraction
It reduces the complexity of viewing the things.Avoids code duplication and increases reusability.Helps to increase the security of an application or program as only important details are provided to the user.
It reduces the complexity of viewing the things.
Avoids code duplication and increases reusability.
Helps to increase the security of an application or program as only important details are provided to the user.
Related articles :
Interfaces in java
Abstract classes in java
Difference between abstract class and interface
abstract keyword in java
vaibhav jain 20
gabaa406
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
Java-Abstract Class and Interface
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Reverse a string in Java
Stream In Java
Arrays.sort() in Java with examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Initializing a List in Java
Different ways of Reading a text file in Java
Generics in Java
|
[
{
"code": null,
"e": 29048,
"s": 29020,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 29293,
"s": 29048,
"text": "Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components."
},
{
"code": null,
"e": 29586,
"s": 29293,
"text": "Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects."
},
{
"code": null,
"e": 30003,
"s": 29586,
"text": "Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is. "
},
{
"code": null,
"e": 30122,
"s": 30003,
"text": "In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces."
},
{
"code": null,
"e": 30164,
"s": 30122,
"text": "Abstract classes and Abstract methods : "
},
{
"code": null,
"e": 30897,
"s": 30164,
"text": "An abstract class is a class that is declared with an abstract keyword.An abstract method is a method that is declared without implementation.An abstract class may or may not have all abstract methods. Some of them can be concrete methodsA method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make the subclass itself abstract.Any class that contains one or more abstract methods must also be declared with an abstract keyword.There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.An abstract class can have parameterized constructors and the default constructor is always present in an abstract class."
},
{
"code": null,
"e": 30969,
"s": 30897,
"text": "An abstract class is a class that is declared with an abstract keyword."
},
{
"code": null,
"e": 31041,
"s": 30969,
"text": "An abstract method is a method that is declared without implementation."
},
{
"code": null,
"e": 31138,
"s": 31041,
"text": "An abstract class may or may not have all abstract methods. Some of them can be concrete methods"
},
{
"code": null,
"e": 31285,
"s": 31138,
"text": "A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make the subclass itself abstract."
},
{
"code": null,
"e": 31386,
"s": 31285,
"text": "Any class that contains one or more abstract methods must also be declared with an abstract keyword."
},
{
"code": null,
"e": 31514,
"s": 31386,
"text": "There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator."
},
{
"code": null,
"e": 31636,
"s": 31514,
"text": "An abstract class can have parameterized constructors and the default constructor is always present in an abstract class."
},
{
"code": null,
"e": 31702,
"s": 31636,
"text": "When to use abstract classes and abstract methods with an example"
},
{
"code": null,
"e": 32073,
"s": 31702,
"text": "There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details."
},
{
"code": null,
"e": 32628,
"s": 32073,
"text": "Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size, and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on — each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes. "
},
{
"code": null,
"e": 32633,
"s": 32628,
"text": "Java"
},
{
"code": "// Java program to illustrate the// concept of Abstractionabstract class Shape { String color; // these are abstract methods abstract double area(); public abstract String toString(); // abstract class can have the constructor public Shape(String color) { System.out.println(\"Shape constructor called\"); this.color = color; } // this is a concrete method public String getColor() { return color; }}class Circle extends Shape { double radius; public Circle(String color, double radius) { // calling Shape constructor super(color); System.out.println(\"Circle constructor called\"); this.radius = radius; } @Override double area() { return Math.PI * Math.pow(radius, 2); } @Override public String toString() { return \"Circle color is \" + super.getColor() + \"and area is : \" + area(); }}class Rectangle extends Shape { double length; double width; public Rectangle(String color, double length, double width) { // calling Shape constructor super(color); System.out.println(\"Rectangle constructor called\"); this.length = length; this.width = width; } @Override double area() { return length * width; } @Override public String toString() { return \"Rectangle color is \" + super.getColor() + \"and area is : \" + area(); }}public class Test { public static void main(String[] args) { Shape s1 = new Circle(\"Red\", 2.2); Shape s2 = new Rectangle(\"Yellow\", 2, 4); System.out.println(s1.toString()); System.out.println(s2.toString()); }}",
"e": 34343,
"s": 32633,
"text": null
},
{
"code": null,
"e": 34543,
"s": 34343,
"text": "Shape constructor called\nCircle constructor called\nShape constructor called\nRectangle constructor called\nCircle color is Redand area is : 15.205308443374602\nRectangle color is Yellowand area is : 8.0"
},
{
"code": null,
"e": 34577,
"s": 34543,
"text": "Encapsulation vs Data Abstraction"
},
{
"code": null,
"e": 34867,
"s": 34577,
"text": "Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding).While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation."
},
{
"code": null,
"e": 34977,
"s": 34867,
"text": "Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding)."
},
{
"code": null,
"e": 35158,
"s": 34977,
"text": "While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation."
},
{
"code": null,
"e": 35184,
"s": 35158,
"text": "Advantages of Abstraction"
},
{
"code": null,
"e": 35394,
"s": 35184,
"text": "It reduces the complexity of viewing the things.Avoids code duplication and increases reusability.Helps to increase the security of an application or program as only important details are provided to the user."
},
{
"code": null,
"e": 35443,
"s": 35394,
"text": "It reduces the complexity of viewing the things."
},
{
"code": null,
"e": 35494,
"s": 35443,
"text": "Avoids code duplication and increases reusability."
},
{
"code": null,
"e": 35606,
"s": 35494,
"text": "Helps to increase the security of an application or program as only important details are provided to the user."
},
{
"code": null,
"e": 35627,
"s": 35606,
"text": "Related articles : "
},
{
"code": null,
"e": 35646,
"s": 35627,
"text": "Interfaces in java"
},
{
"code": null,
"e": 35671,
"s": 35646,
"text": "Abstract classes in java"
},
{
"code": null,
"e": 35719,
"s": 35671,
"text": "Difference between abstract class and interface"
},
{
"code": null,
"e": 35744,
"s": 35719,
"text": "abstract keyword in java"
},
{
"code": null,
"e": 35760,
"s": 35744,
"text": "vaibhav jain 20"
},
{
"code": null,
"e": 35769,
"s": 35760,
"text": "gabaa406"
},
{
"code": null,
"e": 35810,
"s": 35769,
"text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g"
},
{
"code": null,
"e": 35844,
"s": 35810,
"text": "Java-Abstract Class and Interface"
},
{
"code": null,
"e": 35865,
"s": 35844,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 35870,
"s": 35865,
"text": "Java"
},
{
"code": null,
"e": 35875,
"s": 35870,
"text": "Java"
},
{
"code": null,
"e": 35973,
"s": 35875,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36017,
"s": 35973,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36042,
"s": 36017,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36057,
"s": 36042,
"text": "Stream In Java"
},
{
"code": null,
"e": 36093,
"s": 36057,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 36124,
"s": 36093,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 36156,
"s": 36124,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 36180,
"s": 36156,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 36208,
"s": 36180,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 36254,
"s": 36208,
"text": "Different ways of Reading a text file in Java"
}
] |
How to check if the clicked element is a div or not in JavaScript ?
|
30 Jan, 2020
Given an HTML document, which contains many elements. The task is to determine whether the clicked element is DIV or not with the help of JavaScript.Two approaches are discussed here, first approach uses the tagName property of element and second uses instanceOf operator to search for DIV.Approach 1:
Use element.tagName property, which returns the tagName of the element.(eg.. if(el.tagName == ‘DIV’) then it is DIV else not)
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Check if an element is a div in JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;" onClick="GFG_Fun(this.tagName)"> GeeksForGeeks </h1> <p id="GFG_UP" onClick="GFG_Fun(this.tagName)"> </p> <div id="div" onClick="GFG_Fun(this.tagName)"> This is Div element. </div> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on any element to check if it's DIV or not."; function GFG_Fun(tagName) { // checking if the tagName is equal to 'DIV'. if (tagName == 'DIV') { down.innerHTML = "It's a DIV Element"; } else { down.innerHTML = "It's not a DIV Element"; } } </script></body> </html>
Output:
Before clicking on element:
After clicking on element:
Approach 2:
Use instanceOf operator, and check whether the element is HTMLDivElement or not.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Check if an element is a div in JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;" onClick="GFG_Fun(this)"> GeeksForGeeks </h1> <p id="GFG_UP" onClick="GFG_Fun(this)"> </p> <div id="div" onClick="GFG_Fun(this)"> This is Div element. </div> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on any element to check if it's DIV or not."; function GFG_Fun(el) { // checking if the el is instance of HTMLDivElement if (el instanceof HTMLDivElement) { down.innerHTML = "It's a DIV Element"; } else { down.innerHTML = "It's not a DIV Element"; } } </script></body> </html>
Output:
Before clicking on element:
After clicking on element:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "Given an HTML document, which contains many elements. The task is to determine whether the clicked element is DIV or not with the help of JavaScript.Two approaches are discussed here, first approach uses the tagName property of element and second uses instanceOf operator to search for DIV.Approach 1:"
},
{
"code": null,
"e": 456,
"s": 330,
"text": "Use element.tagName property, which returns the tagName of the element.(eg.. if(el.tagName == ‘DIV’) then it is DIV else not)"
},
{
"code": null,
"e": 511,
"s": 456,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Check if an element is a div in JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\" onClick=\"GFG_Fun(this.tagName)\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" onClick=\"GFG_Fun(this.tagName)\"> </p> <div id=\"div\" onClick=\"GFG_Fun(this.tagName)\"> This is Div element. </div> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on any element to check if it's DIV or not.\"; function GFG_Fun(tagName) { // checking if the tagName is equal to 'DIV'. if (tagName == 'DIV') { down.innerHTML = \"It's a DIV Element\"; } else { down.innerHTML = \"It's not a DIV Element\"; } } </script></body> </html>",
"e": 1652,
"s": 511,
"text": null
},
{
"code": null,
"e": 1660,
"s": 1652,
"text": "Output:"
},
{
"code": null,
"e": 1688,
"s": 1660,
"text": "Before clicking on element:"
},
{
"code": null,
"e": 1715,
"s": 1688,
"text": "After clicking on element:"
},
{
"code": null,
"e": 1727,
"s": 1715,
"text": "Approach 2:"
},
{
"code": null,
"e": 1808,
"s": 1727,
"text": "Use instanceOf operator, and check whether the element is HTMLDivElement or not."
},
{
"code": null,
"e": 1863,
"s": 1808,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Check if an element is a div in JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\" onClick=\"GFG_Fun(this)\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" onClick=\"GFG_Fun(this)\"> </p> <div id=\"div\" onClick=\"GFG_Fun(this)\"> This is Div element. </div> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on any element to check if it's DIV or not.\"; function GFG_Fun(el) { // checking if the el is instance of HTMLDivElement if (el instanceof HTMLDivElement) { down.innerHTML = \"It's a DIV Element\"; } else { down.innerHTML = \"It's not a DIV Element\"; } } </script></body> </html>",
"e": 2994,
"s": 1863,
"text": null
},
{
"code": null,
"e": 3002,
"s": 2994,
"text": "Output:"
},
{
"code": null,
"e": 3030,
"s": 3002,
"text": "Before clicking on element:"
},
{
"code": null,
"e": 3057,
"s": 3030,
"text": "After clicking on element:"
},
{
"code": null,
"e": 3073,
"s": 3057,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3084,
"s": 3073,
"text": "JavaScript"
},
{
"code": null,
"e": 3101,
"s": 3084,
"text": "Web Technologies"
},
{
"code": null,
"e": 3128,
"s": 3101,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3226,
"s": 3128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3287,
"s": 3226,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3359,
"s": 3287,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3399,
"s": 3359,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3441,
"s": 3399,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3482,
"s": 3441,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3515,
"s": 3482,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3577,
"s": 3515,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3638,
"s": 3577,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3688,
"s": 3638,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Print all Increasing Subsequence of a List
|
20 Dec, 2021
Given a list or array of integer, the task is to print all such subsequences of this list such in which the elements are arranged in increasing order.A Subsequence of the list is an ordered subset of that list’s element having same sequential ordering as the original list. Examples:
Input: arr = {1, 2]} Output: 2 1 1 2Input: arr = {1, 3, 2} Output: 2 3 1 1 2 1 3
Approach:
Here, we will use recursion to find the desired output.
The function will take two lists as an argument and the base condition will be until the list is empty.
At each step of recursion, we will make the decision whether to include or exclude a particular element of the original list.
For achieving this, we will maintain two list namely inp and out, the input and output list of that step.
While including an element in output list, we will check whether that element is greater than the last element in output list, if yes then we will include that element.
When the length of the input list becomes zero then the output list will contain the desired output. This is also a base condition too.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to store all// increasing subsequence of the given list#include<bits/stdc++.h>using namespace std; vector<vector<int>>st; // Method to find increasing subsequencevoid find(vector<int>inp, vector<int>out){ if(inp.size() == 0) { if(out.size() != 0) { // Storing result st.push_back(out); } return; } vector<int>temp; temp.push_back(inp[0]); // Excluding 1st element inp.erase(inp.begin()); find(inp, out); // Including first element // checking the condition // for increasing subsequence if(out.size() == 0) find(inp, temp); else if(temp[0] > out[out.size() - 1]) { out.push_back(temp[0]); find(inp, out); }} // Driver codeint main(){ // Input list vector<int>ls1 = { 1, 3, 2 }; vector<int>ls2; // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.size(); i++) { for(int j = 0; j < st[i].size(); j++) cout << st[i][j] << " "; cout << endl; }} // This code is contributed by Stream_Cipher
// Java implementation to store all// increasing subsequence of the given listimport java.util.*;public class Main{ static Vector<Vector<Integer>> st = new Vector<Vector<Integer>>(); static int[][] add = {{1,2}, {1,3}}; // Method to find increasing subsequence static void find(Vector<Integer> inp, Vector<Integer> Out) { if(inp.size() == 0) { if(Out.size() != 0) { // Storing result st.add(Out); } return; } Vector<Integer> temp = new Vector<Integer>(); temp.add(inp.get(0)); // Excluding 1st element inp.remove(0); find(inp, Out); // Including first element // checking the condition // for increasing subsequence if(Out.size() == 0) find(inp, temp); else if(temp.get(0) > Out.get(Out.size() - 1)) { Out.add(temp.get(0)); find(inp, Out); } } public static void main(String[] args) { // Input list Vector<Integer> ls1 = new Vector<Integer>(); ls1.add(1); ls1.add(3); ls1.add(2); Vector<Integer> ls2 = new Vector<Integer>(); // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.size(); i++) { for(int j = 0; j < st.get(i).size(); j++) System.out.print(st.get(i).get(j) + " "); System.out.println(); } for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) System.out.print(add[i][j] + " "); System.out.println(); } }} // This code is contributed by rameshtravel07.
# Python3 implementation# To store all increasing subsequence of the given listst = [] # Method to find increasing subsequencedef find(inp, out) : if len(inp)== 0 : if len(out) != 0 : # storing result st.append(out) return # excluding 1st element find(inp[1:], out[:]) # including first element # checking the condition # for increasing subsequence if len(out)== 0: find(inp[1:], inp[:1]) elif inp[0] > out[-1] : out.append(inp[0]) find(inp[1:], out[:]) # The input listls1 = [1, 3, 2]ls2 = [] # Calling the functionfind(ls1, ls2) # Printing the listsfor i in st: print(*i)
// C# implementation to store all// increasing subsequence of the given listusing System;using System.Collections.Generic;class GFG { static List<List<int>> st = new List<List<int>>(); static int[,] add = {{1,2}, {1,3}}; // Method to find increasing subsequence static void find(List<int> inp, List<int> Out) { if(inp.Count == 0) { if(Out.Count != 0) { // Storing result st.Add(Out); } return; } List<int> temp = new List<int>(); temp.Add(inp[0]); // Excluding 1st element inp.RemoveAt(0); find(inp, Out); // Including first element // checking the condition // for increasing subsequence if(Out.Count == 0) find(inp, temp); else if(temp[0] > Out[Out.Count - 1]) { Out.Add(temp[0]); find(inp, Out); } } static void Main() { // Input list List<int> ls1 = new List<int>(new int[]{ 1, 3, 2 }); List<int> ls2 = new List<int>(); // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.Count; i++) { for(int j = 0; j < st[i].Count; j++) Console.Write(st[i][j] + " "); Console.WriteLine(); } for(int i = 0; i < add.GetLength(0); i++) { for(int j = 0; j < add.GetLength(1); j++) Console.Write(add[i,j] + " "); Console.WriteLine(); } }} // This code is contributed by suresh07.
<script> // Javascript implementation to store all // increasing subsequence of the given list let st = []; // Method to find increasing subsequence function find(inp, out) { if(inp.length == 0) { if(out.length != 0) { // Storing result st.push(out); } return; } let temp = []; temp.push(inp[0]); // Excluding 1st element inp.shift(); find(inp, out); // Including first element // checking the condition // for increasing subsequence if(out.length == 0) find(inp, temp); else if(temp[0] > out[out.length - 1]) { out.push(temp[0]); find(inp, out); } } // Input list let ls1 = [ 1, 3, 2 ]; let ls2 = []; // Calling the function find(ls1, ls2); st.push([1, 2]); st.push([1, 3]); // Printing the list for(let i = 0; i < st.length; i++) { for(let j = 0; j < st[i].length; j++) document.write(st[i][j] + " "); document.write("</br>"); } // This code is contributed by suresh07.</script>
2
3
1
1 2
1 3
Time Complexity: .
nidhi_biet
Stream_Cipher
suresh07
divyeshrabadiya07
rameshtravel07
subsequence
Arrays
Python Programs
Recursion
Arrays
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Next Greater Element
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
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 340,
"s": 54,
"text": "Given a list or array of integer, the task is to print all such subsequences of this list such in which the elements are arranged in increasing order.A Subsequence of the list is an ordered subset of that list’s element having same sequential ordering as the original list. Examples: "
},
{
"code": null,
"e": 423,
"s": 340,
"text": "Input: arr = {1, 2]} Output: 2 1 1 2Input: arr = {1, 3, 2} Output: 2 3 1 1 2 1 3 "
},
{
"code": null,
"e": 437,
"s": 425,
"text": "Approach: "
},
{
"code": null,
"e": 493,
"s": 437,
"text": "Here, we will use recursion to find the desired output."
},
{
"code": null,
"e": 597,
"s": 493,
"text": "The function will take two lists as an argument and the base condition will be until the list is empty."
},
{
"code": null,
"e": 723,
"s": 597,
"text": "At each step of recursion, we will make the decision whether to include or exclude a particular element of the original list."
},
{
"code": null,
"e": 829,
"s": 723,
"text": "For achieving this, we will maintain two list namely inp and out, the input and output list of that step."
},
{
"code": null,
"e": 998,
"s": 829,
"text": "While including an element in output list, we will check whether that element is greater than the last element in output list, if yes then we will include that element."
},
{
"code": null,
"e": 1134,
"s": 998,
"text": "When the length of the input list becomes zero then the output list will contain the desired output. This is also a base condition too."
},
{
"code": null,
"e": 1187,
"s": 1134,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1191,
"s": 1187,
"text": "C++"
},
{
"code": null,
"e": 1196,
"s": 1191,
"text": "Java"
},
{
"code": null,
"e": 1204,
"s": 1196,
"text": "Python3"
},
{
"code": null,
"e": 1207,
"s": 1204,
"text": "C#"
},
{
"code": null,
"e": 1218,
"s": 1207,
"text": "Javascript"
},
{
"code": "// C++ implementation to store all// increasing subsequence of the given list#include<bits/stdc++.h>using namespace std; vector<vector<int>>st; // Method to find increasing subsequencevoid find(vector<int>inp, vector<int>out){ if(inp.size() == 0) { if(out.size() != 0) { // Storing result st.push_back(out); } return; } vector<int>temp; temp.push_back(inp[0]); // Excluding 1st element inp.erase(inp.begin()); find(inp, out); // Including first element // checking the condition // for increasing subsequence if(out.size() == 0) find(inp, temp); else if(temp[0] > out[out.size() - 1]) { out.push_back(temp[0]); find(inp, out); }} // Driver codeint main(){ // Input list vector<int>ls1 = { 1, 3, 2 }; vector<int>ls2; // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.size(); i++) { for(int j = 0; j < st[i].size(); j++) cout << st[i][j] << \" \"; cout << endl; }} // This code is contributed by Stream_Cipher",
"e": 2390,
"s": 1218,
"text": null
},
{
"code": "// Java implementation to store all// increasing subsequence of the given listimport java.util.*;public class Main{ static Vector<Vector<Integer>> st = new Vector<Vector<Integer>>(); static int[][] add = {{1,2}, {1,3}}; // Method to find increasing subsequence static void find(Vector<Integer> inp, Vector<Integer> Out) { if(inp.size() == 0) { if(Out.size() != 0) { // Storing result st.add(Out); } return; } Vector<Integer> temp = new Vector<Integer>(); temp.add(inp.get(0)); // Excluding 1st element inp.remove(0); find(inp, Out); // Including first element // checking the condition // for increasing subsequence if(Out.size() == 0) find(inp, temp); else if(temp.get(0) > Out.get(Out.size() - 1)) { Out.add(temp.get(0)); find(inp, Out); } } public static void main(String[] args) { // Input list Vector<Integer> ls1 = new Vector<Integer>(); ls1.add(1); ls1.add(3); ls1.add(2); Vector<Integer> ls2 = new Vector<Integer>(); // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.size(); i++) { for(int j = 0; j < st.get(i).size(); j++) System.out.print(st.get(i).get(j) + \" \"); System.out.println(); } for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) System.out.print(add[i][j] + \" \"); System.out.println(); } }} // This code is contributed by rameshtravel07.",
"e": 4199,
"s": 2390,
"text": null
},
{
"code": "# Python3 implementation# To store all increasing subsequence of the given listst = [] # Method to find increasing subsequencedef find(inp, out) : if len(inp)== 0 : if len(out) != 0 : # storing result st.append(out) return # excluding 1st element find(inp[1:], out[:]) # including first element # checking the condition # for increasing subsequence if len(out)== 0: find(inp[1:], inp[:1]) elif inp[0] > out[-1] : out.append(inp[0]) find(inp[1:], out[:]) # The input listls1 = [1, 3, 2]ls2 = [] # Calling the functionfind(ls1, ls2) # Printing the listsfor i in st: print(*i)",
"e": 4859,
"s": 4199,
"text": null
},
{
"code": "// C# implementation to store all// increasing subsequence of the given listusing System;using System.Collections.Generic;class GFG { static List<List<int>> st = new List<List<int>>(); static int[,] add = {{1,2}, {1,3}}; // Method to find increasing subsequence static void find(List<int> inp, List<int> Out) { if(inp.Count == 0) { if(Out.Count != 0) { // Storing result st.Add(Out); } return; } List<int> temp = new List<int>(); temp.Add(inp[0]); // Excluding 1st element inp.RemoveAt(0); find(inp, Out); // Including first element // checking the condition // for increasing subsequence if(Out.Count == 0) find(inp, temp); else if(temp[0] > Out[Out.Count - 1]) { Out.Add(temp[0]); find(inp, Out); } } static void Main() { // Input list List<int> ls1 = new List<int>(new int[]{ 1, 3, 2 }); List<int> ls2 = new List<int>(); // Calling the function find(ls1, ls2); // Printing the list for(int i = 0; i < st.Count; i++) { for(int j = 0; j < st[i].Count; j++) Console.Write(st[i][j] + \" \"); Console.WriteLine(); } for(int i = 0; i < add.GetLength(0); i++) { for(int j = 0; j < add.GetLength(1); j++) Console.Write(add[i,j] + \" \"); Console.WriteLine(); } }} // This code is contributed by suresh07.",
"e": 6481,
"s": 4859,
"text": null
},
{
"code": "<script> // Javascript implementation to store all // increasing subsequence of the given list let st = []; // Method to find increasing subsequence function find(inp, out) { if(inp.length == 0) { if(out.length != 0) { // Storing result st.push(out); } return; } let temp = []; temp.push(inp[0]); // Excluding 1st element inp.shift(); find(inp, out); // Including first element // checking the condition // for increasing subsequence if(out.length == 0) find(inp, temp); else if(temp[0] > out[out.length - 1]) { out.push(temp[0]); find(inp, out); } } // Input list let ls1 = [ 1, 3, 2 ]; let ls2 = []; // Calling the function find(ls1, ls2); st.push([1, 2]); st.push([1, 3]); // Printing the list for(let i = 0; i < st.length; i++) { for(let j = 0; j < st[i].length; j++) document.write(st[i][j] + \" \"); document.write(\"</br>\"); } // This code is contributed by suresh07.</script>",
"e": 7700,
"s": 6481,
"text": null
},
{
"code": null,
"e": 7714,
"s": 7700,
"text": "2\n3\n1\n1 2\n1 3"
},
{
"code": null,
"e": 7736,
"s": 7716,
"text": "Time Complexity: . "
},
{
"code": null,
"e": 7747,
"s": 7736,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7761,
"s": 7747,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 7770,
"s": 7761,
"text": "suresh07"
},
{
"code": null,
"e": 7788,
"s": 7770,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 7803,
"s": 7788,
"text": "rameshtravel07"
},
{
"code": null,
"e": 7815,
"s": 7803,
"text": "subsequence"
},
{
"code": null,
"e": 7822,
"s": 7815,
"text": "Arrays"
},
{
"code": null,
"e": 7838,
"s": 7822,
"text": "Python Programs"
},
{
"code": null,
"e": 7848,
"s": 7838,
"text": "Recursion"
},
{
"code": null,
"e": 7855,
"s": 7848,
"text": "Arrays"
},
{
"code": null,
"e": 7865,
"s": 7855,
"text": "Recursion"
},
{
"code": null,
"e": 7963,
"s": 7865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7995,
"s": 7963,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8020,
"s": 7995,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 8067,
"s": 8020,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 8131,
"s": 8067,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8152,
"s": 8131,
"text": "Next Greater Element"
},
{
"code": null,
"e": 8195,
"s": 8152,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 8217,
"s": 8195,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 8256,
"s": 8217,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 8294,
"s": 8256,
"text": "Python | Convert a list to dictionary"
}
] |
LocalDateTime ofInstant() method in Java with Examples
|
17 May, 2020
ofInstant(Instant instant, ZoneId zone) method of LocalDateTime class in Java is used to create an instance of LocalDateTime using an Instant and zone ID. These two parameters are passed to the method and method returns LocalDateTime on the basis of these two parameters. The calculation of the LocalDateTime follows the following step.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date-time is calculated using the instant and the obtained offset.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.
Finally, the local date-time is calculated using the instant and the obtained offset.
Syntax:
public static LocalDateTime
ofInstant(Instant instant,
ZoneId zone)
Parameters: The method accepts two parameters:
instant – It is of Instant type and represents the instant passed to create localdatetime.
zone – It is of ZoneId type and represents the time-zone used for creating the offset.
Return Value: This method returns the localdate-time.
Exceptions: This method throws DateTimeException if the result exceeds the supported range.
Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:
Program 1:
// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime localdatetime = LocalDateTime.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print full date System.out.println( "Date: " + localdatetime); }}
Date: 2020-05-13T12:40:38.087
Program 2:
// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime localdatetime = LocalDateTime.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print year only System.out.println( "Year: " + localdatetime.getYear()); }}
Year: 2020
References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#ofInstant(java.time.Instant, java.time.ZoneId)
Java-Functions
Java-LocalDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "ofInstant(Instant instant, ZoneId zone) method of LocalDateTime class in Java is used to create an instance of LocalDateTime using an Instant and zone ID. These two parameters are passed to the method and method returns LocalDateTime on the basis of these two parameters. The calculation of the LocalDateTime follows the following step."
},
{
"code": null,
"e": 580,
"s": 365,
"text": "The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date-time is calculated using the instant and the obtained offset."
},
{
"code": null,
"e": 710,
"s": 580,
"text": "The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance."
},
{
"code": null,
"e": 796,
"s": 710,
"text": "Finally, the local date-time is calculated using the instant and the obtained offset."
},
{
"code": null,
"e": 804,
"s": 796,
"text": "Syntax:"
},
{
"code": null,
"e": 898,
"s": 804,
"text": "public static LocalDateTime \n ofInstant(Instant instant,\n ZoneId zone)\n"
},
{
"code": null,
"e": 945,
"s": 898,
"text": "Parameters: The method accepts two parameters:"
},
{
"code": null,
"e": 1036,
"s": 945,
"text": "instant – It is of Instant type and represents the instant passed to create localdatetime."
},
{
"code": null,
"e": 1123,
"s": 1036,
"text": "zone – It is of ZoneId type and represents the time-zone used for creating the offset."
},
{
"code": null,
"e": 1177,
"s": 1123,
"text": "Return Value: This method returns the localdate-time."
},
{
"code": null,
"e": 1269,
"s": 1177,
"text": "Exceptions: This method throws DateTimeException if the result exceeds the supported range."
},
{
"code": null,
"e": 1355,
"s": 1269,
"text": "Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:"
},
{
"code": null,
"e": 1366,
"s": 1355,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime localdatetime = LocalDateTime.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print full date System.out.println( \"Date: \" + localdatetime); }}",
"e": 1859,
"s": 1366,
"text": null
},
{
"code": null,
"e": 1890,
"s": 1859,
"text": "Date: 2020-05-13T12:40:38.087\n"
},
{
"code": null,
"e": 1901,
"s": 1890,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDateTime object LocalDateTime localdatetime = LocalDateTime.ofInstant( Instant.now(), ZoneId.systemDefault()); // Print year only System.out.println( \"Year: \" + localdatetime.getYear()); }}",
"e": 2404,
"s": 1901,
"text": null
},
{
"code": null,
"e": 2416,
"s": 2404,
"text": "Year: 2020\n"
},
{
"code": null,
"e": 2546,
"s": 2416,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#ofInstant(java.time.Instant, java.time.ZoneId)"
},
{
"code": null,
"e": 2561,
"s": 2546,
"text": "Java-Functions"
},
{
"code": null,
"e": 2580,
"s": 2561,
"text": "Java-LocalDateTime"
},
{
"code": null,
"e": 2585,
"s": 2580,
"text": "Java"
},
{
"code": null,
"e": 2590,
"s": 2585,
"text": "Java"
}
] |
Python – color_matrix() function in Wand
|
08 May, 2020
color_matrix() method allows you to recalculate color values by applying a matrix transform. A matrix can be up to a 6×6 grid where each column maps to a color channel to reference, and each row represents a color channel to effect.red, green, blue, n/a, alpha, and a constant (a.k.a offset) describe the corresponding rows and columns.
Syntax :
wand.image.color_matrix(matrix)
Parameters :
Source Image :
Example 1:
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="koala.jpeg") as img: matrix = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] # Recalculate color using color_matrix() method img.color_matrix(matrix) img.save(filename ="cm_koala.jpeg")
Output:
Example 2:
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="koala.jpeg") as img: matrix = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] # Recalculate color using color_matrix() method img.color_matrix(matrix) img.save(filename ="cm_koala2.jpeg")
Output:
Python-wand
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "color_matrix() method allows you to recalculate color values by applying a matrix transform. A matrix can be up to a 6×6 grid where each column maps to a color channel to reference, and each row represents a color channel to effect.red, green, blue, n/a, alpha, and a constant (a.k.a offset) describe the corresponding rows and columns."
},
{
"code": null,
"e": 374,
"s": 365,
"text": "Syntax :"
},
{
"code": null,
"e": 407,
"s": 374,
"text": "wand.image.color_matrix(matrix)\n"
},
{
"code": null,
"e": 420,
"s": 407,
"text": "Parameters :"
},
{
"code": null,
"e": 435,
"s": 420,
"text": "Source Image :"
},
{
"code": null,
"e": 446,
"s": 435,
"text": "Example 1:"
},
{
"code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename =\"koala.jpeg\") as img: matrix = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] # Recalculate color using color_matrix() method img.color_matrix(matrix) img.save(filename =\"cm_koala.jpeg\")",
"e": 779,
"s": 446,
"text": null
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Output:"
},
{
"code": null,
"e": 798,
"s": 787,
"text": "Example 2:"
},
{
"code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename =\"koala.jpeg\") as img: matrix = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] # Recalculate color using color_matrix() method img.color_matrix(matrix) img.save(filename =\"cm_koala2.jpeg\")",
"e": 1132,
"s": 798,
"text": null
},
{
"code": null,
"e": 1140,
"s": 1132,
"text": "Output:"
},
{
"code": null,
"e": 1152,
"s": 1140,
"text": "Python-wand"
},
{
"code": null,
"e": 1159,
"s": 1152,
"text": "Python"
},
{
"code": null,
"e": 1257,
"s": 1159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1289,
"s": 1257,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1316,
"s": 1289,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1337,
"s": 1316,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1360,
"s": 1337,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1391,
"s": 1360,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1447,
"s": 1391,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1489,
"s": 1447,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1531,
"s": 1489,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1570,
"s": 1531,
"text": "Python | Get unique values from a list"
}
] |
Making your own Linux Shell in C
|
07 Jun, 2020
To know more about what a shell is, click here.
We all use the built in terminal window in Linux distributions like Ubuntu, Fedora, etc. But how do they actually work? In this article, We are going to handle some under the hood features and algorithms what actually work inside a shell. All Linux operating systems have a terminal window to write in commands. But how are they executed properly after they are entered?Also, how are extra features like keeping the history of commands and showing help handled? All of this can be understood by creating your own shell.
The Basics
After a command is entered, the following things are done:
Command is entered and if length is non-null, keep it in history.Parsing : Parsing is the breaking up of commands into individual words and stringsChecking for special characters like pipes, etc is doneChecking if built-in commands are asked for.If pipes are present, handling pipes.Executing system commands and libraries by forking a child and calling execvp.Printing current directory name and asking for next input.
Command is entered and if length is non-null, keep it in history.
Parsing : Parsing is the breaking up of commands into individual words and strings
Checking for special characters like pipes, etc is done
Checking if built-in commands are asked for.
If pipes are present, handling pipes.
Executing system commands and libraries by forking a child and calling execvp.
Printing current directory name and asking for next input.
For keeping history of commands, recovering history using arrow keys and handling autocomplete using the tab key, we will be using the readline library provided by GNU.
Implementation
To install the readline library, open the terminal window and write
sudo apt-get install libreadline-dev
It will ask for your password. Enter it. Press y in the next step.
Printing the directory can be done using getcwd.
Getting user name can be done by getenv(“USER”)
Parsing can be done by using strsep(“”). It will separate words based on spaces. Always skip words with zero length to avoid storing of extra spaces.
After parsing, check the list of built-in commands, and if present, execute it. If not, execute it as a system command. To check for built-in commands, store the commands in an array of character pointers, and compare all with strcmp().Note: “cd” does not work natively using execvp, so it is a built-in command, executed with chdir().
For executing a system command, a new child will be created and then by using the execvp, execute the command, and wait until it is finished.
Detecting pipes can also be done by using strsep(“|”).To handle pipes, first separate the first part of the command from the second part. Then after parsing each part, call both parts in two separate new children, using execvp. Piping means passing the output of first command as the input of second command.Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing.Open a pipe using the pipe() function.Create two children.In child 1->Here the output has to be taken into the pipe.
Copy file descriptor 1 to stdout.
Close file descriptor 0.
Execute the first command using execvp()
In child 2->Here the input has to be taken from the pipe.
Copy file descriptor 0 to stdin.
Close file descriptor 1.
Execute the second command using execvp()
Wait for the two children to finish in the parent.
Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing.Open a pipe using the pipe() function.Create two children.In child 1->Here the output has to be taken into the pipe.
Copy file descriptor 1 to stdout.
Close file descriptor 0.
Execute the first command using execvp()
In child 2->Here the input has to be taken from the pipe.
Copy file descriptor 0 to stdin.
Close file descriptor 1.
Execute the second command using execvp()
Wait for the two children to finish in the parent.
Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing.
Open a pipe using the pipe() function.
Create two children.
In child 1->Here the output has to be taken into the pipe.
Copy file descriptor 1 to stdout.
Close file descriptor 0.
Execute the first command using execvp()
Here the output has to be taken into the pipe.
Copy file descriptor 1 to stdout.
Close file descriptor 0.
Execute the first command using execvp()
In child 2->Here the input has to be taken from the pipe.
Copy file descriptor 0 to stdin.
Close file descriptor 1.
Execute the second command using execvp()
Here the input has to be taken from the pipe.
Copy file descriptor 0 to stdin.
Close file descriptor 1.
Execute the second command using execvp()
Wait for the two children to finish in the parent.
// C Program to design a shell in Linux#include<stdio.h>#include<string.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/wait.h>#include<readline/readline.h>#include<readline/history.h> #define MAXCOM 1000 // max number of letters to be supported#define MAXLIST 100 // max number of commands to be supported // Clearing the shell using escape sequences#define clear() printf("\033[H\033[J") // Greeting shell during startupvoid init_shell(){ clear(); printf("\n\n\n\n******************" "************************"); printf("\n\n\n\t****MY SHELL****"); printf("\n\n\t-USE AT YOUR OWN RISK-"); printf("\n\n\n\n*******************" "***********************"); char* username = getenv("USER"); printf("\n\n\nUSER is: @%s", username); printf("\n"); sleep(1); clear();} // Function to take inputint takeInput(char* str){ char* buf; buf = readline("\n>>> "); if (strlen(buf) != 0) { add_history(buf); strcpy(str, buf); return 0; } else { return 1; }} // Function to print Current Directory.void printDir(){ char cwd[1024]; getcwd(cwd, sizeof(cwd)); printf("\nDir: %s", cwd);} // Function where the system command is executedvoid execArgs(char** parsed){ // Forking a child pid_t pid = fork(); if (pid == -1) { printf("\nFailed forking child.."); return; } else if (pid == 0) { if (execvp(parsed[0], parsed) < 0) { printf("\nCould not execute command.."); } exit(0); } else { // waiting for child to terminate wait(NULL); return; }} // Function where the piped system commands is executedvoid execArgsPiped(char** parsed, char** parsedpipe){ // 0 is read end, 1 is write end int pipefd[2]; pid_t p1, p2; if (pipe(pipefd) < 0) { printf("\nPipe could not be initialized"); return; } p1 = fork(); if (p1 < 0) { printf("\nCould not fork"); return; } if (p1 == 0) { // Child 1 executing.. // It only needs to write at the write end close(pipefd[0]); dup2(pipefd[1], STDOUT_FILENO); close(pipefd[1]); if (execvp(parsed[0], parsed) < 0) { printf("\nCould not execute command 1.."); exit(0); } } else { // Parent executing p2 = fork(); if (p2 < 0) { printf("\nCould not fork"); return; } // Child 2 executing.. // It only needs to read at the read end if (p2 == 0) { close(pipefd[1]); dup2(pipefd[0], STDIN_FILENO); close(pipefd[0]); if (execvp(parsedpipe[0], parsedpipe) < 0) { printf("\nCould not execute command 2.."); exit(0); } } else { // parent executing, waiting for two children wait(NULL); wait(NULL); } }} // Help command builtinvoid openHelp(){ puts("\n***WELCOME TO MY SHELL HELP***" "\nCopyright @ Suprotik Dey" "\n-Use the shell at your own risk..." "\nList of Commands supported:" "\n>cd" "\n>ls" "\n>exit" "\n>all other general commands available in UNIX shell" "\n>pipe handling" "\n>improper space handling"); return;} // Function to execute builtin commandsint ownCmdHandler(char** parsed){ int NoOfOwnCmds = 4, i, switchOwnArg = 0; char* ListOfOwnCmds[NoOfOwnCmds]; char* username; ListOfOwnCmds[0] = "exit"; ListOfOwnCmds[1] = "cd"; ListOfOwnCmds[2] = "help"; ListOfOwnCmds[3] = "hello"; for (i = 0; i < NoOfOwnCmds; i++) { if (strcmp(parsed[0], ListOfOwnCmds[i]) == 0) { switchOwnArg = i + 1; break; } } switch (switchOwnArg) { case 1: printf("\nGoodbye\n"); exit(0); case 2: chdir(parsed[1]); return 1; case 3: openHelp(); return 1; case 4: username = getenv("USER"); printf("\nHello %s.\nMind that this is " "not a place to play around." "\nUse help to know more..\n", username); return 1; default: break; } return 0;} // function for finding pipeint parsePipe(char* str, char** strpiped){ int i; for (i = 0; i < 2; i++) { strpiped[i] = strsep(&str, "|"); if (strpiped[i] == NULL) break; } if (strpiped[1] == NULL) return 0; // returns zero if no pipe is found. else { return 1; }} // function for parsing command wordsvoid parseSpace(char* str, char** parsed){ int i; for (i = 0; i < MAXLIST; i++) { parsed[i] = strsep(&str, " "); if (parsed[i] == NULL) break; if (strlen(parsed[i]) == 0) i--; }} int processString(char* str, char** parsed, char** parsedpipe){ char* strpiped[2]; int piped = 0; piped = parsePipe(str, strpiped); if (piped) { parseSpace(strpiped[0], parsed); parseSpace(strpiped[1], parsedpipe); } else { parseSpace(str, parsed); } if (ownCmdHandler(parsed)) return 0; else return 1 + piped;} int main(){ char inputString[MAXCOM], *parsedArgs[MAXLIST]; char* parsedArgsPiped[MAXLIST]; int execFlag = 0; init_shell(); while (1) { // print shell line printDir(); // take input if (takeInput(inputString)) continue; // process execFlag = processString(inputString, parsedArgs, parsedArgsPiped); // execflag returns zero if there is no command // or it is a builtin command, // 1 if it is a simple command // 2 if it is including a pipe. // execute if (execFlag == 1) execArgs(parsedArgs); if (execFlag == 2) execArgsPiped(parsedArgs, parsedArgsPiped); } return 0;}
To Run the code –
gcc shell.c -lreadline
./a.out
Output:
This article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
top_gunn
system-programming
C Language
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
AWK command in Unix/Linux with examples
tar command in Linux with examples
UDP Server-Client implementation in C
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jun, 2020"
},
{
"code": null,
"e": 102,
"s": 54,
"text": "To know more about what a shell is, click here."
},
{
"code": null,
"e": 622,
"s": 102,
"text": "We all use the built in terminal window in Linux distributions like Ubuntu, Fedora, etc. But how do they actually work? In this article, We are going to handle some under the hood features and algorithms what actually work inside a shell. All Linux operating systems have a terminal window to write in commands. But how are they executed properly after they are entered?Also, how are extra features like keeping the history of commands and showing help handled? All of this can be understood by creating your own shell."
},
{
"code": null,
"e": 633,
"s": 622,
"text": "The Basics"
},
{
"code": null,
"e": 692,
"s": 633,
"text": "After a command is entered, the following things are done:"
},
{
"code": null,
"e": 1112,
"s": 692,
"text": "Command is entered and if length is non-null, keep it in history.Parsing : Parsing is the breaking up of commands into individual words and stringsChecking for special characters like pipes, etc is doneChecking if built-in commands are asked for.If pipes are present, handling pipes.Executing system commands and libraries by forking a child and calling execvp.Printing current directory name and asking for next input."
},
{
"code": null,
"e": 1178,
"s": 1112,
"text": "Command is entered and if length is non-null, keep it in history."
},
{
"code": null,
"e": 1261,
"s": 1178,
"text": "Parsing : Parsing is the breaking up of commands into individual words and strings"
},
{
"code": null,
"e": 1317,
"s": 1261,
"text": "Checking for special characters like pipes, etc is done"
},
{
"code": null,
"e": 1362,
"s": 1317,
"text": "Checking if built-in commands are asked for."
},
{
"code": null,
"e": 1400,
"s": 1362,
"text": "If pipes are present, handling pipes."
},
{
"code": null,
"e": 1479,
"s": 1400,
"text": "Executing system commands and libraries by forking a child and calling execvp."
},
{
"code": null,
"e": 1538,
"s": 1479,
"text": "Printing current directory name and asking for next input."
},
{
"code": null,
"e": 1707,
"s": 1538,
"text": "For keeping history of commands, recovering history using arrow keys and handling autocomplete using the tab key, we will be using the readline library provided by GNU."
},
{
"code": null,
"e": 1722,
"s": 1707,
"text": "Implementation"
},
{
"code": null,
"e": 1790,
"s": 1722,
"text": "To install the readline library, open the terminal window and write"
},
{
"code": null,
"e": 1827,
"s": 1790,
"text": "sudo apt-get install libreadline-dev"
},
{
"code": null,
"e": 1894,
"s": 1827,
"text": "It will ask for your password. Enter it. Press y in the next step."
},
{
"code": null,
"e": 1943,
"s": 1894,
"text": "Printing the directory can be done using getcwd."
},
{
"code": null,
"e": 1991,
"s": 1943,
"text": "Getting user name can be done by getenv(“USER”)"
},
{
"code": null,
"e": 2141,
"s": 1991,
"text": "Parsing can be done by using strsep(“”). It will separate words based on spaces. Always skip words with zero length to avoid storing of extra spaces."
},
{
"code": null,
"e": 2477,
"s": 2141,
"text": "After parsing, check the list of built-in commands, and if present, execute it. If not, execute it as a system command. To check for built-in commands, store the commands in an array of character pointers, and compare all with strcmp().Note: “cd” does not work natively using execvp, so it is a built-in command, executed with chdir()."
},
{
"code": null,
"e": 2619,
"s": 2477,
"text": "For executing a system command, a new child will be created and then by using the execvp, execute the command, and wait until it is finished."
},
{
"code": null,
"e": 3473,
"s": 2619,
"text": "Detecting pipes can also be done by using strsep(“|”).To handle pipes, first separate the first part of the command from the second part. Then after parsing each part, call both parts in two separate new children, using execvp. Piping means passing the output of first command as the input of second command.Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing.Open a pipe using the pipe() function.Create two children.In child 1->Here the output has to be taken into the pipe.\nCopy file descriptor 1 to stdout.\nClose file descriptor 0.\nExecute the first command using execvp()\nIn child 2->Here the input has to be taken from the pipe.\nCopy file descriptor 0 to stdin.\nClose file descriptor 1.\nExecute the second command using execvp()\nWait for the two children to finish in the parent."
},
{
"code": null,
"e": 4019,
"s": 3473,
"text": "Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing.Open a pipe using the pipe() function.Create two children.In child 1->Here the output has to be taken into the pipe.\nCopy file descriptor 1 to stdout.\nClose file descriptor 0.\nExecute the first command using execvp()\nIn child 2->Here the input has to be taken from the pipe.\nCopy file descriptor 0 to stdin.\nClose file descriptor 1.\nExecute the second command using execvp()\nWait for the two children to finish in the parent."
},
{
"code": null,
"e": 4139,
"s": 4019,
"text": "Declare an integer array of size 2 for storing file descriptors. File descriptor 0 is for reading and 1 is for writing."
},
{
"code": null,
"e": 4178,
"s": 4139,
"text": "Open a pipe using the pipe() function."
},
{
"code": null,
"e": 4199,
"s": 4178,
"text": "Create two children."
},
{
"code": null,
"e": 4360,
"s": 4199,
"text": "In child 1->Here the output has to be taken into the pipe.\nCopy file descriptor 1 to stdout.\nClose file descriptor 0.\nExecute the first command using execvp()\n"
},
{
"code": null,
"e": 4509,
"s": 4360,
"text": "Here the output has to be taken into the pipe.\nCopy file descriptor 1 to stdout.\nClose file descriptor 0.\nExecute the first command using execvp()\n"
},
{
"code": null,
"e": 4668,
"s": 4509,
"text": "In child 2->Here the input has to be taken from the pipe.\nCopy file descriptor 0 to stdin.\nClose file descriptor 1.\nExecute the second command using execvp()\n"
},
{
"code": null,
"e": 4815,
"s": 4668,
"text": "Here the input has to be taken from the pipe.\nCopy file descriptor 0 to stdin.\nClose file descriptor 1.\nExecute the second command using execvp()\n"
},
{
"code": null,
"e": 4866,
"s": 4815,
"text": "Wait for the two children to finish in the parent."
},
{
"code": "// C Program to design a shell in Linux#include<stdio.h>#include<string.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/wait.h>#include<readline/readline.h>#include<readline/history.h> #define MAXCOM 1000 // max number of letters to be supported#define MAXLIST 100 // max number of commands to be supported // Clearing the shell using escape sequences#define clear() printf(\"\\033[H\\033[J\") // Greeting shell during startupvoid init_shell(){ clear(); printf(\"\\n\\n\\n\\n******************\" \"************************\"); printf(\"\\n\\n\\n\\t****MY SHELL****\"); printf(\"\\n\\n\\t-USE AT YOUR OWN RISK-\"); printf(\"\\n\\n\\n\\n*******************\" \"***********************\"); char* username = getenv(\"USER\"); printf(\"\\n\\n\\nUSER is: @%s\", username); printf(\"\\n\"); sleep(1); clear();} // Function to take inputint takeInput(char* str){ char* buf; buf = readline(\"\\n>>> \"); if (strlen(buf) != 0) { add_history(buf); strcpy(str, buf); return 0; } else { return 1; }} // Function to print Current Directory.void printDir(){ char cwd[1024]; getcwd(cwd, sizeof(cwd)); printf(\"\\nDir: %s\", cwd);} // Function where the system command is executedvoid execArgs(char** parsed){ // Forking a child pid_t pid = fork(); if (pid == -1) { printf(\"\\nFailed forking child..\"); return; } else if (pid == 0) { if (execvp(parsed[0], parsed) < 0) { printf(\"\\nCould not execute command..\"); } exit(0); } else { // waiting for child to terminate wait(NULL); return; }} // Function where the piped system commands is executedvoid execArgsPiped(char** parsed, char** parsedpipe){ // 0 is read end, 1 is write end int pipefd[2]; pid_t p1, p2; if (pipe(pipefd) < 0) { printf(\"\\nPipe could not be initialized\"); return; } p1 = fork(); if (p1 < 0) { printf(\"\\nCould not fork\"); return; } if (p1 == 0) { // Child 1 executing.. // It only needs to write at the write end close(pipefd[0]); dup2(pipefd[1], STDOUT_FILENO); close(pipefd[1]); if (execvp(parsed[0], parsed) < 0) { printf(\"\\nCould not execute command 1..\"); exit(0); } } else { // Parent executing p2 = fork(); if (p2 < 0) { printf(\"\\nCould not fork\"); return; } // Child 2 executing.. // It only needs to read at the read end if (p2 == 0) { close(pipefd[1]); dup2(pipefd[0], STDIN_FILENO); close(pipefd[0]); if (execvp(parsedpipe[0], parsedpipe) < 0) { printf(\"\\nCould not execute command 2..\"); exit(0); } } else { // parent executing, waiting for two children wait(NULL); wait(NULL); } }} // Help command builtinvoid openHelp(){ puts(\"\\n***WELCOME TO MY SHELL HELP***\" \"\\nCopyright @ Suprotik Dey\" \"\\n-Use the shell at your own risk...\" \"\\nList of Commands supported:\" \"\\n>cd\" \"\\n>ls\" \"\\n>exit\" \"\\n>all other general commands available in UNIX shell\" \"\\n>pipe handling\" \"\\n>improper space handling\"); return;} // Function to execute builtin commandsint ownCmdHandler(char** parsed){ int NoOfOwnCmds = 4, i, switchOwnArg = 0; char* ListOfOwnCmds[NoOfOwnCmds]; char* username; ListOfOwnCmds[0] = \"exit\"; ListOfOwnCmds[1] = \"cd\"; ListOfOwnCmds[2] = \"help\"; ListOfOwnCmds[3] = \"hello\"; for (i = 0; i < NoOfOwnCmds; i++) { if (strcmp(parsed[0], ListOfOwnCmds[i]) == 0) { switchOwnArg = i + 1; break; } } switch (switchOwnArg) { case 1: printf(\"\\nGoodbye\\n\"); exit(0); case 2: chdir(parsed[1]); return 1; case 3: openHelp(); return 1; case 4: username = getenv(\"USER\"); printf(\"\\nHello %s.\\nMind that this is \" \"not a place to play around.\" \"\\nUse help to know more..\\n\", username); return 1; default: break; } return 0;} // function for finding pipeint parsePipe(char* str, char** strpiped){ int i; for (i = 0; i < 2; i++) { strpiped[i] = strsep(&str, \"|\"); if (strpiped[i] == NULL) break; } if (strpiped[1] == NULL) return 0; // returns zero if no pipe is found. else { return 1; }} // function for parsing command wordsvoid parseSpace(char* str, char** parsed){ int i; for (i = 0; i < MAXLIST; i++) { parsed[i] = strsep(&str, \" \"); if (parsed[i] == NULL) break; if (strlen(parsed[i]) == 0) i--; }} int processString(char* str, char** parsed, char** parsedpipe){ char* strpiped[2]; int piped = 0; piped = parsePipe(str, strpiped); if (piped) { parseSpace(strpiped[0], parsed); parseSpace(strpiped[1], parsedpipe); } else { parseSpace(str, parsed); } if (ownCmdHandler(parsed)) return 0; else return 1 + piped;} int main(){ char inputString[MAXCOM], *parsedArgs[MAXLIST]; char* parsedArgsPiped[MAXLIST]; int execFlag = 0; init_shell(); while (1) { // print shell line printDir(); // take input if (takeInput(inputString)) continue; // process execFlag = processString(inputString, parsedArgs, parsedArgsPiped); // execflag returns zero if there is no command // or it is a builtin command, // 1 if it is a simple command // 2 if it is including a pipe. // execute if (execFlag == 1) execArgs(parsedArgs); if (execFlag == 2) execArgsPiped(parsedArgs, parsedArgsPiped); } return 0;}",
"e": 10836,
"s": 4866,
"text": null
},
{
"code": null,
"e": 10854,
"s": 10836,
"text": "To Run the code –"
},
{
"code": null,
"e": 10887,
"s": 10854,
"text": " gcc shell.c -lreadline\n./a.out "
},
{
"code": null,
"e": 10895,
"s": 10887,
"text": "Output:"
},
{
"code": null,
"e": 11195,
"s": 10895,
"text": "This article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11320,
"s": 11195,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11329,
"s": 11320,
"text": "top_gunn"
},
{
"code": null,
"e": 11348,
"s": 11329,
"text": "system-programming"
},
{
"code": null,
"e": 11359,
"s": 11348,
"text": "C Language"
},
{
"code": null,
"e": 11370,
"s": 11359,
"text": "Linux-Unix"
},
{
"code": null,
"e": 11468,
"s": 11370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11485,
"s": 11468,
"text": "Substring in C++"
},
{
"code": null,
"e": 11520,
"s": 11485,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 11542,
"s": 11520,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 11588,
"s": 11542,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 11633,
"s": 11588,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 11673,
"s": 11633,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 11700,
"s": 11673,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 11740,
"s": 11700,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 11775,
"s": 11740,
"text": "tar command in Linux with examples"
}
] |
Python – Generate random number except K in list
|
06 Mar, 2020
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed.
Method #1 : Using choice() + list comprehensionThe combination of above functions can be used to perform this task. In this, we first filter out the numbers except K using list comprehension and then feed that list to choice() for random number generation.
# Python3 code to demonstrate # Generate random number except K in list# using choice() + list comprehensionimport random # Initializing list test_list = [4, 7, 8, 4, 6, 10] # printing original listprint("The original list is : " + str(test_list)) # Initializing K K = 4 # Generate random number except K in list# using choice() + list comprehensionres = random.choice([ele for ele in test_list if ele != K]) # printing result print ("The random number except K is : " + str(res))
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8
Method #2 : Using filter() + lambda + choice()This is yet another way in which this task can be performed. In this, we perform method of creating new list using filter and lambda.
# Python3 code to demonstrate # Generate random number except K in list# using choice() + filter() + lambdaimport random # Initializing list test_list = [4, 7, 8, 4, 6, 10] # printing original listprint("The original list is : " + str(test_list)) # Initializing K K = 4 # Generate random number except K in list# using choice() + filter() + lambdares = random.choice(list(filter(lambda ele: ele != K, test_list))) # printing result print ("The random number except K is : " + str(res))
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Mar, 2020"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 593,
"s": 336,
"text": "Method #1 : Using choice() + list comprehensionThe combination of above functions can be used to perform this task. In this, we first filter out the numbers except K using list comprehension and then feed that list to choice() for random number generation."
},
{
"code": "# Python3 code to demonstrate # Generate random number except K in list# using choice() + list comprehensionimport random # Initializing list test_list = [4, 7, 8, 4, 6, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing K K = 4 # Generate random number except K in list# using choice() + list comprehensionres = random.choice([ele for ele in test_list if ele != K]) # printing result print (\"The random number except K is : \" + str(res))",
"e": 1079,
"s": 593,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1079,
"text": "The original list is : [4, 7, 8, 4, 6, 10]\nThe random number except K is : 8\n"
},
{
"code": null,
"e": 1339,
"s": 1159,
"text": "Method #2 : Using filter() + lambda + choice()This is yet another way in which this task can be performed. In this, we perform method of creating new list using filter and lambda."
},
{
"code": "# Python3 code to demonstrate # Generate random number except K in list# using choice() + filter() + lambdaimport random # Initializing list test_list = [4, 7, 8, 4, 6, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing K K = 4 # Generate random number except K in list# using choice() + filter() + lambdares = random.choice(list(filter(lambda ele: ele != K, test_list))) # printing result print (\"The random number except K is : \" + str(res))",
"e": 1830,
"s": 1339,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1830,
"text": "The original list is : [4, 7, 8, 4, 6, 10]\nThe random number except K is : 8\n"
},
{
"code": null,
"e": 1929,
"s": 1908,
"text": "Python list-programs"
},
{
"code": null,
"e": 1936,
"s": 1929,
"text": "Python"
},
{
"code": null,
"e": 1952,
"s": 1936,
"text": "Python Programs"
},
{
"code": null,
"e": 2050,
"s": 1952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2068,
"s": 2050,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2110,
"s": 2068,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2132,
"s": 2110,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2167,
"s": 2132,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2193,
"s": 2167,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2236,
"s": 2193,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2258,
"s": 2236,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2297,
"s": 2258,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2335,
"s": 2297,
"text": "Python | Convert a list to dictionary"
}
] |
numpy.linalg.det() Method in Python
|
29 Jul, 2021
In NumPy, we can compute the determinant of the given square array with the help of numpy.linalg.det(). It will take the given square array as a parameter and return the determinant of that.
Syntax: numpy.linalg.det() Parameter: An square array. Return: The determinant of that square array.
Example 1:
Python
import numpy as npfrom numpy import linalg as LA array1 = np.array([[1, 2], [3, 4]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))
Output:
[[1 2]
[3 4]]
-2.0000000000000004
Example 2:
Python
import numpy as npfrom numpy import linalg as LA array1 = np.array([[1, 2, 3], [3, 4, 1], [3, 2, 1]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))
Output:
[[1 2 3]
[3 4 1]
[3 2 1]]
-15.999999999999998
surinderdawra388
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 219,
"s": 28,
"text": "In NumPy, we can compute the determinant of the given square array with the help of numpy.linalg.det(). It will take the given square array as a parameter and return the determinant of that."
},
{
"code": null,
"e": 320,
"s": 219,
"text": "Syntax: numpy.linalg.det() Parameter: An square array. Return: The determinant of that square array."
},
{
"code": null,
"e": 331,
"s": 320,
"text": "Example 1:"
},
{
"code": null,
"e": 338,
"s": 331,
"text": "Python"
},
{
"code": "import numpy as npfrom numpy import linalg as LA array1 = np.array([[1, 2], [3, 4]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))",
"e": 522,
"s": 338,
"text": null
},
{
"code": null,
"e": 530,
"s": 522,
"text": "Output:"
},
{
"code": null,
"e": 565,
"s": 530,
"text": "[[1 2]\n [3 4]]\n-2.0000000000000004"
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Example 2:"
},
{
"code": null,
"e": 583,
"s": 576,
"text": "Python"
},
{
"code": "import numpy as npfrom numpy import linalg as LA array1 = np.array([[1, 2, 3], [3, 4, 1], [3, 2, 1]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))",
"e": 784,
"s": 583,
"text": null
},
{
"code": null,
"e": 792,
"s": 784,
"text": "Output:"
},
{
"code": null,
"e": 840,
"s": 792,
"text": "[[1 2 3]\n [3 4 1]\n [3 2 1]]\n-15.999999999999998"
},
{
"code": null,
"e": 857,
"s": 840,
"text": "surinderdawra388"
},
{
"code": null,
"e": 886,
"s": 857,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 899,
"s": 886,
"text": "Python-numpy"
},
{
"code": null,
"e": 906,
"s": 899,
"text": "Python"
},
{
"code": null,
"e": 1004,
"s": 906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1036,
"s": 1004,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1063,
"s": 1036,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1084,
"s": 1063,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1107,
"s": 1084,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1163,
"s": 1107,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1194,
"s": 1163,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1236,
"s": 1194,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1278,
"s": 1236,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1317,
"s": 1278,
"text": "Python | Get unique values from a list"
}
] |
TypeScript - Multidimensional Arrays
|
An array element can reference another array for its value. Such arrays are called as multidimensional arrays. TypeScript supports the concept of multi-dimensional arrays. The simplest form of a multi-dimensional array is a two-dimensional array.
var arr_name:datatype[][]=[ [val1,val2,val3],[v1,v2,v3] ]
var arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1,val2,val 3],
[v1,v2,v3] ]
The following example better explains this concept.
var multi:number[][] = [[1,2,3],[23,24,25]]
console.log(multi[0][0])
console.log(multi[0][1])
console.log(multi[0][2])
console.log(multi[1][0])
console.log(multi[1][1])
console.log(multi[1][2])
The above example initially declares an array with 2 elements. Each of these elements refer to another array having 3 elements. The pictorial representation of the above array is given below.
While referring to an array element here, the subscript of the initial array element must be followed by the subscript of the referenced array element. This is illustrated in the code.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var multi = [[1, 2, 3], [23, 24, 25]];
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);
The output of the above code is as follows −
|
[
{
"code": null,
"e": 2429,
"s": 2182,
"text": "An array element can reference another array for its value. Such arrays are called as multidimensional arrays. TypeScript supports the concept of multi-dimensional arrays. The simplest form of a multi-dimensional array is a two-dimensional array."
},
{
"code": null,
"e": 2488,
"s": 2429,
"text": "var arr_name:datatype[][]=[ [val1,val2,val3],[v1,v2,v3] ]\n"
},
{
"code": null,
"e": 2595,
"s": 2488,
"text": "var arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1,val2,val 3],\n [v1,v2,v3] ]\n"
},
{
"code": null,
"e": 2647,
"s": 2595,
"text": "The following example better explains this concept."
},
{
"code": null,
"e": 2849,
"s": 2647,
"text": "var multi:number[][] = [[1,2,3],[23,24,25]] \nconsole.log(multi[0][0]) \nconsole.log(multi[0][1]) \nconsole.log(multi[0][2]) \nconsole.log(multi[1][0]) \nconsole.log(multi[1][1]) \nconsole.log(multi[1][2])\n"
},
{
"code": null,
"e": 3041,
"s": 2849,
"text": "The above example initially declares an array with 2 elements. Each of these elements refer to another array having 3 elements. The pictorial representation of the above array is given below."
},
{
"code": null,
"e": 3226,
"s": 3041,
"text": "While referring to an array element here, the subscript of the initial array element must be followed by the subscript of the referenced array element. This is illustrated in the code."
},
{
"code": null,
"e": 3284,
"s": 3226,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 3513,
"s": 3284,
"text": "//Generated by typescript 1.8.10\nvar multi = [[1, 2, 3], [23, 24, 25]];\nconsole.log(multi[0][0]);\nconsole.log(multi[0][1]);\nconsole.log(multi[0][2]);\nconsole.log(multi[1][0]);\nconsole.log(multi[1][1]);\nconsole.log(multi[1][2]);\n"
}
] |
Node.js URL.pathToFileURL API
|
14 Oct, 2021
This URL.pathToFileURL function converts the path to a file and ensures that the URL control characters (/, \, : ) are correctly appended/adjusted when converting the given path into a File URL.
Syntax:
url.pathToFileURL(path)
Parameters: This function accepts single parameter path which holds the path to convert a file URL.
Return Value: This function returns the file URL object.
Below programs illustrates the use of URL.-pathToFileURL Method:
Example 1:
// Node program to demonstrate the // URL.pathToFileURL API as Setter // Importing the module 'url' var url = require('url'); // Some random path from systemconst path = 'D:\GeeksForGeeks' // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path))
Output:
URL {
href: 'file:///D:/GeeksForGeeks',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/D:/GeeksForGeeks',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Example 2:
// Node program to demonstrate the // URL.pathToFileURL API as Setter // Importing the module 'url' var url = require('url'); // Some random path from systemconst path = 'D:\NodeJS\node_modules\npm' // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path))
Output:
URL {
href: 'file:///D:/NodeJS%0Aode_modules%0Apm',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/D:/NodeJS%0Aode_modules%0Apm',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Note: The above program will compile and run by using the node app.js command.
Reference https://nodejs.org/api/url.html#url_url_pathtofileurl_path
Node-URL
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Oct, 2021"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "This URL.pathToFileURL function converts the path to a file and ensures that the URL control characters (/, \\, : ) are correctly appended/adjusted when converting the given path into a File URL."
},
{
"code": null,
"e": 231,
"s": 223,
"text": "Syntax:"
},
{
"code": null,
"e": 255,
"s": 231,
"text": "url.pathToFileURL(path)"
},
{
"code": null,
"e": 355,
"s": 255,
"text": "Parameters: This function accepts single parameter path which holds the path to convert a file URL."
},
{
"code": null,
"e": 412,
"s": 355,
"text": "Return Value: This function returns the file URL object."
},
{
"code": null,
"e": 477,
"s": 412,
"text": "Below programs illustrates the use of URL.-pathToFileURL Method:"
},
{
"code": null,
"e": 488,
"s": 477,
"text": "Example 1:"
},
{
"code": "// Node program to demonstrate the // URL.pathToFileURL API as Setter // Importing the module 'url' var url = require('url'); // Some random path from systemconst path = 'D:\\GeeksForGeeks' // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path)) ",
"e": 767,
"s": 488,
"text": null
},
{
"code": null,
"e": 775,
"s": 767,
"text": "Output:"
},
{
"code": null,
"e": 1027,
"s": 775,
"text": " \nURL {\n href: 'file:///D:/GeeksForGeeks',\n origin: 'null',\n protocol: 'file:',\n username: '',\n password: '',\n host: '',\n hostname: '',\n port: '',\n pathname: '/D:/GeeksForGeeks',\n search: '',\n searchParams: URLSearchParams {},\n hash: ''\n}\n"
},
{
"code": null,
"e": 1038,
"s": 1027,
"text": "Example 2:"
},
{
"code": "// Node program to demonstrate the // URL.pathToFileURL API as Setter // Importing the module 'url' var url = require('url'); // Some random path from systemconst path = 'D:\\NodeJS\\node_modules\\npm' // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path)) ",
"e": 1329,
"s": 1038,
"text": null
},
{
"code": null,
"e": 1337,
"s": 1329,
"text": "Output:"
},
{
"code": null,
"e": 1611,
"s": 1337,
"text": "URL {\n href: 'file:///D:/NodeJS%0Aode_modules%0Apm',\n origin: 'null',\n protocol: 'file:',\n username: '',\n password: '',\n host: '',\n hostname: '',\n port: '',\n pathname: '/D:/NodeJS%0Aode_modules%0Apm',\n search: '',\n searchParams: URLSearchParams {},\n hash: ''\n}\n"
},
{
"code": null,
"e": 1690,
"s": 1611,
"text": "Note: The above program will compile and run by using the node app.js command."
},
{
"code": null,
"e": 1759,
"s": 1690,
"text": "Reference https://nodejs.org/api/url.html#url_url_pathtofileurl_path"
},
{
"code": null,
"e": 1768,
"s": 1759,
"text": "Node-URL"
},
{
"code": null,
"e": 1775,
"s": 1768,
"text": "Picked"
},
{
"code": null,
"e": 1783,
"s": 1775,
"text": "Node.js"
},
{
"code": null,
"e": 1800,
"s": 1783,
"text": "Web Technologies"
}
] |
Title alignment in Plotly
|
24 Jan, 2022
In this article, we are going to discuss title assignment and alignment using plotly module.
In order to align titles in visualization using plotly module, we are going to use the update_layout() method.
Syntax:
plotly.graph_objects.Figure.update_layout(title_text, title_x, title_y)
Parameters:
title: Accepts string value as the title of the visualization.
title_x: This parameter is used to align the title in a horizontal motion and accepts a value from 0 to 1.
title_y: This parameter is used to align the title in a vertical motion and accepts a value from 0 to 1.
Let’s implement the method on the below examples:
Example 1
Python3
# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected=True) # generating 150 random integers# from 1 to 50x = np.random.randint(low=1, high=50, size=150)*0.1 # generating 150 random integers# from 1 to 50y = np.random.randint(low=1, high=50, size=150)*0.1 # plotting scatter plotfig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers')) # title alignmentfig.update_layout(title_text='Dots') fig.show()
Output:
Example 2
Python3
# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # different individual parts in# total chartcountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # values corresponding to each# individual country present in# countriesvalues = [4500, 2500, 1053, 500, 3200, 1500, 1253, 600, 3500] # plotting pie chartfig = go.Figure(data=[go.Pie(labels=countries, values=values)]) # title alignmentfig.update_layout(title_text='Pie',title_y=0.5) fig.show()
Output:
With title_y=0.5, the title should be in center.
When title_y = 0.1
When title_y = 1
Example 3
Python3
# import required librariesimport dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.express as pximport pandas as pd external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a "long-form" data framedf = pd.DataFrame({ "Year": ["2015", "2016", "2017", "2015", "2016", "2017"], "Revenue": [4, 1, 2, 2, 4, 5], "Company": ["ABC Pvt. Ltd.", "ABC Pvt. Ltd.", "ABC Pvt. Ltd.", "XYZ Pvt. Ltd.", "XYZ Pvt. Ltd.", "XYZ Pvt. Ltd."]}) # depict visualizationfig = px.bar(df, x="Year", y="Revenue", color="Company", barmode="group") app.layout = html.Div(children=[ dcc.Graph( id='example-graph', figure=fig )]) # align titlefig.update_layout(title_text='Revenue', title_x=0.5) if __name__ == '__main__': app.run_server(debug=True)
Output:
With title_x=0.5, the title should be in center.
When title_x = 0.3
When title_x = 1
manikarora059
sagar0719kumar
Picked
Python-Plotly
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?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "In this article, we are going to discuss title assignment and alignment using plotly module."
},
{
"code": null,
"e": 233,
"s": 121,
"text": "In order to align titles in visualization using plotly module, we are going to use the update_layout() method. "
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Syntax:"
},
{
"code": null,
"e": 313,
"s": 241,
"text": "plotly.graph_objects.Figure.update_layout(title_text, title_x, title_y)"
},
{
"code": null,
"e": 325,
"s": 313,
"text": "Parameters:"
},
{
"code": null,
"e": 388,
"s": 325,
"text": "title: Accepts string value as the title of the visualization."
},
{
"code": null,
"e": 495,
"s": 388,
"text": "title_x: This parameter is used to align the title in a horizontal motion and accepts a value from 0 to 1."
},
{
"code": null,
"e": 600,
"s": 495,
"text": "title_y: This parameter is used to align the title in a vertical motion and accepts a value from 0 to 1."
},
{
"code": null,
"e": 650,
"s": 600,
"text": "Let’s implement the method on the below examples:"
},
{
"code": null,
"e": 660,
"s": 650,
"text": "Example 1"
},
{
"code": null,
"e": 668,
"s": 660,
"text": "Python3"
},
{
"code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected=True) # generating 150 random integers# from 1 to 50x = np.random.randint(low=1, high=50, size=150)*0.1 # generating 150 random integers# from 1 to 50y = np.random.randint(low=1, high=50, size=150)*0.1 # plotting scatter plotfig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers')) # title alignmentfig.update_layout(title_text='Dots') fig.show()",
"e": 1215,
"s": 668,
"text": null
},
{
"code": null,
"e": 1223,
"s": 1215,
"text": "Output:"
},
{
"code": null,
"e": 1233,
"s": 1223,
"text": "Example 2"
},
{
"code": null,
"e": 1241,
"s": 1233,
"text": "Python3"
},
{
"code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # different individual parts in# total chartcountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # values corresponding to each# individual country present in# countriesvalues = [4500, 2500, 1053, 500, 3200, 1500, 1253, 600, 3500] # plotting pie chartfig = go.Figure(data=[go.Pie(labels=countries, values=values)]) # title alignmentfig.update_layout(title_text='Pie',title_y=0.5) fig.show()",
"e": 1944,
"s": 1241,
"text": null
},
{
"code": null,
"e": 1952,
"s": 1944,
"text": "Output:"
},
{
"code": null,
"e": 2001,
"s": 1952,
"text": "With title_y=0.5, the title should be in center."
},
{
"code": null,
"e": 2020,
"s": 2001,
"text": "When title_y = 0.1"
},
{
"code": null,
"e": 2037,
"s": 2020,
"text": "When title_y = 1"
},
{
"code": null,
"e": 2047,
"s": 2037,
"text": "Example 3"
},
{
"code": null,
"e": 2055,
"s": 2047,
"text": "Python3"
},
{
"code": "# import required librariesimport dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.express as pximport pandas as pd external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a \"long-form\" data framedf = pd.DataFrame({ \"Year\": [\"2015\", \"2016\", \"2017\", \"2015\", \"2016\", \"2017\"], \"Revenue\": [4, 1, 2, 2, 4, 5], \"Company\": [\"ABC Pvt. Ltd.\", \"ABC Pvt. Ltd.\", \"ABC Pvt. Ltd.\", \"XYZ Pvt. Ltd.\", \"XYZ Pvt. Ltd.\", \"XYZ Pvt. Ltd.\"]}) # depict visualizationfig = px.bar(df, x=\"Year\", y=\"Revenue\", color=\"Company\", barmode=\"group\") app.layout = html.Div(children=[ dcc.Graph( id='example-graph', figure=fig )]) # align titlefig.update_layout(title_text='Revenue', title_x=0.5) if __name__ == '__main__': app.run_server(debug=True)",
"e": 2943,
"s": 2055,
"text": null
},
{
"code": null,
"e": 2954,
"s": 2946,
"text": "Output:"
},
{
"code": null,
"e": 3005,
"s": 2956,
"text": "With title_x=0.5, the title should be in center."
},
{
"code": null,
"e": 3028,
"s": 3009,
"text": "When title_x = 0.3"
},
{
"code": null,
"e": 3049,
"s": 3032,
"text": "When title_x = 1"
},
{
"code": null,
"e": 3067,
"s": 3053,
"text": "manikarora059"
},
{
"code": null,
"e": 3082,
"s": 3067,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 3089,
"s": 3082,
"text": "Picked"
},
{
"code": null,
"e": 3103,
"s": 3089,
"text": "Python-Plotly"
},
{
"code": null,
"e": 3110,
"s": 3103,
"text": "Python"
},
{
"code": null,
"e": 3208,
"s": 3110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3253,
"s": 3208,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3269,
"s": 3253,
"text": "Deque in Python"
},
{
"code": null,
"e": 3291,
"s": 3269,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3307,
"s": 3291,
"text": "Queue in Python"
},
{
"code": null,
"e": 3357,
"s": 3307,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3399,
"s": 3357,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3426,
"s": 3399,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3449,
"s": 3426,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 3470,
"s": 3449,
"text": "Python OOPs Concepts"
}
] |
Passive Aggressive Classifiers
|
17 Jul, 2020
The Passive-Aggressive algorithms are a family of Machine learning algorithms that are not very well known by beginners and even intermediate Machine Learning enthusiasts. However, they can be very useful and efficient for certain applications.
Note: This is a high-level overview of the algorithm explaining how it works and when to use it. It does not go deep into the mathematics of how it works.Passive-Aggressive algorithms are generally used for large-scale learning. It is one of the few ‘online-learning algorithms‘. In online machine learning algorithms, the input data comes in sequential order and the machine learning model is updated step-by-step, as opposed to batch learning, where the entire training dataset is used at once. This is very useful in situations where there is a huge amount of data and it is computationally infeasible to train the entire dataset because of the sheer size of the data. We can simply say that an online-learning algorithm will get a training example, update the classifier, and then throw away the example.
A very good example of this would be to detect fake news on a social media website like Twitter, where new data is being added every second. To dynamically read data from Twitter continuously, the data would be huge, and using an online-learning algorithm would be ideal.
Passive-Aggressive algorithms are somewhat similar to a Perceptron model, in the sense that they do not require a learning rate. However, they do include a regularization parameter.
How Passive-Aggressive Algorithms Work:Passive-Aggressive algorithms are called so because :
Passive: If the prediction is correct, keep the model and do not make any changes. i.e., the data in the example is not enough to cause any changes in the model.
Aggressive: If the prediction is incorrect, make changes to the model. i.e., some change to the model may correct it.
Understanding the mathematics behind this algorithm is not very simple and is beyond the scope of a single article. This article provides just an overview of the algorithm and a simple implementation of it. To learn more about the mathematics behind this algorithm, I recommend watching this excellent video on the algorithm’s working by Dr Victor Lavrenko.
Important parameters:
C : This is the regularization parameter, and denotes the penalization the model will make on an incorrect prediction
max_iter : The maximum number of iterations the model makes over the training data.
tol : The stopping criterion. If it is set to None, the model will stop when (loss > previous_loss – tol). By default, it is set to 1e-3.
Simple Implementation in Python3Although for practical usage of this algorithm, huge streams of data are required, but for the sake of this example, we will be using the popular iris dataset. To learn more about this dataset, you can use go this link.
Code: Python’s scikit-learn library implementation of Passive-Aggressive classifiers.
# Importing modulesfrom sklearn.datasets import load_irisfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.metrics import classification_report, accuracy_scorefrom sklearn.model_selection import train_test_split # Loading datasetdataset = load_iris()X = dataset.datay = dataset.target # Splitting iris dataset into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 13) # Creating modelmodel = PassiveAggressiveClassifier(C = 0.5, random_state = 5) # Fitting model model.fit(X_train, y_train) # Making prediction on test settest_pred = model.predict(X_test) # Model evaluationprint(f"Test Set Accuracy : {accuracy_score(y_test, test_pred) * 100} %\n\n") print(f"Classification Report : \n\n{classification_report(y_test, test_pred)}")
We have used set the regularization parameter, ‘C’ to 0.5. Now let us see the output.Output:
Test Set Accuracy : 93.33333333333333 %
Classification Report :
precision recall f1-score support
0 1.00 1.00 1.00 4
1 1.00 0.75 0.86 4
2 0.88 1.00 0.93 7
accuracy 0.93 15
macro avg 0.96 0.92 0.93 15
weighted avg 0.94 0.93 0.93 15
We have achieved a test set accuracy of 93.33%.Conclusion:If you want to work on big data, this is a very important classifier and I encourage you to go ahead and try to build a project using this classifier and use live data from a social media website like Twitter as input. There will be a huge amount of data coming in every second and this classifier will be able to handle data of this size.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jul, 2020"
},
{
"code": null,
"e": 299,
"s": 54,
"text": "The Passive-Aggressive algorithms are a family of Machine learning algorithms that are not very well known by beginners and even intermediate Machine Learning enthusiasts. However, they can be very useful and efficient for certain applications."
},
{
"code": null,
"e": 1108,
"s": 299,
"text": "Note: This is a high-level overview of the algorithm explaining how it works and when to use it. It does not go deep into the mathematics of how it works.Passive-Aggressive algorithms are generally used for large-scale learning. It is one of the few ‘online-learning algorithms‘. In online machine learning algorithms, the input data comes in sequential order and the machine learning model is updated step-by-step, as opposed to batch learning, where the entire training dataset is used at once. This is very useful in situations where there is a huge amount of data and it is computationally infeasible to train the entire dataset because of the sheer size of the data. We can simply say that an online-learning algorithm will get a training example, update the classifier, and then throw away the example."
},
{
"code": null,
"e": 1380,
"s": 1108,
"text": "A very good example of this would be to detect fake news on a social media website like Twitter, where new data is being added every second. To dynamically read data from Twitter continuously, the data would be huge, and using an online-learning algorithm would be ideal."
},
{
"code": null,
"e": 1562,
"s": 1380,
"text": "Passive-Aggressive algorithms are somewhat similar to a Perceptron model, in the sense that they do not require a learning rate. However, they do include a regularization parameter."
},
{
"code": null,
"e": 1655,
"s": 1562,
"text": "How Passive-Aggressive Algorithms Work:Passive-Aggressive algorithms are called so because :"
},
{
"code": null,
"e": 1818,
"s": 1655,
"text": "Passive: If the prediction is correct, keep the model and do not make any changes. i.e., the data in the example is not enough to cause any changes in the model. "
},
{
"code": null,
"e": 1936,
"s": 1818,
"text": "Aggressive: If the prediction is incorrect, make changes to the model. i.e., some change to the model may correct it."
},
{
"code": null,
"e": 2294,
"s": 1936,
"text": "Understanding the mathematics behind this algorithm is not very simple and is beyond the scope of a single article. This article provides just an overview of the algorithm and a simple implementation of it. To learn more about the mathematics behind this algorithm, I recommend watching this excellent video on the algorithm’s working by Dr Victor Lavrenko."
},
{
"code": null,
"e": 2316,
"s": 2294,
"text": "Important parameters:"
},
{
"code": null,
"e": 2434,
"s": 2316,
"text": "C : This is the regularization parameter, and denotes the penalization the model will make on an incorrect prediction"
},
{
"code": null,
"e": 2518,
"s": 2434,
"text": "max_iter : The maximum number of iterations the model makes over the training data."
},
{
"code": null,
"e": 2658,
"s": 2518,
"text": "tol : The stopping criterion. If it is set to None, the model will stop when (loss > previous_loss – tol). By default, it is set to 1e-3."
},
{
"code": null,
"e": 2910,
"s": 2658,
"text": "Simple Implementation in Python3Although for practical usage of this algorithm, huge streams of data are required, but for the sake of this example, we will be using the popular iris dataset. To learn more about this dataset, you can use go this link."
},
{
"code": null,
"e": 2996,
"s": 2910,
"text": "Code: Python’s scikit-learn library implementation of Passive-Aggressive classifiers."
},
{
"code": "# Importing modulesfrom sklearn.datasets import load_irisfrom sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn.metrics import classification_report, accuracy_scorefrom sklearn.model_selection import train_test_split # Loading datasetdataset = load_iris()X = dataset.datay = dataset.target # Splitting iris dataset into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 13) # Creating modelmodel = PassiveAggressiveClassifier(C = 0.5, random_state = 5) # Fitting model model.fit(X_train, y_train) # Making prediction on test settest_pred = model.predict(X_test) # Model evaluationprint(f\"Test Set Accuracy : {accuracy_score(y_test, test_pred) * 100} %\\n\\n\") print(f\"Classification Report : \\n\\n{classification_report(y_test, test_pred)}\")",
"e": 3821,
"s": 2996,
"text": null
},
{
"code": null,
"e": 3914,
"s": 3821,
"text": "We have used set the regularization parameter, ‘C’ to 0.5. Now let us see the output.Output:"
},
{
"code": null,
"e": 4362,
"s": 3914,
"text": "Test Set Accuracy : 93.33333333333333 %\n\n\nClassification Report : \n\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 4\n 1 1.00 0.75 0.86 4\n 2 0.88 1.00 0.93 7\n\n accuracy 0.93 15\n macro avg 0.96 0.92 0.93 15\nweighted avg 0.94 0.93 0.93 15"
},
{
"code": null,
"e": 4760,
"s": 4362,
"text": "We have achieved a test set accuracy of 93.33%.Conclusion:If you want to work on big data, this is a very important classifier and I encourage you to go ahead and try to build a project using this classifier and use live data from a social media website like Twitter as input. There will be a huge amount of data coming in every second and this classifier will be able to handle data of this size."
},
{
"code": null,
"e": 4777,
"s": 4760,
"text": "Machine Learning"
},
{
"code": null,
"e": 4784,
"s": 4777,
"text": "Python"
},
{
"code": null,
"e": 4801,
"s": 4784,
"text": "Machine Learning"
},
{
"code": null,
"e": 4899,
"s": 4801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4940,
"s": 4899,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4973,
"s": 4940,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 5009,
"s": 4973,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5033,
"s": 5009,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5084,
"s": 5033,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 5112,
"s": 5084,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5134,
"s": 5112,
"text": "Python map() function"
},
{
"code": null,
"e": 5184,
"s": 5134,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5202,
"s": 5184,
"text": "Python Dictionary"
}
] |
Print all possible expressions that evaluate to a target
|
25 May, 2022
Given a string that contains only digits from 0 to 9, and an integer value, target. Find out how many expressions are possible which evaluate to target using binary operator +, – and * in given string of digits.
Input : "123", Target : 6
Output : {“1+2+3”, “1*2*3”}
Input : “125”, Target : 7
Output : {“1*2+5”, “12-5”}
This problem can be solved by putting all possible binary operator in mid between to digits and evaluating them and then check they evaluate to target or not.
While writing the recursive code, we need to keep these variable as argument of recursive method – result vector, input string, current expression string, target value, position till which input is processed, current evaluated value and last value in evaluation.
Last value is kept in recursion because of multiplication operation, while doing multiplication we need last value for correct evaluation.
See below example for better understanding –
Input is 125, suppose we have reached till 1+2 now,
Input = “125”, current expression = “1+2”,
position = 2, current val = 3, last = 2
Now when we go for multiplication, we need last
value for evaluation as follows:
current val = current val - last + last * current val
First we subtract last and then add last * current
val for evaluation, new last is last * current val.
current val = 3 – 2 + 2*5 = 11
last = 2*5 = 10
Another thing to note in below code is, we have ignored all numbers which start from 0 by imposing a condition as first condition inside the loop so that we will not process number like 03, 05 etc.See the use of c_str() function, this function converts the C++ string into C char array, this function is used in below code because atoi() function expects a character array as an argument not the string. It converts character array to number.
C++
Java
Python3
C#
Javascript
// C++ program to find all possible expression which// evaluate to target#include <bits/stdc++.h>using namespace std; // Utility recursive method to generate all possible// expressionsvoid getExprUtil(vector<string>& res, string curExp, string input, int target, int pos, int curVal, int last){ // true if whole input is processed with some // operators if (pos == input.length()) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.push_back(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.length(); i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i string part = input.substr(pos, i + 1 - pos); // take numeric value of part int cur = atoi(part.c_str()); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + "+" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + "-" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + "*" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } }} // Below method returns all possible expression// evaluating to targetvector<string> getExprs(string input, int target){ vector<string> res; getExprUtil(res, "", input, target, 0, 0, 0); return res;} // method to print resultvoid printResult(vector<string> res){ for (int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << endl;} // Driver code to test above methodsint main(){ string input = "123"; int target = 6; vector<string> res = getExprs(input, target); printResult(res); input = "125"; target = 7; res = getExprs(input, target); printResult(res); return 0;}
// Java program to find all possible expression which// evaluate to target import java.util.ArrayList; class GFG { // Utility recursive method to generate all possible // expressions static void getExprUtil(ArrayList<String> res, String curExp, String input, int target, int pos, int curVal, int last) { // true if whole input is processed with some // operators if (pos == input.length()) { // if current value is equal to target // then only add to final solution // if question is : all possible o/p then just // push_back without condition if (curVal == target) res.add(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.length(); i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input.charAt(pos) == '0') break; // take part of input from pos to i String part = input.substring(pos, i + 1); // take numeric value of part int cur = Integer.parseInt(part); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + "+" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + "-" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + "*" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target static ArrayList<String> getExprs(String input, int target) { ArrayList<String> res = new ArrayList<String>(); getExprUtil(res, "", input, target, 0, 0, 0); return res; } // method to print result static void printResult(ArrayList<String> res) { for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + " "); System.out.println(); } // Driver code to test above methods public static void main(String[] args) { String input = "123"; int target = 6; ArrayList<String> res = getExprs(input, target); printResult(res); input = "125"; target = 7; res = getExprs(input, target); printResult(res); }} // This code is contributed by jainlovely450.o
# Python3 program to find all possible expression which# evaluate to target # Utility recursive method to generate all possible# expressionsdef getExprUtil(res, curExp, _input, target, pos, curVal, last): # true if whole input is processed with some # operators if (pos == len(_input)): # if current value is equal to target #then only add to final solution # if question is : all possible o/p then just #push_back without condition if (curVal == target): res.append(curExp) return # loop to put operator at all positions for i in range(pos,len(_input)): # ignoring case which start with 0 as they # are useless for evaluation if (i != pos and _input[pos] == '0'): break # take part of input from pos to i part = _input[pos: i + 1].strip() # take numeric value of part cur = int(part) # if pos is 0 then just send numeric value # for next recursion if (pos == 0): getExprUtil(res, curExp + part, _input, target, i + 1, cur, cur) # try all given binary operator for evaluation else: getExprUtil(res, curExp + "+" + part, _input, target, i + 1, curVal + cur, cur) getExprUtil(res, curExp + "-" + part, _input, target, i + 1, curVal - cur, -cur) getExprUtil(res, curExp + "*" + part, _input, target, i + 1, curVal - last + last * cur, last * cur) # Below method returns all possible expression# evaluating to targetdef getExprs(_input, target): res=[] getExprUtil(res, "", _input, target, 0, 0, 0) return res # method to print resultdef printResult(res): for i in range(len(res)): print(res[i],end=" ") print() # Driver code to test above methodsif __name__ == '__main__': _input = "123" target = 6 res = getExprs(_input, target) printResult(res) _input = "125" target = 7 res = getExprs(_input, target) printResult(res)
// C# program to find all possible expression which// evaluate to targetusing System;using System.Collections.Generic;class GFG { // Utility recursive method to generate all possible expressions static void getExprUtil(List<string> res, string curExp, string input, int target, int pos, int curVal, int last) { // true if whole input is processed with some // operators if (pos == input.Length) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.Add(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.Length; i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i string part = input.Substring(pos, i + 1 - pos); // take numeric value of part int cur = Int32.Parse(part); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + "+" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + "-" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + "*" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target static List<string> getExprs(string input, int target) { List<string> res = new List<string>(); getExprUtil(res, "", input, target, 0, 0, 0); return res; } // method to print result static void printResult(List<string> res) { for (int i = 0; i < res.Count; i++) Console.Write(res[i] + " "); Console.WriteLine(); } static void Main() { string input = "123"; int target = 6; List<string> res = getExprs(input, target); printResult(res); input = "125"; target = 7; res = getExprs(input, target); printResult(res); }} // This code is contributed by divyesh072019.
<script> // Javascript program to find all possible expression which // evaluate to target // Utility recursive method to generate all possible // expressions function getExprUtil(res, curExp, input, target, pos, curVal, last) { // true if whole input is processed with some // operators if (pos == input.length) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.push(curExp); return; } // loop to put operator at all positions for (let i = pos; i < input.length; i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i let part = input.substr(pos, i + 1 - pos); // take numeric value of part let cur = parseInt(part, 10); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + "+" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + "-" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + "*" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target function getExprs(input, target) { let res = []; getExprUtil(res, "", input, target, 0, 0, 0); return res; } // method to print result function printResult(res) { for (let i = 0; i < res.length; i++) document.write(res[i] + " "); document.write("</br>"); } let input = "123"; let target = 6; let res = getExprs(input, target); printResult(res); input = "125"; target = 7; res = getExprs(input, target); printResult(res); // This code is contributed by decode2207.</script>
Output:
1+2+3 1*2*3
1*2+5 12-5
Time Complexity: O()Auxiliary Space: O(N) This article is contributed by Utkarsh Trivedi. 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.
surinderdawra388
pankajsharmagfg
amartyaghoshgfg
decode2207
divyesh072019
jainlovely450
Algorithms
Recursion
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 265,
"s": 52,
"text": "Given a string that contains only digits from 0 to 9, and an integer value, target. Find out how many expressions are possible which evaluate to target using binary operator +, – and * in given string of digits. "
},
{
"code": null,
"e": 374,
"s": 265,
"text": "Input : \"123\", Target : 6\nOutput : {“1+2+3”, “1*2*3”}\n\nInput : “125”, Target : 7\nOutput : {“1*2+5”, “12-5”}"
},
{
"code": null,
"e": 537,
"s": 376,
"text": "This problem can be solved by putting all possible binary operator in mid between to digits and evaluating them and then check they evaluate to target or not. "
},
{
"code": null,
"e": 800,
"s": 537,
"text": "While writing the recursive code, we need to keep these variable as argument of recursive method – result vector, input string, current expression string, target value, position till which input is processed, current evaluated value and last value in evaluation."
},
{
"code": null,
"e": 939,
"s": 800,
"text": "Last value is kept in recursion because of multiplication operation, while doing multiplication we need last value for correct evaluation."
},
{
"code": null,
"e": 986,
"s": 939,
"text": "See below example for better understanding – "
},
{
"code": null,
"e": 1413,
"s": 986,
"text": "Input is 125, suppose we have reached till 1+2 now,\nInput = “125”, current expression = “1+2”, \nposition = 2, current val = 3, last = 2\n\nNow when we go for multiplication, we need last \nvalue for evaluation as follows:\n\ncurrent val = current val - last + last * current val\n\nFirst we subtract last and then add last * current \nval for evaluation, new last is last * current val.\ncurrent val = 3 – 2 + 2*5 = 11\nlast = 2*5 = 10 "
},
{
"code": null,
"e": 1857,
"s": 1413,
"text": "Another thing to note in below code is, we have ignored all numbers which start from 0 by imposing a condition as first condition inside the loop so that we will not process number like 03, 05 etc.See the use of c_str() function, this function converts the C++ string into C char array, this function is used in below code because atoi() function expects a character array as an argument not the string. It converts character array to number. "
},
{
"code": null,
"e": 1861,
"s": 1857,
"text": "C++"
},
{
"code": null,
"e": 1866,
"s": 1861,
"text": "Java"
},
{
"code": null,
"e": 1874,
"s": 1866,
"text": "Python3"
},
{
"code": null,
"e": 1877,
"s": 1874,
"text": "C#"
},
{
"code": null,
"e": 1888,
"s": 1877,
"text": "Javascript"
},
{
"code": "// C++ program to find all possible expression which// evaluate to target#include <bits/stdc++.h>using namespace std; // Utility recursive method to generate all possible// expressionsvoid getExprUtil(vector<string>& res, string curExp, string input, int target, int pos, int curVal, int last){ // true if whole input is processed with some // operators if (pos == input.length()) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.push_back(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.length(); i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i string part = input.substr(pos, i + 1 - pos); // take numeric value of part int cur = atoi(part.c_str()); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + \"+\" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + \"-\" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + \"*\" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } }} // Below method returns all possible expression// evaluating to targetvector<string> getExprs(string input, int target){ vector<string> res; getExprUtil(res, \"\", input, target, 0, 0, 0); return res;} // method to print resultvoid printResult(vector<string> res){ for (int i = 0; i < res.size(); i++) cout << res[i] << \" \"; cout << endl;} // Driver code to test above methodsint main(){ string input = \"123\"; int target = 6; vector<string> res = getExprs(input, target); printResult(res); input = \"125\"; target = 7; res = getExprs(input, target); printResult(res); return 0;}",
"e": 4283,
"s": 1888,
"text": null
},
{
"code": "// Java program to find all possible expression which// evaluate to target import java.util.ArrayList; class GFG { // Utility recursive method to generate all possible // expressions static void getExprUtil(ArrayList<String> res, String curExp, String input, int target, int pos, int curVal, int last) { // true if whole input is processed with some // operators if (pos == input.length()) { // if current value is equal to target // then only add to final solution // if question is : all possible o/p then just // push_back without condition if (curVal == target) res.add(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.length(); i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input.charAt(pos) == '0') break; // take part of input from pos to i String part = input.substring(pos, i + 1); // take numeric value of part int cur = Integer.parseInt(part); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + \"+\" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + \"-\" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + \"*\" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target static ArrayList<String> getExprs(String input, int target) { ArrayList<String> res = new ArrayList<String>(); getExprUtil(res, \"\", input, target, 0, 0, 0); return res; } // method to print result static void printResult(ArrayList<String> res) { for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \"); System.out.println(); } // Driver code to test above methods public static void main(String[] args) { String input = \"123\"; int target = 6; ArrayList<String> res = getExprs(input, target); printResult(res); input = \"125\"; target = 7; res = getExprs(input, target); printResult(res); }} // This code is contributed by jainlovely450.o",
"e": 7268,
"s": 4283,
"text": null
},
{
"code": "# Python3 program to find all possible expression which# evaluate to target # Utility recursive method to generate all possible# expressionsdef getExprUtil(res, curExp, _input, target, pos, curVal, last): # true if whole input is processed with some # operators if (pos == len(_input)): # if current value is equal to target #then only add to final solution # if question is : all possible o/p then just #push_back without condition if (curVal == target): res.append(curExp) return # loop to put operator at all positions for i in range(pos,len(_input)): # ignoring case which start with 0 as they # are useless for evaluation if (i != pos and _input[pos] == '0'): break # take part of input from pos to i part = _input[pos: i + 1].strip() # take numeric value of part cur = int(part) # if pos is 0 then just send numeric value # for next recursion if (pos == 0): getExprUtil(res, curExp + part, _input, target, i + 1, cur, cur) # try all given binary operator for evaluation else: getExprUtil(res, curExp + \"+\" + part, _input, target, i + 1, curVal + cur, cur) getExprUtil(res, curExp + \"-\" + part, _input, target, i + 1, curVal - cur, -cur) getExprUtil(res, curExp + \"*\" + part, _input, target, i + 1, curVal - last + last * cur, last * cur) # Below method returns all possible expression# evaluating to targetdef getExprs(_input, target): res=[] getExprUtil(res, \"\", _input, target, 0, 0, 0) return res # method to print resultdef printResult(res): for i in range(len(res)): print(res[i],end=\" \") print() # Driver code to test above methodsif __name__ == '__main__': _input = \"123\" target = 6 res = getExprs(_input, target) printResult(res) _input = \"125\" target = 7 res = getExprs(_input, target) printResult(res)",
"e": 9368,
"s": 7268,
"text": null
},
{
"code": "// C# program to find all possible expression which// evaluate to targetusing System;using System.Collections.Generic;class GFG { // Utility recursive method to generate all possible expressions static void getExprUtil(List<string> res, string curExp, string input, int target, int pos, int curVal, int last) { // true if whole input is processed with some // operators if (pos == input.Length) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.Add(curExp); return; } // loop to put operator at all positions for (int i = pos; i < input.Length; i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i string part = input.Substring(pos, i + 1 - pos); // take numeric value of part int cur = Int32.Parse(part); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + \"+\" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + \"-\" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + \"*\" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target static List<string> getExprs(string input, int target) { List<string> res = new List<string>(); getExprUtil(res, \"\", input, target, 0, 0, 0); return res; } // method to print result static void printResult(List<string> res) { for (int i = 0; i < res.Count; i++) Console.Write(res[i] + \" \"); Console.WriteLine(); } static void Main() { string input = \"123\"; int target = 6; List<string> res = getExprs(input, target); printResult(res); input = \"125\"; target = 7; res = getExprs(input, target); printResult(res); }} // This code is contributed by divyesh072019.",
"e": 11794,
"s": 9368,
"text": null
},
{
"code": "<script> // Javascript program to find all possible expression which // evaluate to target // Utility recursive method to generate all possible // expressions function getExprUtil(res, curExp, input, target, pos, curVal, last) { // true if whole input is processed with some // operators if (pos == input.length) { // if current value is equal to target //then only add to final solution // if question is : all possible o/p then just //push_back without condition if (curVal == target) res.push(curExp); return; } // loop to put operator at all positions for (let i = pos; i < input.length; i++) { // ignoring case which start with 0 as they // are useless for evaluation if (i != pos && input[pos] == '0') break; // take part of input from pos to i let part = input.substr(pos, i + 1 - pos); // take numeric value of part let cur = parseInt(part, 10); // if pos is 0 then just send numeric value // for next recursion if (pos == 0) getExprUtil(res, curExp + part, input, target, i + 1, cur, cur); // try all given binary operator for evaluation else { getExprUtil(res, curExp + \"+\" + part, input, target, i + 1, curVal + cur, cur); getExprUtil(res, curExp + \"-\" + part, input, target, i + 1, curVal - cur, -cur); getExprUtil(res, curExp + \"*\" + part, input, target, i + 1, curVal - last + last * cur, last * cur); } } } // Below method returns all possible expression // evaluating to target function getExprs(input, target) { let res = []; getExprUtil(res, \"\", input, target, 0, 0, 0); return res; } // method to print result function printResult(res) { for (let i = 0; i < res.length; i++) document.write(res[i] + \" \"); document.write(\"</br>\"); } let input = \"123\"; let target = 6; let res = getExprs(input, target); printResult(res); input = \"125\"; target = 7; res = getExprs(input, target); printResult(res); // This code is contributed by decode2207.</script>",
"e": 14300,
"s": 11794,
"text": null
},
{
"code": null,
"e": 14310,
"s": 14300,
"text": "Output: "
},
{
"code": null,
"e": 14334,
"s": 14310,
"text": "1+2+3 1*2*3 \n1*2+5 12-5"
},
{
"code": null,
"e": 14800,
"s": 14334,
"text": "Time Complexity: O()Auxiliary Space: O(N) This article is contributed by Utkarsh Trivedi. 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. "
},
{
"code": null,
"e": 14817,
"s": 14800,
"text": "surinderdawra388"
},
{
"code": null,
"e": 14833,
"s": 14817,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 14849,
"s": 14833,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14860,
"s": 14849,
"text": "decode2207"
},
{
"code": null,
"e": 14874,
"s": 14860,
"text": "divyesh072019"
},
{
"code": null,
"e": 14888,
"s": 14874,
"text": "jainlovely450"
},
{
"code": null,
"e": 14899,
"s": 14888,
"text": "Algorithms"
},
{
"code": null,
"e": 14909,
"s": 14899,
"text": "Recursion"
},
{
"code": null,
"e": 14919,
"s": 14909,
"text": "Recursion"
},
{
"code": null,
"e": 14930,
"s": 14919,
"text": "Algorithms"
}
] |
Spring Boot – H2 Database
|
18 Feb, 2022
H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some basic operations in Spring Boot using H2 Database.
Some of the main features of the H2 Database are:
Very fast, open-source, JDBC API
Embedded and server modes; disk-based or in-memory databases
Transaction support, multi-version concurrency
Browser-based Console application
Encrypted databases
Fulltext search
Pure Java with a small footprint: around 2.5 MB jar file size
ODBC driver
Configure H2 Database in Spring Boot Application
Step 1: Adding the dependency
To use the H2 database in the spring boot application we have to add the following dependency in the pom.xml file:
dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Step 2: Write some properties in the application.properties file
# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Let’s understand what are these properties are by opening the H2 Database console.
H2 Console: By default, the console view of the H2 database is disabled. Before accessing the H2 database, we must enable it by using the following property.
spring.h2.console.enabled=true
Once we have enabled the H2 console, now we can access the H2 console in the browser by invoking the URL http://localhost:8082/h2-console.
Note: Provide your port number in which your spring application is running
The following figure shows the console view of the H2 database.
Example:
We are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the H2 Database.
Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project.
Step 2: Add the following dependency
Spring Web
H2 Database
Lombok
Spring Data JPA
Below is the complete code for the pom.xml file. Please check if you have missed something.
XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
Step 3: Create 4 packages and later create some classes and interfaces inside these packages as seen in the below image
entity
repository
service
controller
Note:
Green Rounded Icon ‘I’ Buttons are Interface
Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Create a simple POJO class inside the Department.java file.
Example:
Java
// Java Program to Demonstrate Department File // Importing required package modulespackage com.amiya.springbootdemoproject.entity; // Importing required classesimport javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}
Step 5: Inside the repository package
Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the CrudRepository as we have discussed above.
Example Below is the code for the DepartmentRepository.java file
Java
package com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interface extending CrudRepositorypublic interface DepartmentRepository extends CrudRepository<Department, Long> {}
Step 6: Inside the service package
Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl.
Example 1-A
Java
// Java Program to Demonstrate DepartmentService File // Importing required package modulespackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}
Example 1-B
Java
// Java Program to Demonstrate DepartmentServiceImpl.java// File // Importing required package modulespackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;import java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !"".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}
Step 7: Inside the controller package
Inside the package create one class named as DepartmentController.
Example
Java
// java Program to Illustrate DepartmentController File // Importing required packages modulespackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping("/departments") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping("/departments") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping("/departments/{id}") public Department updateDepartment(@RequestBody Department department, @PathVariable("id") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping("/departments/{id}") public String deleteDepartmentById(@PathVariable("id") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return "Deleted Successfully"; }}
Step 8: Below is the code for the application.properties file
server.port = 8082
# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database.
Endpoint 1: POST – http://localhost:8082/departments/
Endpoint 2: GET – http://localhost:8082/departments/
Endpoint 3: PUT – http://localhost:8082/departments/1
Endpoint 4: DELETE – http://localhost:8082/departments/1
Lastly, H2 Database is as depicted in the below media as follows:
sagartomar9927
kk9826225
Java-Spring-Boot
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Different ways of Reading a text file in Java
Constructors in Java
Strings in Java
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Hashtable in Java
Compare two Strings in Java
HashSet in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 378,
"s": 52,
"text": "H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some basic operations in Spring Boot using H2 Database."
},
{
"code": null,
"e": 428,
"s": 378,
"text": "Some of the main features of the H2 Database are:"
},
{
"code": null,
"e": 461,
"s": 428,
"text": "Very fast, open-source, JDBC API"
},
{
"code": null,
"e": 522,
"s": 461,
"text": "Embedded and server modes; disk-based or in-memory databases"
},
{
"code": null,
"e": 569,
"s": 522,
"text": "Transaction support, multi-version concurrency"
},
{
"code": null,
"e": 603,
"s": 569,
"text": "Browser-based Console application"
},
{
"code": null,
"e": 623,
"s": 603,
"text": "Encrypted databases"
},
{
"code": null,
"e": 639,
"s": 623,
"text": "Fulltext search"
},
{
"code": null,
"e": 701,
"s": 639,
"text": "Pure Java with a small footprint: around 2.5 MB jar file size"
},
{
"code": null,
"e": 713,
"s": 701,
"text": "ODBC driver"
},
{
"code": null,
"e": 762,
"s": 713,
"text": "Configure H2 Database in Spring Boot Application"
},
{
"code": null,
"e": 792,
"s": 762,
"text": "Step 1: Adding the dependency"
},
{
"code": null,
"e": 907,
"s": 792,
"text": "To use the H2 database in the spring boot application we have to add the following dependency in the pom.xml file:"
},
{
"code": null,
"e": 1037,
"s": 907,
"text": "dependency>\n <groupId>com.h2database</groupId>\n <artifactId>h2</artifactId>\n <scope>runtime</scope>\n </dependency>"
},
{
"code": null,
"e": 1102,
"s": 1037,
"text": "Step 2: Write some properties in the application.properties file"
},
{
"code": null,
"e": 1363,
"s": 1102,
"text": "# H2 Database\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:dcbapp\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=password\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect"
},
{
"code": null,
"e": 1447,
"s": 1363,
"text": "Let’s understand what are these properties are by opening the H2 Database console. "
},
{
"code": null,
"e": 1605,
"s": 1447,
"text": "H2 Console: By default, the console view of the H2 database is disabled. Before accessing the H2 database, we must enable it by using the following property."
},
{
"code": null,
"e": 1636,
"s": 1605,
"text": "spring.h2.console.enabled=true"
},
{
"code": null,
"e": 1776,
"s": 1636,
"text": "Once we have enabled the H2 console, now we can access the H2 console in the browser by invoking the URL http://localhost:8082/h2-console. "
},
{
"code": null,
"e": 1851,
"s": 1776,
"text": "Note: Provide your port number in which your spring application is running"
},
{
"code": null,
"e": 1915,
"s": 1851,
"text": "The following figure shows the console view of the H2 database."
},
{
"code": null,
"e": 1924,
"s": 1915,
"text": "Example:"
},
{
"code": null,
"e": 2040,
"s": 1924,
"text": "We are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the H2 Database."
},
{
"code": null,
"e": 2160,
"s": 2040,
"text": "Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. "
},
{
"code": null,
"e": 2197,
"s": 2160,
"text": "Step 2: Add the following dependency"
},
{
"code": null,
"e": 2208,
"s": 2197,
"text": "Spring Web"
},
{
"code": null,
"e": 2220,
"s": 2208,
"text": "H2 Database"
},
{
"code": null,
"e": 2227,
"s": 2220,
"text": "Lombok"
},
{
"code": null,
"e": 2243,
"s": 2227,
"text": "Spring Data JPA"
},
{
"code": null,
"e": 2335,
"s": 2243,
"text": "Below is the complete code for the pom.xml file. Please check if you have missed something."
},
{
"code": null,
"e": 2339,
"s": 2335,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>",
"e": 4797,
"s": 2339,
"text": null
},
{
"code": null,
"e": 4919,
"s": 4797,
"text": " Step 3: Create 4 packages and later create some classes and interfaces inside these packages as seen in the below image "
},
{
"code": null,
"e": 4926,
"s": 4919,
"text": "entity"
},
{
"code": null,
"e": 4937,
"s": 4926,
"text": "repository"
},
{
"code": null,
"e": 4945,
"s": 4937,
"text": "service"
},
{
"code": null,
"e": 4956,
"s": 4945,
"text": "controller"
},
{
"code": null,
"e": 4962,
"s": 4956,
"text": "Note:"
},
{
"code": null,
"e": 5007,
"s": 4962,
"text": "Green Rounded Icon ‘I’ Buttons are Interface"
},
{
"code": null,
"e": 5049,
"s": 5007,
"text": "Blue Rounded Icon ‘C’ Buttons are Classes"
},
{
"code": null,
"e": 5083,
"s": 5049,
"text": "Step 4: Inside the entity package"
},
{
"code": null,
"e": 5144,
"s": 5083,
"text": "Create a simple POJO class inside the Department.java file. "
},
{
"code": null,
"e": 5154,
"s": 5144,
"text": "Example: "
},
{
"code": null,
"e": 5159,
"s": 5154,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Department File // Importing required package modulespackage com.amiya.springbootdemoproject.entity; // Importing required classesimport javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}",
"e": 5854,
"s": 5159,
"text": null
},
{
"code": null,
"e": 5893,
"s": 5854,
"text": " Step 5: Inside the repository package"
},
{
"code": null,
"e": 6048,
"s": 5893,
"text": "Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the CrudRepository as we have discussed above."
},
{
"code": null,
"e": 6114,
"s": 6048,
"text": "Example Below is the code for the DepartmentRepository.java file "
},
{
"code": null,
"e": 6119,
"s": 6114,
"text": "Java"
},
{
"code": "package com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interface extending CrudRepositorypublic interface DepartmentRepository extends CrudRepository<Department, Long> {}",
"e": 6483,
"s": 6119,
"text": null
},
{
"code": null,
"e": 6519,
"s": 6483,
"text": " Step 6: Inside the service package"
},
{
"code": null,
"e": 6633,
"s": 6519,
"text": "Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. "
},
{
"code": null,
"e": 6646,
"s": 6633,
"text": "Example 1-A "
},
{
"code": null,
"e": 6651,
"s": 6646,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate DepartmentService File // Importing required package modulespackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}",
"e": 7291,
"s": 6651,
"text": null
},
{
"code": null,
"e": 7305,
"s": 7291,
"text": " Example 1-B "
},
{
"code": null,
"e": 7310,
"s": 7305,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate DepartmentServiceImpl.java// File // Importing required package modulespackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;import java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !\"\".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !\"\".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !\"\".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}",
"e": 9444,
"s": 7310,
"text": null
},
{
"code": null,
"e": 9483,
"s": 9444,
"text": " Step 7: Inside the controller package"
},
{
"code": null,
"e": 9551,
"s": 9483,
"text": "Inside the package create one class named as DepartmentController. "
},
{
"code": null,
"e": 9561,
"s": 9551,
"text": "Example "
},
{
"code": null,
"e": 9566,
"s": 9561,
"text": "Java"
},
{
"code": "// java Program to Illustrate DepartmentController File // Importing required packages modulespackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping(\"/departments\") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping(\"/departments\") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping(\"/departments/{id}\") public Department updateDepartment(@RequestBody Department department, @PathVariable(\"id\") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping(\"/departments/{id}\") public String deleteDepartmentById(@PathVariable(\"id\") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return \"Deleted Successfully\"; }}",
"e": 11132,
"s": 9566,
"text": null
},
{
"code": null,
"e": 11196,
"s": 11132,
"text": " Step 8: Below is the code for the application.properties file "
},
{
"code": null,
"e": 11477,
"s": 11196,
"text": "server.port = 8082\n\n# H2 Database\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:dcbapp\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=password\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect"
},
{
"code": null,
"e": 11578,
"s": 11477,
"text": "Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database. "
},
{
"code": null,
"e": 11633,
"s": 11578,
"text": "Endpoint 1: POST – http://localhost:8082/departments/ "
},
{
"code": null,
"e": 11687,
"s": 11633,
"text": "Endpoint 2: GET – http://localhost:8082/departments/ "
},
{
"code": null,
"e": 11742,
"s": 11687,
"text": "Endpoint 3: PUT – http://localhost:8082/departments/1 "
},
{
"code": null,
"e": 11800,
"s": 11742,
"text": "Endpoint 4: DELETE – http://localhost:8082/departments/1 "
},
{
"code": null,
"e": 11867,
"s": 11800,
"text": "Lastly, H2 Database is as depicted in the below media as follows: "
},
{
"code": null,
"e": 11884,
"s": 11869,
"text": "sagartomar9927"
},
{
"code": null,
"e": 11894,
"s": 11884,
"text": "kk9826225"
},
{
"code": null,
"e": 11911,
"s": 11894,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 11918,
"s": 11911,
"text": "Picked"
},
{
"code": null,
"e": 11923,
"s": 11918,
"text": "Java"
},
{
"code": null,
"e": 11928,
"s": 11923,
"text": "Java"
},
{
"code": null,
"e": 12026,
"s": 11928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12063,
"s": 12026,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 12109,
"s": 12063,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 12130,
"s": 12109,
"text": "Constructors in Java"
},
{
"code": null,
"e": 12146,
"s": 12130,
"text": "Strings in Java"
},
{
"code": null,
"e": 12183,
"s": 12146,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 12223,
"s": 12183,
"text": "How to Create Array of Objects in Java?"
},
{
"code": null,
"e": 12241,
"s": 12223,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 12269,
"s": 12241,
"text": "Compare two Strings in Java"
},
{
"code": null,
"e": 12285,
"s": 12269,
"text": "HashSet in Java"
}
] |
Python Dictionary items() method
|
04 Dec, 2020
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values.
Syntax: dictionary.items()Parameters: This method takes no parameters.Returns: A view object that displays a list of a given dictionary’s (key, value) tuple pair.
Example #1:
Python3
# Python program to show working# of items() method in Dictionary # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' } print("Dictionary items:") # Printing all the items of the Dictionaryprint(Dictionary1.items())
Output:
Dictionary items:
dict_items([('A', 'Geeks'), ('B', 4), ('C', 'Geeks')])
Order of these items in the list may not always be same. Example #2: To show working of items() after modification of Dictionary.
Python3
# Python program to show working# of items() method in Dictionary # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' } print("Original Dictionary items:") items = Dictionary1.items() # Printing all the items of the Dictionaryprint(items) # Delete an item from dictionarydel[Dictionary1['C']]print('Updated Dictionary:')print(items)
Output:
Original Dictionary items:
dict_items([('A', 'Geeks'), ('C', 'Geeks'), ('B', 4)])
Updated Dictionary:
dict_items([('A', 'Geeks'), ('B', 4)])
If the Dictionary is updated anytime, the changes are reflected in the view object automatically.
001amankumar
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 365,
"s": 53,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. "
},
{
"code": null,
"e": 528,
"s": 365,
"text": "Syntax: dictionary.items()Parameters: This method takes no parameters.Returns: A view object that displays a list of a given dictionary’s (key, value) tuple pair."
},
{
"code": null,
"e": 542,
"s": 528,
"text": "Example #1: "
},
{
"code": null,
"e": 550,
"s": 542,
"text": "Python3"
},
{
"code": "# Python program to show working# of items() method in Dictionary # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' } print(\"Dictionary items:\") # Printing all the items of the Dictionaryprint(Dictionary1.items())",
"e": 798,
"s": 550,
"text": null
},
{
"code": null,
"e": 808,
"s": 798,
"text": "Output: "
},
{
"code": null,
"e": 883,
"s": 808,
"text": "Dictionary items:\ndict_items([('A', 'Geeks'), ('B', 4), ('C', 'Geeks')])\n\n"
},
{
"code": null,
"e": 1017,
"s": 883,
"text": "Order of these items in the list may not always be same. Example #2: To show working of items() after modification of Dictionary. "
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "Python3"
},
{
"code": "# Python program to show working# of items() method in Dictionary # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' } print(\"Original Dictionary items:\") items = Dictionary1.items() # Printing all the items of the Dictionaryprint(items) # Delete an item from dictionarydel[Dictionary1['C']]print('Updated Dictionary:')print(items)",
"e": 1392,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1402,
"s": 1392,
"text": "Output: "
},
{
"code": null,
"e": 1545,
"s": 1402,
"text": "Original Dictionary items:\ndict_items([('A', 'Geeks'), ('C', 'Geeks'), ('B', 4)])\nUpdated Dictionary:\ndict_items([('A', 'Geeks'), ('B', 4)])\n\n"
},
{
"code": null,
"e": 1644,
"s": 1545,
"text": "If the Dictionary is updated anytime, the changes are reflected in the view object automatically. "
},
{
"code": null,
"e": 1657,
"s": 1644,
"text": "001amankumar"
},
{
"code": null,
"e": 1669,
"s": 1657,
"text": "python-dict"
},
{
"code": null,
"e": 1691,
"s": 1669,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 1698,
"s": 1691,
"text": "Python"
},
{
"code": null,
"e": 1710,
"s": 1698,
"text": "python-dict"
},
{
"code": null,
"e": 1808,
"s": 1710,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1836,
"s": 1808,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1886,
"s": 1836,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1908,
"s": 1886,
"text": "Python map() function"
},
{
"code": null,
"e": 1926,
"s": 1908,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1970,
"s": 1926,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2012,
"s": 1970,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2035,
"s": 2012,
"text": "Taking input in Python"
},
{
"code": null,
"e": 2057,
"s": 2035,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2092,
"s": 2057,
"text": "Read a file line by line in Python"
}
] |
How to clear all options in a dropdown box?
|
27 Sep, 2019
Clearing the entire dropdown list is pretty easy, all we have to do is to create a button, which calls a function that performs the deletion.Let’s look at the syntax of the deletion part:
document.getElementById("idofdropdownlist").innerHTML = "";
Here, it gets all the elements present in the given Id and clears then by assigning all the objects null, if not assigned to null, still object remains.Approach 1: Check out the code:
<!DOCTYPE html><html> <body> <p>Which character is your favorite guardian?</p> <select id="guardian"> <!--dropdown list with id=guardian--> <option>Guardians</option> <option>Quill</option> <option>Gamora</option> <option>Drax</option> <option>rocket</option> <option>groot</option> <option>mantis</option> </select> <input type="button" onclick="myFunction()" value="Only IronMan clear them all" /> <!––Button which avokes myFuction()--> <script> function myFunction() { //clears all the guardians with the specified id document.getElementById("guardian").innerHTML = null; } </script></body> </html>
Output:
Approach 2:This process not only removes the option but also removes the dropdown box too.Check out the code:
<html> <body> <p>Which character is your favorite guardian?</p> <select id="guardian"> <!--dropdown list with id=guardian--> <option>Guardians</option> <option>Quill</option> <option>Gamora</option> <option>Drax</option> <option>rocket</option> <option>groot</option> <option>mantis</option> </select> <input type="button" onclick="myFunction()" value="Only IronMan clear them all"> <!––Button which avokes myFuction()--> <script> function myFunction() { //process the options in a loop and removes them document.querySelectorAll( '#guardian').forEach(guardian => guardian.remove()) //here, guardian inside the for is a variable not id. } </script></body> </html>
Output:
These methods work on all browsers.
Picked
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "Clearing the entire dropdown list is pretty easy, all we have to do is to create a button, which calls a function that performs the deletion.Let’s look at the syntax of the deletion part:"
},
{
"code": null,
"e": 276,
"s": 216,
"text": "document.getElementById(\"idofdropdownlist\").innerHTML = \"\";"
},
{
"code": null,
"e": 460,
"s": 276,
"text": "Here, it gets all the elements present in the given Id and clears then by assigning all the objects null, if not assigned to null, still object remains.Approach 1: Check out the code:"
},
{
"code": "<!DOCTYPE html><html> <body> <p>Which character is your favorite guardian?</p> <select id=\"guardian\"> <!--dropdown list with id=guardian--> <option>Guardians</option> <option>Quill</option> <option>Gamora</option> <option>Drax</option> <option>rocket</option> <option>groot</option> <option>mantis</option> </select> <input type=\"button\" onclick=\"myFunction()\" value=\"Only IronMan clear them all\" /> <!––Button which avokes myFuction()--> <script> function myFunction() { //clears all the guardians with the specified id document.getElementById(\"guardian\").innerHTML = null; } </script></body> </html>",
"e": 1294,
"s": 460,
"text": null
},
{
"code": null,
"e": 1302,
"s": 1294,
"text": "Output:"
},
{
"code": null,
"e": 1412,
"s": 1302,
"text": "Approach 2:This process not only removes the option but also removes the dropdown box too.Check out the code:"
},
{
"code": "<html> <body> <p>Which character is your favorite guardian?</p> <select id=\"guardian\"> <!--dropdown list with id=guardian--> <option>Guardians</option> <option>Quill</option> <option>Gamora</option> <option>Drax</option> <option>rocket</option> <option>groot</option> <option>mantis</option> </select> <input type=\"button\" onclick=\"myFunction()\" value=\"Only IronMan clear them all\"> <!––Button which avokes myFuction()--> <script> function myFunction() { //process the options in a loop and removes them document.querySelectorAll( '#guardian').forEach(guardian => guardian.remove()) //here, guardian inside the for is a variable not id. } </script></body> </html>",
"e": 2249,
"s": 1412,
"text": null
},
{
"code": null,
"e": 2257,
"s": 2249,
"text": "Output:"
},
{
"code": null,
"e": 2293,
"s": 2257,
"text": "These methods work on all browsers."
},
{
"code": null,
"e": 2300,
"s": 2293,
"text": "Picked"
},
{
"code": null,
"e": 2311,
"s": 2300,
"text": "JavaScript"
},
{
"code": null,
"e": 2328,
"s": 2311,
"text": "Web Technologies"
},
{
"code": null,
"e": 2355,
"s": 2328,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2453,
"s": 2355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2514,
"s": 2453,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2586,
"s": 2514,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2626,
"s": 2586,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2678,
"s": 2626,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2719,
"s": 2678,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2781,
"s": 2719,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2814,
"s": 2781,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2875,
"s": 2814,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2925,
"s": 2875,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
int Keyword in C#
|
22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.Int32.
Syntax:
int variable_name = value;
Int keyword occupies 4 bytes (32 bits) space in the memory.
Example:
Input: num: -245
Output: num: -245
Size of an int variable: 4
Input: num = 7923645
Output: Type of num: System.Int32
num: 7923645
Size of a int variable: 4
Example 1:
// C# program for int keywordusing System;using System.Text; class geeks { static void Main(string[] args) { // variable declaration int num = -245; // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a int variable: " + sizeof(int)); }}
Output:
num: -245
Size of a int variable: 4
Example 2:
// C# program for int keywordusing System;using System.Text; namespace Test { class geeks { static void Main(string[] args) { // variable declaration int num = 7923645; // to print type of variable Console.WriteLine("Type of num: " + num.GetType()); // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a int variable: " + sizeof(int)); // to print minimum & maximum value of int Console.WriteLine("Min value of int: " + int.MinValue); Console.WriteLine("Max value of int: " + int.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}
Output:
Type of num: System.Int32
num: 7923645
Size of a int variable: 4
Min value of int: -2147483648
Max value of int: 2147483647
Example 3:
// C# program for int keywordusing System;using System.Text; class geeks { static void Main(string[] args) { // variable declaration int num1 = 2147483650; // to print value Console.WriteLine("num1: " + num1); // variable declaration int num = 792.53; // to print value Console.WriteLine("num: " + num); }}
Error: When we input wrong integer and also input number beyond the range
Constant value `2147483650′ cannot be converted to a `int’Cannot implicitly convert type `double’ to `int’
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 334,
"s": 28,
"text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.Int32."
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Syntax:"
},
{
"code": null,
"e": 369,
"s": 342,
"text": "int variable_name = value;"
},
{
"code": null,
"e": 429,
"s": 369,
"text": "Int keyword occupies 4 bytes (32 bits) space in the memory."
},
{
"code": null,
"e": 438,
"s": 429,
"text": "Example:"
},
{
"code": null,
"e": 622,
"s": 438,
"text": "Input: num: -245\n\nOutput: num: -245\n Size of an int variable: 4\n\nInput: num = 7923645\n\nOutput: Type of num: System.Int32\n num: 7923645\n Size of a int variable: 4\n"
},
{
"code": null,
"e": 633,
"s": 622,
"text": "Example 1:"
},
{
"code": "// C# program for int keywordusing System;using System.Text; class geeks { static void Main(string[] args) { // variable declaration int num = -245; // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a int variable: \" + sizeof(int)); }}",
"e": 973,
"s": 633,
"text": null
},
{
"code": null,
"e": 981,
"s": 973,
"text": "Output:"
},
{
"code": null,
"e": 1018,
"s": 981,
"text": "num: -245\nSize of a int variable: 4\n"
},
{
"code": null,
"e": 1029,
"s": 1018,
"text": "Example 2:"
},
{
"code": "// C# program for int keywordusing System;using System.Text; namespace Test { class geeks { static void Main(string[] args) { // variable declaration int num = 7923645; // to print type of variable Console.WriteLine(\"Type of num: \" + num.GetType()); // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a int variable: \" + sizeof(int)); // to print minimum & maximum value of int Console.WriteLine(\"Min value of int: \" + int.MinValue); Console.WriteLine(\"Max value of int: \" + int.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}",
"e": 1723,
"s": 1029,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1723,
"text": "Output:"
},
{
"code": null,
"e": 1856,
"s": 1731,
"text": "Type of num: System.Int32\nnum: 7923645\nSize of a int variable: 4\nMin value of int: -2147483648\nMax value of int: 2147483647\n"
},
{
"code": null,
"e": 1867,
"s": 1856,
"text": "Example 3:"
},
{
"code": "// C# program for int keywordusing System;using System.Text; class geeks { static void Main(string[] args) { // variable declaration int num1 = 2147483650; // to print value Console.WriteLine(\"num1: \" + num1); // variable declaration int num = 792.53; // to print value Console.WriteLine(\"num: \" + num); }}",
"e": 2250,
"s": 1867,
"text": null
},
{
"code": null,
"e": 2324,
"s": 2250,
"text": "Error: When we input wrong integer and also input number beyond the range"
},
{
"code": null,
"e": 2431,
"s": 2324,
"text": "Constant value `2147483650′ cannot be converted to a `int’Cannot implicitly convert type `double’ to `int’"
},
{
"code": null,
"e": 2446,
"s": 2431,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 2449,
"s": 2446,
"text": "C#"
},
{
"code": null,
"e": 2547,
"s": 2449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2590,
"s": 2547,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2639,
"s": 2590,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2662,
"s": 2639,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2678,
"s": 2662,
"text": "C# | List Class"
},
{
"code": null,
"e": 2706,
"s": 2678,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 2767,
"s": 2706,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 2790,
"s": 2767,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 2815,
"s": 2790,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 2837,
"s": 2815,
"text": "Partial Classes in C#"
}
] |
PostgreSQL – DISTINCT ON expression
|
07 Oct, 2021
PostgreSQL also provides on an expression as DISTINCT ON that is used with the SELECT statement to remove duplicates from a query set result just like the DISTINCT clause.In addition to that it also keeps the “first row” of each row of duplicates in the query set result.
Syntax: SELECT DISTINCT ON (column_1) column_alias, column_2 FROM table_name ORDER BY column_1, column_2;
As the order of rows returned from the SELECT statement is unpredictable which means the “first row” of each group of the duplicate is also unpredictable. It is good practice to use the ORDER BY clause with the DISTINCT ON(expression) to make the result set in the desired order.
Note: The DISTINCT ON expression must always match the leftmost expression in the ORDER BY clause.
Now, let’s look into a few examples for better understanding. For the sake of example, we will create a sample database as explained below:
Create a database(say, Favourite_colours) using the commands shown below:
CREATE DATABASE Favourite_colours;
Now add a table(say, my_table) with columns(say, id, colour_1 and colour_2) to the database using the command below:
CREATE TABLE my_table(
id serial NOT NULL PRIMARY KEY,
colour_1 VARCHAR,
colour_2 VARCHAR
);
Now insert some data in the table that we just added to our database using the command below:
INSERT INTO my_table(colour_1, colour_2)
VALUES
('red', 'red'),
('red', 'red'),
('red', NULL),
(NULL, 'red'),
('red', 'green'),
('red', 'blue'),
('green', 'red'),
('green', 'blue'),
('green', 'green'),
('blue', 'red'),
('blue', 'green'),
('blue', 'blue');
Now check if everything is as intended by making a query as below:
SELECT
id,
colour_1,
colour_2
FROM
my_table;
If everything is as intended, the output will be like as shown below:
Since, our database is good to go, we move onto the implementation of the SELECT DISTINCT ON expression.
Example 1:
SELECT
DISTINCT ON
(colour_1) colour_1,
colour_2
FROM
my_table
ORDER BY
colour_1,
colour_2;
Output:
Example 2: Notice the change in the query set result order.
SELECT
DISTINCT ON
(colour_2) colour_2,
colour_1
FROM
my_table
ORDER BY
colour_2,
colour_1;
Output:
akshaysingh98088
postgreSQL-constraints
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "PostgreSQL also provides on an expression as DISTINCT ON that is used with the SELECT statement to remove duplicates from a query set result just like the DISTINCT clause.In addition to that it also keeps the “first row” of each row of duplicates in the query set result. "
},
{
"code": null,
"e": 409,
"s": 303,
"text": "Syntax: SELECT DISTINCT ON (column_1) column_alias, column_2 FROM table_name ORDER BY column_1, column_2;"
},
{
"code": null,
"e": 692,
"s": 411,
"text": "As the order of rows returned from the SELECT statement is unpredictable which means the “first row” of each group of the duplicate is also unpredictable. It is good practice to use the ORDER BY clause with the DISTINCT ON(expression) to make the result set in the desired order. "
},
{
"code": null,
"e": 792,
"s": 692,
"text": "Note: The DISTINCT ON expression must always match the leftmost expression in the ORDER BY clause. "
},
{
"code": null,
"e": 933,
"s": 792,
"text": "Now, let’s look into a few examples for better understanding. For the sake of example, we will create a sample database as explained below: "
},
{
"code": null,
"e": 1009,
"s": 933,
"text": "Create a database(say, Favourite_colours) using the commands shown below: "
},
{
"code": null,
"e": 1044,
"s": 1009,
"text": "CREATE DATABASE Favourite_colours;"
},
{
"code": null,
"e": 1162,
"s": 1044,
"text": "Now add a table(say, my_table) with columns(say, id, colour_1 and colour_2) to the database using the command below: "
},
{
"code": null,
"e": 1269,
"s": 1164,
"text": "CREATE TABLE my_table(\n id serial NOT NULL PRIMARY KEY,\n colour_1 VARCHAR,\n colour_2 VARCHAR\n);"
},
{
"code": null,
"e": 1365,
"s": 1269,
"text": "Now insert some data in the table that we just added to our database using the command below: "
},
{
"code": null,
"e": 1669,
"s": 1365,
"text": "INSERT INTO my_table(colour_1, colour_2)\nVALUES\n ('red', 'red'),\n ('red', 'red'),\n ('red', NULL),\n (NULL, 'red'),\n ('red', 'green'),\n ('red', 'blue'),\n ('green', 'red'),\n ('green', 'blue'),\n ('green', 'green'),\n ('blue', 'red'),\n ('blue', 'green'),\n ('blue', 'blue');"
},
{
"code": null,
"e": 1738,
"s": 1669,
"text": "Now check if everything is as intended by making a query as below: "
},
{
"code": null,
"e": 1799,
"s": 1738,
"text": "SELECT\n id,\n colour_1,\n colour_2\nFROM\n my_table;"
},
{
"code": null,
"e": 1871,
"s": 1799,
"text": "If everything is as intended, the output will be like as shown below: "
},
{
"code": null,
"e": 1977,
"s": 1871,
"text": "Since, our database is good to go, we move onto the implementation of the SELECT DISTINCT ON expression. "
},
{
"code": null,
"e": 1990,
"s": 1977,
"text": "Example 1: "
},
{
"code": null,
"e": 2106,
"s": 1990,
"text": "SELECT\n DISTINCT ON\n (colour_1) colour_1,\n colour_2\nFROM\n my_table\nORDER BY\n colour_1,\n colour_2;"
},
{
"code": null,
"e": 2116,
"s": 2106,
"text": "Output: "
},
{
"code": null,
"e": 2177,
"s": 2116,
"text": "Example 2: Notice the change in the query set result order. "
},
{
"code": null,
"e": 2295,
"s": 2179,
"text": "SELECT\n DISTINCT ON\n (colour_2) colour_2,\n colour_1\nFROM\n my_table\nORDER BY\n colour_2,\n colour_1;"
},
{
"code": null,
"e": 2304,
"s": 2295,
"text": "Output: "
},
{
"code": null,
"e": 2325,
"s": 2308,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2348,
"s": 2325,
"text": "postgreSQL-constraints"
},
{
"code": null,
"e": 2359,
"s": 2348,
"text": "PostgreSQL"
}
] |
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) - GeeksforGeeks
|
28 Jul, 2016
Some of the mathematical functions are discussed in below set 1 and set 2
Mathematical Functions in Python | Set 1 (Numeric Functions)Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Trigonometric and angular functions are discussed in this article.
1. sin() :- This function returns the sine of value passed as argument. The value passed in this function should be in radians.
2. cos() :- This function returns the cosine of value passed as argument. The value passed in this function should be in radians.
# Python code to demonstrate the working of# sin() and cos() # importing "math" for mathematical operationsimport math a = math.pi/6 # returning the value of sine of pi/6print ("The value of sine of pi/6 is : ", end="")print (math.sin(a)) # returning the value of cosine of pi/6print ("The value of cosine of pi/6 is : ", end="")print (math.cos(a))
Output:
The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
3. tan() :- This function returns the tangent of value passed as argument. The value passed in this function should be in radians.
4. hypot(a, b) :- This returns the hypotenuse of the values passed in arguments. Numerically, it returns the value of sqrt(a*a + b*b).
# Python code to demonstrate the working of# tan() and hypot() # importing "math" for mathematical operationsimport math a = math.pi/6b = 3c = 4 # returning the value of tangent of pi/6print ("The value of tangent of pi/6 is : ", end="")print (math.tan(a)) # returning the value of hypotenuse of 3 and 4print ("The value of hypotenuse of 3 and 4 is : ", end="")print (math.hypot(b,c))
Output:
The value of tangent of pi/6 is : 0.5773502691896257
The value of hypotenuse of 3 and 4 is : 5.0
5. degrees() :- This function is used to convert argument value from radians to degrees.
6. radians() :- This function is used to convert argument value from degrees to radians.
# Python code to demonstrate the working of# degrees() and radians() # importing "math" for mathematical operationsimport math a = math.pi/6b = 30 # returning the converted value from radians to degreesprint ("The converted value from radians to degrees is : ", end="")print (math.degrees(a)) # returning the converted value from degrees to radiansprint ("The converted value from degrees to radians is : ", end="")print (math.radians(b))
Output:
The converted value from radians to degrees is : 29.999999999999996
The converted value from degrees to radians is : 0.5235987755982988
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24530,
"s": 24502,
"text": "\n28 Jul, 2016"
},
{
"code": null,
"e": 24604,
"s": 24530,
"text": "Some of the mathematical functions are discussed in below set 1 and set 2"
},
{
"code": null,
"e": 24739,
"s": 24604,
"text": "Mathematical Functions in Python | Set 1 (Numeric Functions)Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)"
},
{
"code": null,
"e": 24806,
"s": 24739,
"text": "Trigonometric and angular functions are discussed in this article."
},
{
"code": null,
"e": 24934,
"s": 24806,
"text": "1. sin() :- This function returns the sine of value passed as argument. The value passed in this function should be in radians."
},
{
"code": null,
"e": 25064,
"s": 24934,
"text": "2. cos() :- This function returns the cosine of value passed as argument. The value passed in this function should be in radians."
},
{
"code": "# Python code to demonstrate the working of# sin() and cos() # importing \"math\" for mathematical operationsimport math a = math.pi/6 # returning the value of sine of pi/6print (\"The value of sine of pi/6 is : \", end=\"\")print (math.sin(a)) # returning the value of cosine of pi/6print (\"The value of cosine of pi/6 is : \", end=\"\")print (math.cos(a))",
"e": 25420,
"s": 25064,
"text": null
},
{
"code": null,
"e": 25428,
"s": 25420,
"text": "Output:"
},
{
"code": null,
"e": 25532,
"s": 25428,
"text": "The value of sine of pi/6 is : 0.49999999999999994\nThe value of cosine of pi/6 is : 0.8660254037844387\n"
},
{
"code": null,
"e": 25663,
"s": 25532,
"text": "3. tan() :- This function returns the tangent of value passed as argument. The value passed in this function should be in radians."
},
{
"code": null,
"e": 25798,
"s": 25663,
"text": "4. hypot(a, b) :- This returns the hypotenuse of the values passed in arguments. Numerically, it returns the value of sqrt(a*a + b*b)."
},
{
"code": "# Python code to demonstrate the working of# tan() and hypot() # importing \"math\" for mathematical operationsimport math a = math.pi/6b = 3c = 4 # returning the value of tangent of pi/6print (\"The value of tangent of pi/6 is : \", end=\"\")print (math.tan(a)) # returning the value of hypotenuse of 3 and 4print (\"The value of hypotenuse of 3 and 4 is : \", end=\"\")print (math.hypot(b,c))",
"e": 26190,
"s": 25798,
"text": null
},
{
"code": null,
"e": 26198,
"s": 26190,
"text": "Output:"
},
{
"code": null,
"e": 26296,
"s": 26198,
"text": "The value of tangent of pi/6 is : 0.5773502691896257\nThe value of hypotenuse of 3 and 4 is : 5.0\n"
},
{
"code": null,
"e": 26385,
"s": 26296,
"text": "5. degrees() :- This function is used to convert argument value from radians to degrees."
},
{
"code": null,
"e": 26474,
"s": 26385,
"text": "6. radians() :- This function is used to convert argument value from degrees to radians."
},
{
"code": "# Python code to demonstrate the working of# degrees() and radians() # importing \"math\" for mathematical operationsimport math a = math.pi/6b = 30 # returning the converted value from radians to degreesprint (\"The converted value from radians to degrees is : \", end=\"\")print (math.degrees(a)) # returning the converted value from degrees to radiansprint (\"The converted value from degrees to radians is : \", end=\"\")print (math.radians(b))",
"e": 26920,
"s": 26474,
"text": null
},
{
"code": null,
"e": 26928,
"s": 26920,
"text": "Output:"
},
{
"code": null,
"e": 27065,
"s": 26928,
"text": "The converted value from radians to degrees is : 29.999999999999996\nThe converted value from degrees to radians is : 0.5235987755982988\n"
},
{
"code": null,
"e": 27366,
"s": 27065,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27491,
"s": 27366,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27498,
"s": 27491,
"text": "Python"
},
{
"code": null,
"e": 27596,
"s": 27498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27605,
"s": 27596,
"text": "Comments"
},
{
"code": null,
"e": 27618,
"s": 27605,
"text": "Old Comments"
},
{
"code": null,
"e": 27650,
"s": 27618,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27685,
"s": 27650,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27707,
"s": 27685,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27737,
"s": 27707,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27779,
"s": 27737,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27822,
"s": 27779,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27859,
"s": 27822,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27885,
"s": 27859,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27929,
"s": 27885,
"text": "Reading and Writing to text files in Python"
}
] |
Batch Script - TITLE
|
This batch command sets the title displayed in the console window.
TITLE [Tilename]
Where tilename is the new name to be given to the title of the command prompt window.
@echo off
Title “New Windows Title”
The above command will change the title of the window to “New Windows Title”.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2236,
"s": 2169,
"text": "This batch command sets the title displayed in the console window."
},
{
"code": null,
"e": 2254,
"s": 2236,
"text": "TITLE [Tilename]\n"
},
{
"code": null,
"e": 2340,
"s": 2254,
"text": "Where tilename is the new name to be given to the title of the command prompt window."
},
{
"code": null,
"e": 2377,
"s": 2340,
"text": "@echo off \nTitle “New Windows Title”"
},
{
"code": null,
"e": 2455,
"s": 2377,
"text": "The above command will change the title of the window to “New Windows Title”."
},
{
"code": null,
"e": 2462,
"s": 2455,
"text": " Print"
},
{
"code": null,
"e": 2473,
"s": 2462,
"text": " Add Notes"
}
] |
What is Stale Element Reference Exception in Selenium Webdriver & How To Fix It?
|
We may encounter StaleElementReferenceException while working with Selenium webdriver. We can fix the StaleElementReferenceException in the Selenium webdriver. The term stale means something which is not fresh and decayed. Thus a stale element points to an element that is not present anymore.
There may be a case when an element was in DOM initially but after modifications in Document Object Model (DOM), the element becomes stale and the StaleElementReferenceException is thrown if we attempt to access this element.
This exception is caused whenever an element is not present in the DOM or deleted. We can handle this exception in the following ways −
Refreshing the page and verifying again.
Implement the retry method.
Code Implementation to illustrate StaleElementException.
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 StaleElmnt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//application launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement l = driver.findElement(By.id("gsc-i-id1"));
//enter text
l.sendKeys("Selenium");
//refresh page
driver.navigate().refresh();
//again enter text
l.sendKeys("Selenium");
//browser quit
driver.quit();
}
}
Code Implementation to fix the StaleElementException.
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;
import org.openqa.selenium.StaleElementReferenceException;
public class StaleElmntFix{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//application launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement l = driver.findElement(By.id("gsc-i-id1"));
//enter text
l.sendKeys("Selenium");
//refresh page
driver.navigate().refresh();
//fix exception with try-catch block
try{
l.sendKeys("Selenium");
}
catch(StaleElementReferenceException e){
l = driver.findElement(By.id("gsc-i-id1"));
l.sendKeys("Selenium");
//obtain value entered
String s= l.getAttribute("value");
System.out.println("Value entered is: " +s);
}
driver.quit();
}
}
|
[
{
"code": null,
"e": 1356,
"s": 1062,
"text": "We may encounter StaleElementReferenceException while working with Selenium webdriver. We can fix the StaleElementReferenceException in the Selenium webdriver. The term stale means something which is not fresh and decayed. Thus a stale element points to an element that is not present anymore."
},
{
"code": null,
"e": 1582,
"s": 1356,
"text": "There may be a case when an element was in DOM initially but after modifications in Document Object Model (DOM), the element becomes stale and the StaleElementReferenceException is thrown if we attempt to access this element."
},
{
"code": null,
"e": 1718,
"s": 1582,
"text": "This exception is caused whenever an element is not present in the DOM or deleted. We can handle this exception in the following ways −"
},
{
"code": null,
"e": 1759,
"s": 1718,
"text": "Refreshing the page and verifying again."
},
{
"code": null,
"e": 1787,
"s": 1759,
"text": "Implement the retry method."
},
{
"code": null,
"e": 1844,
"s": 1787,
"text": "Code Implementation to illustrate StaleElementException."
},
{
"code": null,
"e": 2758,
"s": 1844,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class StaleElmnt{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n //application launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n\n // identify element\n WebElement l = driver.findElement(By.id(\"gsc-i-id1\"));\n\n //enter text\n l.sendKeys(\"Selenium\");\n\n //refresh page\n driver.navigate().refresh();\n\n //again enter text\n l.sendKeys(\"Selenium\");\n\n //browser quit\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 2812,
"s": 2758,
"text": "Code Implementation to fix the StaleElementException."
},
{
"code": null,
"e": 4078,
"s": 2812,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.StaleElementReferenceException;\npublic class StaleElmntFix{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n //application launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n\n // identify element\n WebElement l = driver.findElement(By.id(\"gsc-i-id1\"));\n\n //enter text\n l.sendKeys(\"Selenium\");\n\n //refresh page\n driver.navigate().refresh();\n\n //fix exception with try-catch block\n try{\n l.sendKeys(\"Selenium\");\n }\n catch(StaleElementReferenceException e){\n l = driver.findElement(By.id(\"gsc-i-id1\"));\n l.sendKeys(\"Selenium\");\n\n //obtain value entered\n String s= l.getAttribute(\"value\");\n System.out.println(\"Value entered is: \" +s);\n }\n driver.quit();\n }\n}"
}
] |
Finding Mean, Median, Mode in Python without libraries - GeeksforGeeks
|
27 May, 2020
In this article, we will learn how to calculate Mean, Median, and Mode with Python without using external libraries.
Mean : The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers:# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print("Mean / Average is: " + str(mean))Output:Mean / Average is: 3.0
We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.Median : The median is the middle number in a group of numbers. This code calculates Median of a list containing numbers:# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print("Median is: " + str(median))Output:Median is: 3
We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers:# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = "No mode found"else: get_mode = "Mode is / are: " + ', '.join(map(str, mode)) print(get_mode)Output:Mode is / are: 5
We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.Another simple approach to find mode with simple coding# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print("Mode(s) is/are :" + str(d2))Output:Mode(s) is/are :{8, 6}
Mean : The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers:# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print("Mean / Average is: " + str(mean))Output:Mean / Average is: 3.0
We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.
# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print("Mean / Average is: " + str(mean))
Mean / Average is: 3.0
We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.
Median : The median is the middle number in a group of numbers. This code calculates Median of a list containing numbers:# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print("Median is: " + str(median))Output:Median is: 3
We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.
# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print("Median is: " + str(median))
Median is: 3
We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.
Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers:# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = "No mode found"else: get_mode = "Mode is / are: " + ', '.join(map(str, mode)) print(get_mode)Output:Mode is / are: 5
We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.Another simple approach to find mode with simple coding# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print("Mode(s) is/are :" + str(d2))Output:Mode(s) is/are :{8, 6}
# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = "No mode found"else: get_mode = "Mode is / are: " + ', '.join(map(str, mode)) print(get_mode)
Mode is / are: 5
We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.
Another simple approach to find mode with simple coding
# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print("Mode(s) is/are :" + str(d2))
Output:
Mode(s) is/are :{8, 6}
ConclusionWe have successfully calculated mean, median, and mode of a dataset but you might be thinking ‘Will I be using these algorithms every time I want to get mean, median and mode of a dataset?’The answer is you can but you certainly won’t. This was just to show you how the algorithm works behind the scenes when finding out any of these.For any projects, this can be achieved by simply importing an inbuilt library ‘statistics’ in Python 3, and using the inbuilt functions mean(), median() and mode(). Also, there are other external libraries that can help you achieve the same results in just 1 line of code as the code is pre-written in those libraries.
indradevecoagro
maths-mean
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25074,
"s": 25046,
"text": "\n27 May, 2020"
},
{
"code": null,
"e": 25191,
"s": 25074,
"text": "In this article, we will learn how to calculate Mean, Median, and Mode with Python without using external libraries."
},
{
"code": null,
"e": 29079,
"s": 25191,
"text": "Mean : The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers:# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print(\"Mean / Average is: \" + str(mean))Output:Mean / Average is: 3.0\nWe define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.Median : The median is the middle number in a group of numbers. This code calculates Median of a list containing numbers:# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print(\"Median is: \" + str(median))Output:Median is: 3\nWe define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers:# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = \"No mode found\"else: get_mode = \"Mode is / are: \" + ', '.join(map(str, mode)) print(get_mode)Output:Mode is / are: 5\nWe will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.Another simple approach to find mode with simple coding# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print(\"Mode(s) is/are :\" + str(d2))Output:Mode(s) is/are :{8, 6}"
},
{
"code": null,
"e": 29730,
"s": 29079,
"text": "Mean : The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers:# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print(\"Mean / Average is: \" + str(mean))Output:Mean / Average is: 3.0\nWe define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list."
},
{
"code": "# Python program to print# mean of elements # list of elements to calculate meann_num = [1, 2, 3, 4, 5]n = len(n_num) get_sum = sum(n_num)mean = get_sum / n print(\"Mean / Average is: \" + str(mean))",
"e": 29931,
"s": 29730,
"text": null
},
{
"code": null,
"e": 29955,
"s": 29931,
"text": "Mean / Average is: 3.0\n"
},
{
"code": null,
"e": 30219,
"s": 29955,
"text": "We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list."
},
{
"code": null,
"e": 31060,
"s": 30219,
"text": "Median : The median is the middle number in a group of numbers. This code calculates Median of a list containing numbers:# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print(\"Median is: \" + str(median))Output:Median is: 3\nWe define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out."
},
{
"code": "# Python program to print# median of elements # list of elements to calculate mediann_num = [1, 2, 3, 4, 5]n = len(n_num)n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2else: median = n_num[n//2]print(\"Median is: \" + str(median))",
"e": 31362,
"s": 31060,
"text": null
},
{
"code": null,
"e": 31376,
"s": 31362,
"text": "Median is: 3\n"
},
{
"code": null,
"e": 31775,
"s": 31376,
"text": "We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out."
},
{
"code": null,
"e": 34173,
"s": 31775,
"text": "Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers:# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = \"No mode found\"else: get_mode = \"Mode is / are: \" + ', '.join(map(str, mode)) print(get_mode)Output:Mode is / are: 5\nWe will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.Another simple approach to find mode with simple coding# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print(\"Mode(s) is/are :\" + str(d2))Output:Mode(s) is/are :{8, 6}"
},
{
"code": "# Python program to print# mode of elementsfrom collections import Counter # list of elements to calculate moden_num = [1, 2, 3, 4, 5, 5]n = len(n_num) data = Counter(n_num)get_mode = dict(data)mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = \"No mode found\"else: get_mode = \"Mode is / are: \" + ', '.join(map(str, mode)) print(get_mode)",
"e": 34578,
"s": 34173,
"text": null
},
{
"code": null,
"e": 34596,
"s": 34578,
"text": "Mode is / are: 5\n"
},
{
"code": null,
"e": 35287,
"s": 34596,
"text": "We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned."
},
{
"code": null,
"e": 35343,
"s": 35287,
"text": "Another simple approach to find mode with simple coding"
},
{
"code": "# The list for which you need to find # the Modey= [11, 8, 8, 3, 4, 4, 5, 6, 6, 6, 7, 8] # First you sort it# You will get numbers arranged from 3 to # 11 in asc ordery.sort() # Now open an empty list.# What you are going to do is to count# the occurrence of each number and append# (or to add your findings to) L1L1=[] # You can iterate through the sorted list# of numbers in y,# counting the occurrence of each number,# using the following code i = 0while i < len(y) : L1.append(y.count(y[i])) i += 1 # your L1 will be [1, 2, 2, 1, 3, 3, 3, 1, 3, 3, 3, 1], # the occurrences for each number in sorted y # now you can create a custom dictionary d1 for k : V# where k = your values in sorted y # and v = the occurrences of each value in y # the Code is as follows d1 = dict(zip(y, L1)) # your d1 will be {3: 1, 4: 2, 5: 1, 6: 3, 7: 1, 8: 3, 11: 1}# now what you need to do is to filter # the k values with the highest v values.# do this with the following code d2={k for (k,v) in d1.items() if v == max(L1) } print(\"Mode(s) is/are :\" + str(d2))",
"e": 36406,
"s": 35343,
"text": null
},
{
"code": null,
"e": 36414,
"s": 36406,
"text": "Output:"
},
{
"code": null,
"e": 36437,
"s": 36414,
"text": "Mode(s) is/are :{8, 6}"
},
{
"code": null,
"e": 37100,
"s": 36437,
"text": "ConclusionWe have successfully calculated mean, median, and mode of a dataset but you might be thinking ‘Will I be using these algorithms every time I want to get mean, median and mode of a dataset?’The answer is you can but you certainly won’t. This was just to show you how the algorithm works behind the scenes when finding out any of these.For any projects, this can be achieved by simply importing an inbuilt library ‘statistics’ in Python 3, and using the inbuilt functions mean(), median() and mode(). Also, there are other external libraries that can help you achieve the same results in just 1 line of code as the code is pre-written in those libraries."
},
{
"code": null,
"e": 37116,
"s": 37100,
"text": "indradevecoagro"
},
{
"code": null,
"e": 37127,
"s": 37116,
"text": "maths-mean"
},
{
"code": null,
"e": 37151,
"s": 37127,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 37158,
"s": 37151,
"text": "Python"
},
{
"code": null,
"e": 37177,
"s": 37158,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37275,
"s": 37177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37284,
"s": 37275,
"text": "Comments"
},
{
"code": null,
"e": 37297,
"s": 37284,
"text": "Old Comments"
},
{
"code": null,
"e": 37315,
"s": 37297,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37350,
"s": 37315,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 37372,
"s": 37350,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 37402,
"s": 37372,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 37434,
"s": 37402,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 37476,
"s": 37434,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 37502,
"s": 37476,
"text": "Python String | replace()"
},
{
"code": null,
"e": 37539,
"s": 37502,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 37582,
"s": 37539,
"text": "Python program to convert a list to string"
}
] |
Computer Vision 101: Working with Color Images in Python | by Eryk Lewinson | Towards Data Science
|
Every computer vision project — be it a cat/dog classifier or bringing colors to old images/movies — involves working with images. And in the end, the model can only be as good as the underlying data — garbage in, garbage out. That is why in this post I focus on explaining the basics of working with color images in Python, how they are represented and how to convert the images from one color representation to another.
In this section, we set up the Python environment. First, we import all the required libraries:
import numpy as npfrom skimage.color import rgb2lab, rgb2gray, lab2rgbfrom skimage.io import imread, imshowimport matplotlib.pyplot as plt
We use scikit-image, which is a library from scikit-learn’s family that focuses on working with images. There are many alternative approaches, some of the libraries include matplotlib, numpy, OpenCV, Pillow, etc.
In the second step, we define a helper function for printing out a summary of information about the image — its shape and the range of values in each of the layers.
The logic of the function is pretty straightforward, and the slicing of dimensions will make sense as soon as we describe how the images are stored.
We start with the most basic case possible, a grayscale image. Such images are made exclusively of shades of gray. The extremes are black (weakest intensity of contrast) and white (strongest intensity).
Under the hood, the images are stored as a matrix of integers, in which a pixel’s value corresponds to the given shade of gray. The scale of values for grayscale images ranges from 0 (black) to 255 (white). The illustration below provides an intuitive overview of the concept.
In this article, we will be working with the image you already saw as the thumbnail, the circle of colorful crayons. It was not accidental that such a colorful picture was selected :)
We start by loading the grayscale image into Python and printing it.
image_gs = imread('crayons.jpg', as_gray=True)fig, ax = plt.subplots(figsize=(9, 16))imshow(image_gs, ax=ax)ax.set_title('Grayscale image')ax.axis('off');
As the original image is in color, we used as_gray=True to load it as a grayscale image. Alternatively, we could have loaded the image using the default settings of imread (which loads an RGB image — covered in the next section) and converted it to grayscale using the rgb2gray function.
Next, we run the helper function to print the summary of the image.
print_image_summary(image_gs, ['G'])
Running the code produces the following output:
--------------Image Details:--------------Image dimensions: (1280, 1920)Channels:G : min=0.0123, max=1.0000
The image is stored as a 2D matrix, 1280 rows by 1920 columns (high-definition resolution). By looking at the min and max values, we can see that they are in the [0,1] range. That is because they were automatically divided by 255, which is a common preprocessing step for working with images.
Now it is time to work with colors. We start with the RGB model. In short, it is an additive model, in which shades of red, green and blue (hence the name) are added together in various proportions to reproduce a broad spectrum of colors.
In scikit-image, this is the default model for loading the images using imread:
image_rgb = imread('crayons.jpg')
Before printing the images, let’s inspect the summary to understand the way the image is stored in Python.
print_image_summary(image_rgb, ['R', 'G', 'B'])
Running the code generates the following summary:
--------------Image Details:--------------Image dimensions: (1280, 1920, 3)Channels:R : min=0.0000, max=255.0000G : min=0.0000, max=255.0000B : min=0.0000, max=255.0000
In comparison to the grayscale image, this time the image is stored as a 3D np.ndarray. The additional dimension represents each of the 3 color channels. As before, the intensity of the color is presented on a 0–255 scale. It is frequently rescaled to the [0,1] range. Then, a pixel’s value of 0 in any of the layers indicates that there is no color in that particular channel for that pixel.
A helpful note: When using the OpenCV’s imread function, the image is loaded as BGR instead of RGB. To make it compatible with other libraries, we need to change the order of the channels.
It is time to print the image and the different color channels:
fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_rgb/255.0) ax[0].axis('off')ax[0].set_title('original RGB')for i, lab in enumerate(['R','G','B'], 1): temp = np.zeros(image_rgb.shape) temp[:,:,i - 1] = image_rgb[:,:,i - 1] ax[i].imshow(temp/255.0) ax[i].axis("off") ax[i].set_title(lab)plt.show()
In the image below, we can see the original image and the 3 color channels separately. What I like about this image is that by focusing on individual crayons, we can see which colors from the RGB channels and in which proportions constitute the final color in the original image.
Alternatively, we can plot the separate color channels as follows:
fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_rgb) ax[0].axis('off')ax[0].set_title('original RGB')for i, cmap in enumerate(['Reds','Greens','Blues']): ax[i+1].imshow(image_rgb[:,:,i], cmap=cmap) ax[i+1].axis('off') ax[i+1].set_title(cmap[0])plt.show()
What generates the following output:
What I prefer about this variant of plotting the RGB channels is that I find it easier to distinguish the different colors (they stand out more due to the others being much lighter and transparent) and their intensity.
We can often encounter RGB images while working on image classification tasks. When applying convolutional neural networks (CNNs) for that task, we need to apply all the operations to all 3 color channels. In this article, I show how to use CNNs to work with a binary image classification problem.
Next to RGB, another popular way of representing color images is with the Lab color space (also knows as CIELAB).
Before going into more detail, it makes sense to point out the difference between a color model and a color space. A color model is a mathematical way of describing colors. A color space is the method of mapping real, observable colors to the color model’s discrete values. For more details please refer to this answer.
The Lab color space expresses colors as three values:
L: the lightness on a scale from 0 (black) to 100 (white), which in fact is a grayscale image
a: green-red color spectrum, with values ranging from -128 (green) to 127 (red)
b: blue-yellow color spectrum, with values ranging from -128 (blue) to 127 (yellow)
In other words, Lab encodes an image into a grayscale layer and reduces three color layers into two.
We start by converting the image from RGB to Lab and printing the image summary:
image_lab = rgb2lab(image_rgb / 255)
The rgb2lab function assumes that the RGB is standardized to values between 0 and 1, that is why divided all the values by 255. From the following summary, we see that the range of Lab values falls within the ones specified above.
--------------Image Details:--------------Image dimensions: (1280, 1920, 3)Channels:L : min=0.8618, max=100.0000a : min=-73.6517, max=82.9795b : min=-94.7288, max=91.2710
As the next step, we visualize the image — the Lab one and each of the channels separately.
fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab) ax[0].axis('off')ax[0].set_title('Lab')for i, col in enumerate(['L', 'a', 'b'], 1): imshow(image_lab[:, :, i-1], ax=ax[i]) ax[i].axis('off') ax[i].set_title(col)fig.show()
Well, the 1st attempt to visualizing the Lab color space was far from successful. The first image is close to unrecognizable, the L layer is not grayscale. Following the insights from this answer, in order to be printed correctly, the Lab values must be rescaled to the [0,1] range. This time, the first layer is rescaled differently than the latter two.
#scale the lab imageimage_lab_scaled = (image_lab + [0, 128, 128]) / [100, 255, 255]fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab_scaled) ax[0].axis('off')ax[0].set_title('Lab scaled')for i, col in enumerate(['L', 'a', 'b'], 1): imshow(image_lab_scaled[:, :, i-1], ax=ax[i]) ax[i].axis('off') ax[i].set_title(col) fig.show()
The second attempt is much better. In the first image, we see the Lab representation of the color image. This time, the L layer is an actual grayscale image. What could still be improved are the last two layers, as they are in grayscale as well.
In the last attempt, we apply color maps to the a and b layers of the Lab image.
fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab_scaled) ax[0].axis('off')ax[0].set_title('Lab scaled')imshow(image_lab_scaled[:,:,0], ax=ax[1]) ax[1].axis('off')ax[1].set_title('L')ax[2].imshow(image_lab_scaled[:,:,1], cmap='RdYlGn_r') ax[2].axis('off')ax[2].set_title('a')ax[3].imshow(image_lab_scaled[:,:,2], cmap='YlGnBu_r') ax[3].axis('off')ax[3].set_title('b') plt.show()
This time the results are satisfactory. We can clearly distinguish different colors in the a and b layers. What could still be improved are the colormaps themselves. For simplicity, I used the predefined color maps, which contain a color in-between the two extreme ones (yellow for layer a, green in the b layer). A potential solution is to code the color maps manually.
Lab images are commonly encountered while working with image colorization problems, such as the famous DeOldify.
In this article, I went over the basics of working with color images in Python. Using the presented techniques, you can start working on a computer vision problem on your own. I believe it is important to understand how the images are stored and how to transform them into different representations, so that you do not run into unexpected problems while training deep neural networks.
Another popular color space is the XYZ. scikit-image also contains functions for converting RGB or Lab images into XYZ.
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website.
|
[
{
"code": null,
"e": 594,
"s": 172,
"text": "Every computer vision project — be it a cat/dog classifier or bringing colors to old images/movies — involves working with images. And in the end, the model can only be as good as the underlying data — garbage in, garbage out. That is why in this post I focus on explaining the basics of working with color images in Python, how they are represented and how to convert the images from one color representation to another."
},
{
"code": null,
"e": 690,
"s": 594,
"text": "In this section, we set up the Python environment. First, we import all the required libraries:"
},
{
"code": null,
"e": 829,
"s": 690,
"text": "import numpy as npfrom skimage.color import rgb2lab, rgb2gray, lab2rgbfrom skimage.io import imread, imshowimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1042,
"s": 829,
"text": "We use scikit-image, which is a library from scikit-learn’s family that focuses on working with images. There are many alternative approaches, some of the libraries include matplotlib, numpy, OpenCV, Pillow, etc."
},
{
"code": null,
"e": 1207,
"s": 1042,
"text": "In the second step, we define a helper function for printing out a summary of information about the image — its shape and the range of values in each of the layers."
},
{
"code": null,
"e": 1356,
"s": 1207,
"text": "The logic of the function is pretty straightforward, and the slicing of dimensions will make sense as soon as we describe how the images are stored."
},
{
"code": null,
"e": 1559,
"s": 1356,
"text": "We start with the most basic case possible, a grayscale image. Such images are made exclusively of shades of gray. The extremes are black (weakest intensity of contrast) and white (strongest intensity)."
},
{
"code": null,
"e": 1836,
"s": 1559,
"text": "Under the hood, the images are stored as a matrix of integers, in which a pixel’s value corresponds to the given shade of gray. The scale of values for grayscale images ranges from 0 (black) to 255 (white). The illustration below provides an intuitive overview of the concept."
},
{
"code": null,
"e": 2020,
"s": 1836,
"text": "In this article, we will be working with the image you already saw as the thumbnail, the circle of colorful crayons. It was not accidental that such a colorful picture was selected :)"
},
{
"code": null,
"e": 2089,
"s": 2020,
"text": "We start by loading the grayscale image into Python and printing it."
},
{
"code": null,
"e": 2244,
"s": 2089,
"text": "image_gs = imread('crayons.jpg', as_gray=True)fig, ax = plt.subplots(figsize=(9, 16))imshow(image_gs, ax=ax)ax.set_title('Grayscale image')ax.axis('off');"
},
{
"code": null,
"e": 2532,
"s": 2244,
"text": "As the original image is in color, we used as_gray=True to load it as a grayscale image. Alternatively, we could have loaded the image using the default settings of imread (which loads an RGB image — covered in the next section) and converted it to grayscale using the rgb2gray function."
},
{
"code": null,
"e": 2600,
"s": 2532,
"text": "Next, we run the helper function to print the summary of the image."
},
{
"code": null,
"e": 2637,
"s": 2600,
"text": "print_image_summary(image_gs, ['G'])"
},
{
"code": null,
"e": 2685,
"s": 2637,
"text": "Running the code produces the following output:"
},
{
"code": null,
"e": 2793,
"s": 2685,
"text": "--------------Image Details:--------------Image dimensions: (1280, 1920)Channels:G : min=0.0123, max=1.0000"
},
{
"code": null,
"e": 3086,
"s": 2793,
"text": "The image is stored as a 2D matrix, 1280 rows by 1920 columns (high-definition resolution). By looking at the min and max values, we can see that they are in the [0,1] range. That is because they were automatically divided by 255, which is a common preprocessing step for working with images."
},
{
"code": null,
"e": 3325,
"s": 3086,
"text": "Now it is time to work with colors. We start with the RGB model. In short, it is an additive model, in which shades of red, green and blue (hence the name) are added together in various proportions to reproduce a broad spectrum of colors."
},
{
"code": null,
"e": 3405,
"s": 3325,
"text": "In scikit-image, this is the default model for loading the images using imread:"
},
{
"code": null,
"e": 3439,
"s": 3405,
"text": "image_rgb = imread('crayons.jpg')"
},
{
"code": null,
"e": 3546,
"s": 3439,
"text": "Before printing the images, let’s inspect the summary to understand the way the image is stored in Python."
},
{
"code": null,
"e": 3594,
"s": 3546,
"text": "print_image_summary(image_rgb, ['R', 'G', 'B'])"
},
{
"code": null,
"e": 3644,
"s": 3594,
"text": "Running the code generates the following summary:"
},
{
"code": null,
"e": 3813,
"s": 3644,
"text": "--------------Image Details:--------------Image dimensions: (1280, 1920, 3)Channels:R : min=0.0000, max=255.0000G : min=0.0000, max=255.0000B : min=0.0000, max=255.0000"
},
{
"code": null,
"e": 4206,
"s": 3813,
"text": "In comparison to the grayscale image, this time the image is stored as a 3D np.ndarray. The additional dimension represents each of the 3 color channels. As before, the intensity of the color is presented on a 0–255 scale. It is frequently rescaled to the [0,1] range. Then, a pixel’s value of 0 in any of the layers indicates that there is no color in that particular channel for that pixel."
},
{
"code": null,
"e": 4395,
"s": 4206,
"text": "A helpful note: When using the OpenCV’s imread function, the image is loaded as BGR instead of RGB. To make it compatible with other libraries, we need to change the order of the channels."
},
{
"code": null,
"e": 4459,
"s": 4395,
"text": "It is time to print the image and the different color channels:"
},
{
"code": null,
"e": 4790,
"s": 4459,
"text": "fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_rgb/255.0) ax[0].axis('off')ax[0].set_title('original RGB')for i, lab in enumerate(['R','G','B'], 1): temp = np.zeros(image_rgb.shape) temp[:,:,i - 1] = image_rgb[:,:,i - 1] ax[i].imshow(temp/255.0) ax[i].axis(\"off\") ax[i].set_title(lab)plt.show()"
},
{
"code": null,
"e": 5070,
"s": 4790,
"text": "In the image below, we can see the original image and the 3 color channels separately. What I like about this image is that by focusing on individual crayons, we can see which colors from the RGB channels and in which proportions constitute the final color in the original image."
},
{
"code": null,
"e": 5137,
"s": 5070,
"text": "Alternatively, we can plot the separate color channels as follows:"
},
{
"code": null,
"e": 5421,
"s": 5137,
"text": "fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_rgb) ax[0].axis('off')ax[0].set_title('original RGB')for i, cmap in enumerate(['Reds','Greens','Blues']): ax[i+1].imshow(image_rgb[:,:,i], cmap=cmap) ax[i+1].axis('off') ax[i+1].set_title(cmap[0])plt.show()"
},
{
"code": null,
"e": 5458,
"s": 5421,
"text": "What generates the following output:"
},
{
"code": null,
"e": 5677,
"s": 5458,
"text": "What I prefer about this variant of plotting the RGB channels is that I find it easier to distinguish the different colors (they stand out more due to the others being much lighter and transparent) and their intensity."
},
{
"code": null,
"e": 5975,
"s": 5677,
"text": "We can often encounter RGB images while working on image classification tasks. When applying convolutional neural networks (CNNs) for that task, we need to apply all the operations to all 3 color channels. In this article, I show how to use CNNs to work with a binary image classification problem."
},
{
"code": null,
"e": 6089,
"s": 5975,
"text": "Next to RGB, another popular way of representing color images is with the Lab color space (also knows as CIELAB)."
},
{
"code": null,
"e": 6409,
"s": 6089,
"text": "Before going into more detail, it makes sense to point out the difference between a color model and a color space. A color model is a mathematical way of describing colors. A color space is the method of mapping real, observable colors to the color model’s discrete values. For more details please refer to this answer."
},
{
"code": null,
"e": 6463,
"s": 6409,
"text": "The Lab color space expresses colors as three values:"
},
{
"code": null,
"e": 6557,
"s": 6463,
"text": "L: the lightness on a scale from 0 (black) to 100 (white), which in fact is a grayscale image"
},
{
"code": null,
"e": 6637,
"s": 6557,
"text": "a: green-red color spectrum, with values ranging from -128 (green) to 127 (red)"
},
{
"code": null,
"e": 6721,
"s": 6637,
"text": "b: blue-yellow color spectrum, with values ranging from -128 (blue) to 127 (yellow)"
},
{
"code": null,
"e": 6822,
"s": 6721,
"text": "In other words, Lab encodes an image into a grayscale layer and reduces three color layers into two."
},
{
"code": null,
"e": 6903,
"s": 6822,
"text": "We start by converting the image from RGB to Lab and printing the image summary:"
},
{
"code": null,
"e": 6940,
"s": 6903,
"text": "image_lab = rgb2lab(image_rgb / 255)"
},
{
"code": null,
"e": 7171,
"s": 6940,
"text": "The rgb2lab function assumes that the RGB is standardized to values between 0 and 1, that is why divided all the values by 255. From the following summary, we see that the range of Lab values falls within the ones specified above."
},
{
"code": null,
"e": 7342,
"s": 7171,
"text": "--------------Image Details:--------------Image dimensions: (1280, 1920, 3)Channels:L : min=0.8618, max=100.0000a : min=-73.6517, max=82.9795b : min=-94.7288, max=91.2710"
},
{
"code": null,
"e": 7434,
"s": 7342,
"text": "As the next step, we visualize the image — the Lab one and each of the channels separately."
},
{
"code": null,
"e": 7687,
"s": 7434,
"text": "fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab) ax[0].axis('off')ax[0].set_title('Lab')for i, col in enumerate(['L', 'a', 'b'], 1): imshow(image_lab[:, :, i-1], ax=ax[i]) ax[i].axis('off') ax[i].set_title(col)fig.show()"
},
{
"code": null,
"e": 8042,
"s": 7687,
"text": "Well, the 1st attempt to visualizing the Lab color space was far from successful. The first image is close to unrecognizable, the L layer is not grayscale. Following the insights from this answer, in order to be printed correctly, the Lab values must be rescaled to the [0,1] range. This time, the first layer is rescaled differently than the latter two."
},
{
"code": null,
"e": 8404,
"s": 8042,
"text": "#scale the lab imageimage_lab_scaled = (image_lab + [0, 128, 128]) / [100, 255, 255]fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab_scaled) ax[0].axis('off')ax[0].set_title('Lab scaled')for i, col in enumerate(['L', 'a', 'b'], 1): imshow(image_lab_scaled[:, :, i-1], ax=ax[i]) ax[i].axis('off') ax[i].set_title(col) fig.show()"
},
{
"code": null,
"e": 8650,
"s": 8404,
"text": "The second attempt is much better. In the first image, we see the Lab representation of the color image. This time, the L layer is an actual grayscale image. What could still be improved are the last two layers, as they are in grayscale as well."
},
{
"code": null,
"e": 8731,
"s": 8650,
"text": "In the last attempt, we apply color maps to the a and b layers of the Lab image."
},
{
"code": null,
"e": 9134,
"s": 8731,
"text": "fig, ax = plt.subplots(1, 4, figsize = (18, 30))ax[0].imshow(image_lab_scaled) ax[0].axis('off')ax[0].set_title('Lab scaled')imshow(image_lab_scaled[:,:,0], ax=ax[1]) ax[1].axis('off')ax[1].set_title('L')ax[2].imshow(image_lab_scaled[:,:,1], cmap='RdYlGn_r') ax[2].axis('off')ax[2].set_title('a')ax[3].imshow(image_lab_scaled[:,:,2], cmap='YlGnBu_r') ax[3].axis('off')ax[3].set_title('b') plt.show()"
},
{
"code": null,
"e": 9505,
"s": 9134,
"text": "This time the results are satisfactory. We can clearly distinguish different colors in the a and b layers. What could still be improved are the colormaps themselves. For simplicity, I used the predefined color maps, which contain a color in-between the two extreme ones (yellow for layer a, green in the b layer). A potential solution is to code the color maps manually."
},
{
"code": null,
"e": 9618,
"s": 9505,
"text": "Lab images are commonly encountered while working with image colorization problems, such as the famous DeOldify."
},
{
"code": null,
"e": 10003,
"s": 9618,
"text": "In this article, I went over the basics of working with color images in Python. Using the presented techniques, you can start working on a computer vision problem on your own. I believe it is important to understand how the images are stored and how to transform them into different representations, so that you do not run into unexpected problems while training deep neural networks."
},
{
"code": null,
"e": 10123,
"s": 10003,
"text": "Another popular color space is the XYZ. scikit-image also contains functions for converting RGB or Lab images into XYZ."
},
{
"code": null,
"e": 10285,
"s": 10123,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
}
] |
Mobile Angular UI - Drag and Drop
|
Drag and drop feature allows you to take control of a html element by grabbing it and dragging and placing the element to a different location.
To work with drag and drop features in Mobile Angular UI, you need to add the gestures module.
First add the JavaScript file inside index.html as shown below −
<script src="node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.gestures.min.js"></script>
Later add the gestures module as a dependency in app.js as shown below −
var app=angular.module('myFirstApp', [
'ngRoute',
'mobile-angular-ui',
'mobile-angular-ui.gestures'
]);
We need to create a custom directive to drag the item, using the $drag module.
The syntax to use $drag module is as follows −
$drag.bind(element, dragOptions, touchOptions);
element − The html element you want to drag.
dragOptions − It is an object with the following details −
var dragOptions= {
transform: $drag.TRANSLATE_BOTH,
start: function(dragInfo, event){},
end: function(dragInfo, event){},
move: function(dragInfo, event){},
cancel: function(dragInfo, event){}
};
For transform, you can make use of following options −
$drag.NULL_TRANSFORM − no transform movement for the element.
$drag.TRANSLATE_BOTH − The element will move on both x and y axis.
$drag.TRANSLATE_HORIZONTAL − The element will move on x axis.
$drag.TRANSLATE_UP − The element will move on the negative y axis.
$drag.TRANSLATE_DOWN − The element will move on a positive y axis.
$drag.TRANSLATE_LEFT − The element will move on the negative x axis.
$drag.TRANSLATE_RIGHT − The element will move on the positive x axis.
$drag.TRANSLATE_VERTICAL − The element will move on y axis.
$drag.TRANSLATE_INSIDE − It makes use of a function as shown below −
{
transform: $drag.TRANSLATE_INSIDE(myElement)
}
The start, end, move, cancel is a function with draginfo and event details as params.
draginfo − It is an extended version of $touch module. It has following details −
originalTransform − The $transform object relative to CSS transform before $drag is bound.
originalRect − The Bounding Client Rect for bound element before any drag action.
startRect − The Bounding Client Rect for bound element registered at start event.
startTransform − The $transform at start event.
rect − The current Bounding Client Rect for bound element.
transform − The current $transform.
reset − A function restoring element to originalTransform.
undo − A function restoring element to startTransform.
touchOptions − is an option object to be passed to underlying $touch service.
Create a directive using $drag module inside src/js/app.js as shown below −
app.directive('dragItem', ['$drag', function($drag) {
return {
controller: function($scope, $element) {
$drag.bind($element,
{
transform: $drag.TRANSLATE_BOTH,
end: function(drag) {
drag.reset();
}
},
{
sensitiveArea: $element.parent()
}
);
}
};
}]);
Let us see a working example of dragging an element −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Mobile Angular UI Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui" />
<meta name="apple-mobile-web-app-status-bar-style" content="yes" />
<link rel="shortcut icon" href="/assets/img/favicon.png" type="image/x-icon" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-hover.min.css" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-base.min.css" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-desktop.min.css" />
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<script src="node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<script src="node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.gestures.min.js"></script>
<link rel="stylesheet" href="src/css/app.css" />
<script src="src/js/app.js"></script>
</head>
<body ng-app="myFirstApp" ng-controller="MainController">
<!-- Sidebars -->
<div class="sidebar sidebar-left">
<div class="scrollable">
<h1 class="scrollable-header app-name">Tutorials</h1>
<div class="scrollable-content">
<div class="list-group" ui-turn-off='uiSidebarLeft'>
<a class="list-group-item" href="/">Home Page </a>
<a class="list-group-item" href="#/academic"><i class="fa fa-caret-right"></i>Academic Tutorials </a>
<a class="list-group-item" href="#/bigdata"><i class="fa fa-caret-right"></i>Big Data & Analytics </a>
<a class="list-group-item" href="#/computerProg"><i class="fa fa-caret-right"></i>Computer Programming </a>
<a class="list-group-item" href="#/computerscience"><i class="fa fa-caret-right"></i>Computer Science </a>
<a class="list-group-item" href="#/databases"><i class="fa fa-caret-right"></i>Databases </a>
<a class="list-group-item" href="#/devops"><i class="fa fa-caret-right"></i>DevOps </a>
</div>
</div>
</div>
</div>
<div class="sidebar sidebar-right">
<div class="scrollable">
<h1 class="scrollable-header app-name">eBooks</h1>
<div class="scrollable-content">
<div class="list-group" ui-toggle="uiSidebarRight">
<a class="list-group-item" href="#/php"><i class="fa fa-caret-right"></i>PHP </a>
<a class="list-group-item" href="#/Javascript"><i class="fa fa-caret-right"></i>Javascript </a>
</div>
</div>
</div>
</div>
<div class="app">
<div class="navbar navbar-app navbar-absolute-top">
<div class="navbar-brand navbar-brand-center" ui-yield-to="title">
TutorialsPoint
</div>
<div class="btn-group pull-left">
<div ui-toggle="uiSidebarLeft" class="btn sidebar-left-toggle">
<i class="fa fa-th-large "></i> Tutorials
</div>
</div>
<div class="btn-group pull-right" ui-yield-to="navbarAction">
<div ui-toggle="uiSidebarRight" class="btn sidebar-right-toggle">
<i class="fal fa-search"></i> eBooks
</div>
</div>
</div>
<div class="navbar navbar-app navbar-absolute-bottom">
<div class="btn-group justified">
<a ui-turn-on="aboutus_modal" class="btn btn-navbar"><i class="fal fa-globe"></i> About us</a>
<a ui-turn-on="contactus_overlay" class="btn btn-navbar"><i class="fal fa-map-marker-alt"></i> Contact us</a>
</div>
</div>
<!-- App body -->
<div class='app-body'>
<div class='app-content'>
<ng-view></ng-view>
</div>
</div>
</div><!-- ~ .app -->
<!-- Modals and Overlays -->
<div ui-yield-to="modals"></div>
</body>
</html>
/* eslint no-alert: 0 */
'use strict';
//
// Here is how to define your module
// has dependent on mobile-angular-ui
//
var app=angular.module('myFirstApp', [
'ngRoute',
'mobile-angular-ui',
'mobile-angular-ui.gestures'
]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl : "src/home/home.html"
});
$locationProvider.html5Mode({enabled:true, requireBase:false});
});
app.directive('dragItem', ['$drag', function($drag) {
return {
controller: function($scope, $element) {
$drag.bind($element,
{
transform: $drag.TRANSLATE_BOTH,end: function(drag) {
drag.reset();
}
},
{
sensitiveArea: $element.parent()
}
);
}
};
}]);
app.controller('MainController', function($rootScope, $scope, $routeParams) {
$scope.msg="Welcome to Tutorialspoint!"
$scope.js="JavaScript is a lightweight, interpreted programming language. It is designed
for creating network-centric applications. It is
complimentary to and integrated with Java.
JavaScript is very easy to implement because it
is integrated with HTML. It is open and cross-platform.";
$scope.angularjs="AngularJS is a very powerful
JavaScript Framework. It is used in Single Page
Application (SPA) projects. It extends HTML DOM
with additional attributes and makes it more
responsive to user actions. AngularJS is open
source, completely free, and used by thousands of
developers around the world. It is licensed under the Apache license version 2.0.";
$scope.reactjs="React is a front-end library
developed by Facebook. It is used for handling
the view layer for web and mobile apps. ReactJS
allows us to create reusable UI components. It is
currently one of the most popular JavaScript
libraries and has a strong foundation and large community behind it.";
});
The drag element is added inside src/home/home.html −
<div style="height: 100%; width: 100%; padding: 40px;">
<div style="height: 100%; width: 100%; border: 1px solid #444; position: relative;">
<div drag-Item>
<img src="src/img/test.png" width="100" height="100" />
</div>
</div>
</div>
An image is used to drag as shown below −
The display in the browser is as follows −
You can drag the image in the UI and once the mouse is released, it will reset back to the original position as we have used drag.reset()inside the end function.
$drag.bind($element, {
transform: $drag.TRANSLATE_BOTH,
end: function(drag) {
drag.reset();
}
},
{
sensitiveArea: $element.parent()
}
);
28 Lectures
3 hours
Asif Hussain
19 Lectures
5.5 hours
Eduonix Learning Solutions
30 Lectures
3.5 hours
Abhilash Nelson
16 Lectures
2.5 hours
Frahaan Hussain
62 Lectures
4.5 hours
Senol Atac
22 Lectures
3 hours
Sandip Bhattacharya
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2455,
"s": 2311,
"text": "Drag and drop feature allows you to take control of a html element by grabbing it and dragging and placing the element to a different location."
},
{
"code": null,
"e": 2550,
"s": 2455,
"text": "To work with drag and drop features in Mobile Angular UI, you need to add the gestures module."
},
{
"code": null,
"e": 2615,
"s": 2550,
"text": "First add the JavaScript file inside index.html as shown below −"
},
{
"code": null,
"e": 2713,
"s": 2615,
"text": "<script src=\"node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.gestures.min.js\"></script>\n"
},
{
"code": null,
"e": 2786,
"s": 2713,
"text": "Later add the gestures module as a dependency in app.js as shown below −"
},
{
"code": null,
"e": 2899,
"s": 2786,
"text": "var app=angular.module('myFirstApp', [\n 'ngRoute',\n 'mobile-angular-ui',\n 'mobile-angular-ui.gestures'\n]);"
},
{
"code": null,
"e": 2978,
"s": 2899,
"text": "We need to create a custom directive to drag the item, using the $drag module."
},
{
"code": null,
"e": 3025,
"s": 2978,
"text": "The syntax to use $drag module is as follows −"
},
{
"code": null,
"e": 3074,
"s": 3025,
"text": "$drag.bind(element, dragOptions, touchOptions);\n"
},
{
"code": null,
"e": 3119,
"s": 3074,
"text": "element − The html element you want to drag."
},
{
"code": null,
"e": 3178,
"s": 3119,
"text": "dragOptions − It is an object with the following details −"
},
{
"code": null,
"e": 3390,
"s": 3178,
"text": "var dragOptions= {\n transform: $drag.TRANSLATE_BOTH,\n start: function(dragInfo, event){},\n end: function(dragInfo, event){},\n move: function(dragInfo, event){},\n cancel: function(dragInfo, event){}\n};\n"
},
{
"code": null,
"e": 3445,
"s": 3390,
"text": "For transform, you can make use of following options −"
},
{
"code": null,
"e": 3507,
"s": 3445,
"text": "$drag.NULL_TRANSFORM − no transform movement for the element."
},
{
"code": null,
"e": 3574,
"s": 3507,
"text": "$drag.TRANSLATE_BOTH − The element will move on both x and y axis."
},
{
"code": null,
"e": 3636,
"s": 3574,
"text": "$drag.TRANSLATE_HORIZONTAL − The element will move on x axis."
},
{
"code": null,
"e": 3703,
"s": 3636,
"text": "$drag.TRANSLATE_UP − The element will move on the negative y axis."
},
{
"code": null,
"e": 3770,
"s": 3703,
"text": "$drag.TRANSLATE_DOWN − The element will move on a positive y axis."
},
{
"code": null,
"e": 3839,
"s": 3770,
"text": "$drag.TRANSLATE_LEFT − The element will move on the negative x axis."
},
{
"code": null,
"e": 3909,
"s": 3839,
"text": "$drag.TRANSLATE_RIGHT − The element will move on the positive x axis."
},
{
"code": null,
"e": 3969,
"s": 3909,
"text": "$drag.TRANSLATE_VERTICAL − The element will move on y axis."
},
{
"code": null,
"e": 4038,
"s": 3969,
"text": "$drag.TRANSLATE_INSIDE − It makes use of a function as shown below −"
},
{
"code": null,
"e": 4091,
"s": 4038,
"text": "{\n transform: $drag.TRANSLATE_INSIDE(myElement)\n}\n"
},
{
"code": null,
"e": 4177,
"s": 4091,
"text": "The start, end, move, cancel is a function with draginfo and event details as params."
},
{
"code": null,
"e": 4259,
"s": 4177,
"text": "draginfo − It is an extended version of $touch module. It has following details −"
},
{
"code": null,
"e": 4350,
"s": 4259,
"text": "originalTransform − The $transform object relative to CSS transform before $drag is bound."
},
{
"code": null,
"e": 4432,
"s": 4350,
"text": "originalRect − The Bounding Client Rect for bound element before any drag action."
},
{
"code": null,
"e": 4514,
"s": 4432,
"text": "startRect − The Bounding Client Rect for bound element registered at start event."
},
{
"code": null,
"e": 4562,
"s": 4514,
"text": "startTransform − The $transform at start event."
},
{
"code": null,
"e": 4621,
"s": 4562,
"text": "rect − The current Bounding Client Rect for bound element."
},
{
"code": null,
"e": 4657,
"s": 4621,
"text": "transform − The current $transform."
},
{
"code": null,
"e": 4716,
"s": 4657,
"text": "reset − A function restoring element to originalTransform."
},
{
"code": null,
"e": 4771,
"s": 4716,
"text": "undo − A function restoring element to startTransform."
},
{
"code": null,
"e": 4849,
"s": 4771,
"text": "touchOptions − is an option object to be passed to underlying $touch service."
},
{
"code": null,
"e": 4925,
"s": 4849,
"text": "Create a directive using $drag module inside src/js/app.js as shown below −"
},
{
"code": null,
"e": 5338,
"s": 4925,
"text": "app.directive('dragItem', ['$drag', function($drag) {\n return {\n controller: function($scope, $element) {\n $drag.bind($element,\n {\n transform: $drag.TRANSLATE_BOTH,\n end: function(drag) {\n drag.reset();\n }\n },\n {\n sensitiveArea: $element.parent()\n }\n );\n }\n };\n}]);"
},
{
"code": null,
"e": 5392,
"s": 5338,
"text": "Let us see a working example of dragging an element −"
},
{
"code": null,
"e": 9932,
"s": 5392,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>Mobile Angular UI Demo</title>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n <meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n <meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui\" />\n <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"yes\" />\n <link rel=\"shortcut icon\" href=\"/assets/img/favicon.png\" type=\"image/x-icon\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-hover.min.css\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-base.min.css\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-desktop.min.css\" />\n <script src=\"node_modules/angular/angular.min.js\"></script>\n <script src=\"node_modules/angular-route/angular-route.min.js\"></script>\n <script src=\"node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.min.js\"></script>\n <script src=\"node_modules/angular-route/angular-route.min.js\"></script>\n <script src=\"node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.gestures.min.js\"></script>\n <link rel=\"stylesheet\" href=\"src/css/app.css\" />\n <script src=\"src/js/app.js\"></script>\n </head>\n <body ng-app=\"myFirstApp\" ng-controller=\"MainController\">\n \n <!-- Sidebars -->\n <div class=\"sidebar sidebar-left\">\n <div class=\"scrollable\">\n <h1 class=\"scrollable-header app-name\">Tutorials</h1>\n <div class=\"scrollable-content\">\n <div class=\"list-group\" ui-turn-off='uiSidebarLeft'>\n <a class=\"list-group-item\" href=\"/\">Home Page </a>\n <a class=\"list-group-item\" href=\"#/academic\"><i class=\"fa fa-caret-right\"></i>Academic Tutorials </a>\n <a class=\"list-group-item\" href=\"#/bigdata\"><i class=\"fa fa-caret-right\"></i>Big Data & Analytics </a>\n <a class=\"list-group-item\" href=\"#/computerProg\"><i class=\"fa fa-caret-right\"></i>Computer Programming </a>\n <a class=\"list-group-item\" href=\"#/computerscience\"><i class=\"fa fa-caret-right\"></i>Computer Science </a>\n <a class=\"list-group-item\" href=\"#/databases\"><i class=\"fa fa-caret-right\"></i>Databases </a>\n <a class=\"list-group-item\" href=\"#/devops\"><i class=\"fa fa-caret-right\"></i>DevOps </a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"sidebar sidebar-right\">\n <div class=\"scrollable\">\n <h1 class=\"scrollable-header app-name\">eBooks</h1>\n <div class=\"scrollable-content\">\n <div class=\"list-group\" ui-toggle=\"uiSidebarRight\">\n <a class=\"list-group-item\" href=\"#/php\"><i class=\"fa fa-caret-right\"></i>PHP </a>\n <a class=\"list-group-item\" href=\"#/Javascript\"><i class=\"fa fa-caret-right\"></i>Javascript </a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"app\">\n <div class=\"navbar navbar-app navbar-absolute-top\">\n <div class=\"navbar-brand navbar-brand-center\" ui-yield-to=\"title\">\n TutorialsPoint\n </div>\n <div class=\"btn-group pull-left\">\n <div ui-toggle=\"uiSidebarLeft\" class=\"btn sidebar-left-toggle\">\n <i class=\"fa fa-th-large \"></i> Tutorials\n </div>\n </div>\n <div class=\"btn-group pull-right\" ui-yield-to=\"navbarAction\">\n <div ui-toggle=\"uiSidebarRight\" class=\"btn sidebar-right-toggle\">\n <i class=\"fal fa-search\"></i> eBooks\n </div>\n </div>\n </div>\n <div class=\"navbar navbar-app navbar-absolute-bottom\">\n <div class=\"btn-group justified\">\n <a ui-turn-on=\"aboutus_modal\" class=\"btn btn-navbar\"><i class=\"fal fa-globe\"></i> About us</a>\n <a ui-turn-on=\"contactus_overlay\" class=\"btn btn-navbar\"><i class=\"fal fa-map-marker-alt\"></i> Contact us</a>\n </div>\n </div>\n\n <!-- App body -->\n <div class='app-body'>\n <div class='app-content'>\n <ng-view></ng-view>\n </div>\n </div>\n </div><!-- ~ .app -->\n <!-- Modals and Overlays -->\n <div ui-yield-to=\"modals\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 11929,
"s": 9932,
"text": "/* eslint no-alert: 0 */\n\n'use strict';\n//\n// Here is how to define your module\n// has dependent on mobile-angular-ui\n//\nvar app=angular.module('myFirstApp', [\n 'ngRoute',\n 'mobile-angular-ui',\n 'mobile-angular-ui.gestures'\n]);\napp.config(function($routeProvider, $locationProvider) {\n $routeProvider\n .when(\"/\", {\n templateUrl : \"src/home/home.html\"\n });\n $locationProvider.html5Mode({enabled:true, requireBase:false});\n});\napp.directive('dragItem', ['$drag', function($drag) {\n return {\n controller: function($scope, $element) {\n $drag.bind($element, \n {\n transform: $drag.TRANSLATE_BOTH,end: function(drag) {\n drag.reset();\n }\n },\n {\n sensitiveArea: $element.parent()\n }\n );\n }\n };\n}]);\napp.controller('MainController', function($rootScope, $scope, $routeParams) {\n $scope.msg=\"Welcome to Tutorialspoint!\"\n $scope.js=\"JavaScript is a lightweight, interpreted programming language. It is designed \n for creating network-centric applications. It is \n complimentary to and integrated with Java. \n JavaScript is very easy to implement because it \n is integrated with HTML. It is open and cross-platform.\";\n $scope.angularjs=\"AngularJS is a very powerful \n JavaScript Framework. It is used in Single Page \n Application (SPA) projects. It extends HTML DOM \n with additional attributes and makes it more \n responsive to user actions. AngularJS is open \n source, completely free, and used by thousands of \n developers around the world. It is licensed under the Apache license version 2.0.\";\n $scope.reactjs=\"React is a front-end library \n developed by Facebook. It is used for handling \n the view layer for web and mobile apps. ReactJS \n allows us to create reusable UI components. It is \n currently one of the most popular JavaScript \n libraries and has a strong foundation and large community behind it.\";\n});"
},
{
"code": null,
"e": 11983,
"s": 11929,
"text": "The drag element is added inside src/home/home.html −"
},
{
"code": null,
"e": 12244,
"s": 11983,
"text": "<div style=\"height: 100%; width: 100%; padding: 40px;\">\n <div style=\"height: 100%; width: 100%; border: 1px solid #444; position: relative;\">\n <div drag-Item>\n <img src=\"src/img/test.png\" width=\"100\" height=\"100\" />\n </div>\n </div>\n</div>"
},
{
"code": null,
"e": 12286,
"s": 12244,
"text": "An image is used to drag as shown below −"
},
{
"code": null,
"e": 12329,
"s": 12286,
"text": "The display in the browser is as follows −"
},
{
"code": null,
"e": 12491,
"s": 12329,
"text": "You can drag the image in the UI and once the mouse is released, it will reset back to the original position as we have used drag.reset()inside the end function."
},
{
"code": null,
"e": 12670,
"s": 12491,
"text": "$drag.bind($element, {\n transform: $drag.TRANSLATE_BOTH,\n end: function(drag) {\n drag.reset();\n }\n },\n {\n sensitiveArea: $element.parent()\n }\n);"
},
{
"code": null,
"e": 12703,
"s": 12670,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 12717,
"s": 12703,
"text": " Asif Hussain"
},
{
"code": null,
"e": 12752,
"s": 12717,
"text": "\n 19 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 12780,
"s": 12752,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12815,
"s": 12780,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12832,
"s": 12815,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12867,
"s": 12832,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12884,
"s": 12867,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12919,
"s": 12884,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12931,
"s": 12919,
"text": " Senol Atac"
},
{
"code": null,
"e": 12964,
"s": 12931,
"text": "\n 22 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 12985,
"s": 12964,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 12992,
"s": 12985,
"text": " Print"
},
{
"code": null,
"e": 13003,
"s": 12992,
"text": " Add Notes"
}
] |
Wildcard Pattern Matching | Practice | GeeksforGeeks
|
Given two strings 'str' and a wildcard pattern 'pattern' of length N and M respectively, You have to print '1' if the wildcard pattern is matched with str else print '0' .
The wildcard pattern can include the characters ‘?’ and ‘*’
‘?’ – matches any single character
‘*’ – Matches any sequence of characters (including the empty sequence)
Note: The matching should cover the entire str (not partial str).
Example 1:
Input:
pattern = "ba*a?"
str = "baaabab"
Output: 1
Explanation: replace '*' with "aab" and
'?' with 'b'.
Example 2:
Input:
pattern = "a*ab"
str = "baaabab"
Output: 0
Explanation: Because of'a' at first position,
pattern and str can't be matched.
Your Task:
You don't need to read input or print anything. Your task is to complete the function wildCard() which takes the two strings 'pattern' and 'str' as input parameters and returns the answer.
Expected Time Complexity: O(N*M)
Expected Auxiliary Space: O(N*M)
Constraints:
1 <= length of(str,pat) <= 200
0
rounakdiptaghosh19996 days ago
bool solve(string s, string p) { int m = s.size(); int n = p.size(); bool dp[m+1][n+1]; dp[0][0]=true; for(int i=1;i<=m;i++) dp[i][0]=false; for(int i=1;i<=n;i++){ if(p[i-1]=='*') dp[0][i]=dp[0][i-1]; else dp[0][i]=false; } for(int i=1;i<m+1;i++){ for(int j=1;j<n+1;j++){ if(s[i-1]==p[j-1] || p[j-1]=='?') dp[i][j]=dp[i-1][j-1]; else if(p[j-1]=='*') dp[i][j]=dp[i-1][j]||dp[i][j-1]; else dp[i][j]=false; } } return dp[m][n]; }
int wildCard(string pattern,string str) { if(solve(str,pattern)==true) return 1; else return 0; }
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(N*M) and space complexity as O(N*M) is as follows :-
Execution Time :- 0.06 / 1.04 sec
int dp[201][201]; int helper(string pattern,int ind1,string str,int ind2){ if(ind2 == str.length()){ while(ind1 < pattern.length() && pattern[ind1] == '*') ind1++; if(ind1 == pattern.length()) return (1); return (0); } if(ind1 == pattern.length()){ if(ind2 == str.length()) return (1); return (0); } if(dp[ind1][ind2] != -1) return (dp[ind1][ind2]); if(pattern[ind1] == '*'){ if(helper(pattern,ind1+1,str,ind2)) return (dp[ind1][ind2] = 1); for(int i = ind2; i < str.length(); i++){ if(helper(pattern,ind1,str,i+1)) return (dp[ind1][ind2] = 1); } } else if(pattern[ind1] == '?'){ if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1); } else{ if(pattern[ind1] != str[ind2]) return (dp[ind1][ind2] = 0); else{ if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1); } } return (dp[ind1][ind2] = 0); } int wildCard(string pattern,string str){ memset(dp,-1,sizeof dp); return helper(pattern,0,str,0); }
0
swarajpawar3 weeks ago
class Solution{ public:/*You are required to complete this method*/ int f(int i,int j,string &p, string &s,vector<vector<int>>&dp){ if(i<0 and j<0)return true; if(i<0 and j>=0)return false; if(j<0 and i>=0){ for(int k=0;k<=i;k++){ if(p[k]!='*')return false; } return true; } if(dp[i][j]!=-1)return dp[i][j]; if(p[i]==s[j] or p[i]=='?')return dp[i][j]=f(i-1,j-1,p,s,dp); if(p[i]=='*'){ return dp[i][j]=(f(i-1,j,p,s,dp) | f(i,j-1,p,s,dp)); } return dp[i][j]=false; } int wildCard(string pattern,string str) { int n=pattern.size(); int m=str.size(); vector<vector<int>>dp(n,vector<int>(m,-1)); return f(n-1,m-1,pattern,str,dp); }};
0
18pa1a04771 month ago
top down dp
class Solution:
def wildCard(self,s1,s2):
def m(s1,s2,i,j,dp):
for n in range(i,len(s1)):
if s1[n]=="*":
i=n
else:
break
if i==len(s1) and j==len(s2):
return True
if i==len(s1)-1 and s1[i]=="*" :
return True
if (i==len(s1) or j==len(s2)):
return False
if dp[i][j]!=-1:
return dp[i][j]
if s1[i]==s2[j] or s1[i]=="?":
val=m(s1,s2,i+1,j+1,dp)
dp[i][j]=val
return dp[i][j]
else:
if s1[i]!=s2[j] and s1[i]!="*":
return False
else:
for n in range(i,len(s1)):
if s1[n]=="*":
i=n
else:
i=n
break
if i==len(s1):
return True
val=m(s1,s2,i,j,dp)
for k in range(j+1,len(s2)):
val=val or m(s1,s2,i,k,dp)
dp[i][j]=val
return dp[i][j]
dp=[]
l=max(len(s1),len(s2))
for i in range(l+1):
dp.append([])
for j in range(l+1):
dp[i].append(-1)
if m(s1,s2,0,0,dp):
return 1
else:
return 0
python solution for this
0
sandeep55211 month ago
1-D Array Space Optimized Tabulation (Time Taken 0.0)
int wildCard(string a,string b)
{
int m=a.size(),n=b.size();
vector<bool> f(n+1,false),s(n+1);
f[0]=true;
for(int i=1;i<=m;i++){
for(int j=0;j<=n;j++){
if(!j){
if(a[i-1] =='*' and f[0]) s[0]=true;
else s[0]=false;
continue;
}
if(a[i-1]==b[j-1] or a[i-1]=='?') s[j]=f[j-1];
else if(a[i-1]=='*') s[j]= f[j] or s[j-1];
else s[j]=false;
}
f=s;
}
return f[n];
}
+1
madhukartemba1 month ago
4 JAVA SOLUTIONS:
SOURCE: https://www.youtube.com/watch?v=ZmlQ3vgAOMo
RECURSION:
class Solution
{
private boolean rec(int i, int j, StringBuilder str1, StringBuilder str2)
{
if(i<0 && j>=0) return false;
else if(i<0 && j<0) return true;
else if(i>=0 && j<0)
{
while(i>=0)
{
if(str1.charAt(i)!='*') return false;
i--;
}
return true;
}
if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')
{
return rec(i-1, j-1, str1, str2);
}
if(str1.charAt(i)=='*')
{
return rec(i-1, j, str1, str2) || rec(i, j-1, str1, str2);
}
return false;
}
int wildCard(String pattern, String str)
{
StringBuilder str1 = new StringBuilder(pattern);
StringBuilder str2 = new StringBuilder(str);
return rec(str1.length()-1, str2.length()-1, str1, str2) ? 1 : 0;
}
}
RECURSION WITH MEMOIZATION:
class Solution
{
private int rec(int i, int j, StringBuilder str1, StringBuilder str2, int dp[][])
{
if(i<0 && j>=0) return 0;
else if(i<0 && j<0) return 1;
else if(i>=0 && j<0)
{
while(i>=0)
{
if(str1.charAt(i)!='*') return 0;
i--;
}
return 1;
}
if(dp[i][j] != -1) return dp[i][j];
if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')
{
return dp[i][j] = rec(i-1, j-1, str1, str2, dp);
}
if(str1.charAt(i)=='*')
{
return dp[i][j] = (rec(i-1, j, str1, str2, dp)==1 || rec(i, j-1, str1, str2, dp)==1) ? 1 : 0;
}
return dp[i][j] = 0;
}
int wildCard(String pattern, String str)
{
StringBuilder str1 = new StringBuilder(pattern);
StringBuilder str2 = new StringBuilder(str);
int n = str1.length();
int m = str2.length();
int dp[][] = new int[n][m];
for(int i=0; i<n; i++)
{
Arrays.fill(dp[i], -1);
}
return rec(n-1, m-1, str1, str2, dp);
}
}
2D ARRAY DYNAMIC PROGRAMMING:
class Solution
{
int wildCard(String pattern, String str)
{
StringBuilder str1 = new StringBuilder(pattern);
StringBuilder str2 = new StringBuilder(str);
int n = str1.length();
int m = str2.length();
boolean dp[][] = new boolean[n+1][m+1];
for(int i=0; i<=n; i++)
{
boolean flag = true;
for(int x=1; x<=i; x++)
{
if(str1.charAt(x-1)!='*')
{
flag = false;
break;
}
}
dp[i][0] = flag;
}
for(int j=1; j<=m; j++)
{
dp[0][j] = false;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')
{
dp[i][j] = dp[i-1][j-1];
}
else if (str1.charAt(i-1)=='*')
{
dp[i][j] = dp[i-1][j] || dp[i][j-1];
}
else
{
dp[i][j] = false;
}
}
}
return dp[n][m] ? 1 : 0;
}
}
1D ARRAY DYNAMIC PROGRAMMING:
class Solution
{
int wildCard(String pattern, String str)
{
StringBuilder str1 = new StringBuilder(pattern);
StringBuilder str2 = new StringBuilder(str);
int n = str1.length();
int m = str2.length();
boolean prev[] = new boolean[m+1], cur[] = new boolean[m+1];
prev[0] = true;
for(int j=1; j<=m; j++)
{
prev[j] = false;
}
for(int i=1; i<=n; i++)
{
boolean flag = true;
for(int x=1; x<=i; x++)
{
if(str1.charAt(x-1)!='*')
{
flag = false;
break;
}
}
cur[0] = flag;
for(int j=1; j<=m; j++)
{
if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')
{
cur[j] = prev[j-1];
}
else if (str1.charAt(i-1)=='*')
{
cur[j] = prev[j] || cur[j-1];
}
else
{
cur[j] = false;
}
}
//Copy cur into prev for next iteration
for(int k=0; k<=m; k++)
{
prev[k] = cur[k];
}
}
return cur[m] ? 1 : 0;
}
}
0
tirtha19025682 months ago
class Solution
{
int wildCard(String pattern, String str)
{
boolean[][]dp = new boolean[pattern.length()+1][str.length()+1];
dp[0][0] = true;
for(int i=0;i<dp.length;i++){
for(int j=0;j<dp[0].length;j++){
if(i==0 && j==0) dp[i][j] = true;
else if(i==0) dp[i][j] = false;
else if(j==0) {
if(pattern.charAt(i-1) == '*'){
dp[i][j] = dp[i-1][j];
}else{
dp[i][j] = false;
}
}
}
}
for(int i=1;i<dp.length;i++){
for(int j=1;j<dp[0].length;j++){
if(pattern.charAt(i-1) == '?' || pattern.charAt(i-1) == str.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}
else if(pattern.charAt(i-1) == '*'){
dp[i][j] = dp[i][j-1] || dp[i-1][j];
}
else dp[i][j] = false;
}
}
if(dp[pattern.length()][str.length()] == true ) return 1;
return 0;
}
}
+1
equbalzeeshan3 months ago
O(N) time and O(1) space solution
Explanation: For each element in s: 1. If *s==*p or *p == ‘?’ which means this is a match, then go to next element s++ p++. 2. If *p=='*', this is also a match, but one or many chars may be available, so save this *'s position and the matched s position. 3. If not match, then we check if there is a * that previously showed up, → if there is no *, return false; → if there is an *, we set current p to the next element of *, and set current s to the next saved s position.
int wildCard(string pat,string str) {
int S = str.length(), P = pat.length(), star_p = -1, star_s;
int s = 0, p = 0;
while(s < S) {
if(p < P && (str[s] == pat[p] || pat[p] == '?')) {
s++;
p++;
}
else if(p < P && pat[p] == '*') {
star_p = p;
star_s = s; // Dont increment s '*' can match '' too
p++;
}
else if(star_p != -1) {
p = star_p + 1;
s = star_s;
star_s++;
}
else
return false;
}
while(p < P && pat[p] == '*') p++;
return p == P;
}
0
bhaskarmaheshwari83 months ago
int help(string pat,string str,int n1,int n2) { if(n1==0&&n2==0) return 1; if(n1==0) return 0; if(n2==0) { for(int i=0;i<n1;i++) { if(pat[i]!='*') return 0; } return 1; } if(pat[n1-1]==str[n2-1]||pat[n1-1]=='?') return help(pat,str,n1-1,n2-1); else if(pat[n1-1]=='*') { return help(pat,str,n1-1,n2)||help(pat,str,n1,n2-1); } else { return 0; } } int wildCard(string pattern,string str) { int n1=pattern.size(); int n2=str.size(); return help(pattern,str,n1,n2); }
0
choudharymanojloul8444 months ago
int solve(string patt,string str,int i,int j,int pl,int sl)
{
if(i==pl && j==sl)
return 1;
if(j==sl)
{
while(i!=pl)
{
if(patt[i]!='*')
return 0;
i++;
}
return 1;
}
if(i==pl)
return 0;
if(t[i][j]!=-1)
return t[i][j];
if(patt[i]=='*')
{
return t[i][j]=solve(patt,str,i+1,j,pl,sl)||solve(patt,str,i,j+1,pl,sl);
}
if(patt[i]=='?')
{
return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);
}
if(patt[i]!=str[j])
return t[i][j]=0;
return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);
}
int wildCard(string pattern,string str)
{
for(int i=0;i<pattern.size();++i)
{
for(int j=0;j<str.size();++j)
t[i][j]=-1;
}
return solve(pattern,str,0,0,pattern.size(),str.size());
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 579,
"s": 238,
"text": "Given two strings 'str' and a wildcard pattern 'pattern' of length N and M respectively, You have to print '1' if the wildcard pattern is matched with str else print '0' .\n\nThe wildcard pattern can include the characters ‘?’ and ‘*’\n‘?’ – matches any single character\n‘*’ – Matches any sequence of characters (including the empty sequence)"
},
{
"code": null,
"e": 645,
"s": 579,
"text": "Note: The matching should cover the entire str (not partial str)."
},
{
"code": null,
"e": 658,
"s": 647,
"text": "Example 1:"
},
{
"code": null,
"e": 766,
"s": 658,
"text": "Input:\npattern = \"ba*a?\"\nstr = \"baaabab\"\nOutput: 1\nExplanation: replace '*' with \"aab\" and \n'?' with 'b'. \n"
},
{
"code": null,
"e": 777,
"s": 766,
"text": "Example 2:"
},
{
"code": null,
"e": 909,
"s": 777,
"text": "Input:\npattern = \"a*ab\"\nstr = \"baaabab\"\nOutput: 0\nExplanation: Because of'a' at first position,\npattern and str can't be matched. \n"
},
{
"code": null,
"e": 1110,
"s": 909,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function wildCard() which takes the two strings 'pattern' and 'str' as input parameters and returns the answer."
},
{
"code": null,
"e": 1223,
"s": 1112,
"text": "Expected Time Complexity: O(N*M)\nExpected Auxiliary Space: O(N*M)\n\nConstraints:\n1 <= length of(str,pat) <= 200"
},
{
"code": null,
"e": 1225,
"s": 1223,
"text": "0"
},
{
"code": null,
"e": 1256,
"s": 1225,
"text": "rounakdiptaghosh19996 days ago"
},
{
"code": null,
"e": 1868,
"s": 1256,
"text": "bool solve(string s, string p) { int m = s.size(); int n = p.size(); bool dp[m+1][n+1]; dp[0][0]=true; for(int i=1;i<=m;i++) dp[i][0]=false; for(int i=1;i<=n;i++){ if(p[i-1]=='*') dp[0][i]=dp[0][i-1]; else dp[0][i]=false; } for(int i=1;i<m+1;i++){ for(int j=1;j<n+1;j++){ if(s[i-1]==p[j-1] || p[j-1]=='?') dp[i][j]=dp[i-1][j-1]; else if(p[j-1]=='*') dp[i][j]=dp[i-1][j]||dp[i][j-1]; else dp[i][j]=false; } } return dp[m][n]; }"
},
{
"code": null,
"e": 1985,
"s": 1868,
"text": " int wildCard(string pattern,string str) { if(solve(str,pattern)==true) return 1; else return 0; }"
},
{
"code": null,
"e": 1988,
"s": 1985,
"text": "+1"
},
{
"code": null,
"e": 2015,
"s": 1988,
"text": "aloksinghbais022 weeks ago"
},
{
"code": null,
"e": 2110,
"s": 2015,
"text": "C++ solution having time complexity as O(N*M) and space complexity as O(N*M) is as follows :- "
},
{
"code": null,
"e": 2146,
"s": 2112,
"text": "Execution Time :- 0.06 / 1.04 sec"
},
{
"code": null,
"e": 3338,
"s": 2148,
"text": "int dp[201][201]; int helper(string pattern,int ind1,string str,int ind2){ if(ind2 == str.length()){ while(ind1 < pattern.length() && pattern[ind1] == '*') ind1++; if(ind1 == pattern.length()) return (1); return (0); } if(ind1 == pattern.length()){ if(ind2 == str.length()) return (1); return (0); } if(dp[ind1][ind2] != -1) return (dp[ind1][ind2]); if(pattern[ind1] == '*'){ if(helper(pattern,ind1+1,str,ind2)) return (dp[ind1][ind2] = 1); for(int i = ind2; i < str.length(); i++){ if(helper(pattern,ind1,str,i+1)) return (dp[ind1][ind2] = 1); } } else if(pattern[ind1] == '?'){ if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1); } else{ if(pattern[ind1] != str[ind2]) return (dp[ind1][ind2] = 0); else{ if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1); } } return (dp[ind1][ind2] = 0); } int wildCard(string pattern,string str){ memset(dp,-1,sizeof dp); return helper(pattern,0,str,0); }"
},
{
"code": null,
"e": 3340,
"s": 3338,
"text": "0"
},
{
"code": null,
"e": 3363,
"s": 3340,
"text": "swarajpawar3 weeks ago"
},
{
"code": null,
"e": 4134,
"s": 3363,
"text": "class Solution{ public:/*You are required to complete this method*/ int f(int i,int j,string &p, string &s,vector<vector<int>>&dp){ if(i<0 and j<0)return true; if(i<0 and j>=0)return false; if(j<0 and i>=0){ for(int k=0;k<=i;k++){ if(p[k]!='*')return false; } return true; } if(dp[i][j]!=-1)return dp[i][j]; if(p[i]==s[j] or p[i]=='?')return dp[i][j]=f(i-1,j-1,p,s,dp); if(p[i]=='*'){ return dp[i][j]=(f(i-1,j,p,s,dp) | f(i,j-1,p,s,dp)); } return dp[i][j]=false; } int wildCard(string pattern,string str) { int n=pattern.size(); int m=str.size(); vector<vector<int>>dp(n,vector<int>(m,-1)); return f(n-1,m-1,pattern,str,dp); }};"
},
{
"code": null,
"e": 4136,
"s": 4134,
"text": "0"
},
{
"code": null,
"e": 4158,
"s": 4136,
"text": "18pa1a04771 month ago"
},
{
"code": null,
"e": 5936,
"s": 4158,
"text": "top down dp\nclass Solution:\n def wildCard(self,s1,s2):\n def m(s1,s2,i,j,dp):\n for n in range(i,len(s1)):\n if s1[n]==\"*\":\n i=n\n else:\n break\n if i==len(s1) and j==len(s2):\n return True\n if i==len(s1)-1 and s1[i]==\"*\" :\n return True\n if (i==len(s1) or j==len(s2)):\n return False\n if dp[i][j]!=-1:\n return dp[i][j]\n if s1[i]==s2[j] or s1[i]==\"?\":\n val=m(s1,s2,i+1,j+1,dp)\n dp[i][j]=val\n return dp[i][j]\n else:\n if s1[i]!=s2[j] and s1[i]!=\"*\":\n return False\n else:\n for n in range(i,len(s1)):\n if s1[n]==\"*\":\n i=n\n else:\n i=n\n break\n if i==len(s1):\n return True\n val=m(s1,s2,i,j,dp)\n for k in range(j+1,len(s2)):\n val=val or m(s1,s2,i,k,dp)\n \n dp[i][j]=val\n return dp[i][j]\n dp=[]\n l=max(len(s1),len(s2))\n for i in range(l+1):\n dp.append([])\n for j in range(l+1):\n dp[i].append(-1)\n if m(s1,s2,0,0,dp):\n return 1\n else:\n return 0\n python solution for this"
},
{
"code": null,
"e": 5938,
"s": 5936,
"text": "0"
},
{
"code": null,
"e": 5961,
"s": 5938,
"text": "sandeep55211 month ago"
},
{
"code": null,
"e": 6015,
"s": 5961,
"text": "1-D Array Space Optimized Tabulation (Time Taken 0.0)"
},
{
"code": null,
"e": 6585,
"s": 6015,
"text": "int wildCard(string a,string b)\n {\n int m=a.size(),n=b.size();\n vector<bool> f(n+1,false),s(n+1);\n f[0]=true;\n for(int i=1;i<=m;i++){\n for(int j=0;j<=n;j++){\n if(!j){\n if(a[i-1] =='*' and f[0]) s[0]=true;\n else s[0]=false;\n continue;\n }\n if(a[i-1]==b[j-1] or a[i-1]=='?') s[j]=f[j-1];\n else if(a[i-1]=='*') s[j]= f[j] or s[j-1];\n else s[j]=false;\n }\n f=s;\n }\n return f[n];\n }"
},
{
"code": null,
"e": 6588,
"s": 6585,
"text": "+1"
},
{
"code": null,
"e": 6613,
"s": 6588,
"text": "madhukartemba1 month ago"
},
{
"code": null,
"e": 6631,
"s": 6613,
"text": "4 JAVA SOLUTIONS:"
},
{
"code": null,
"e": 6683,
"s": 6631,
"text": "SOURCE: https://www.youtube.com/watch?v=ZmlQ3vgAOMo"
},
{
"code": null,
"e": 6694,
"s": 6683,
"text": "RECURSION:"
},
{
"code": null,
"e": 7702,
"s": 6694,
"text": "class Solution\n{\n \n private boolean rec(int i, int j, StringBuilder str1, StringBuilder str2)\n {\n if(i<0 && j>=0) return false;\n else if(i<0 && j<0) return true;\n else if(i>=0 && j<0)\n {\n while(i>=0)\n {\n if(str1.charAt(i)!='*') return false;\n i--;\n }\n return true;\n }\n \n if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')\n {\n return rec(i-1, j-1, str1, str2);\n }\n \n if(str1.charAt(i)=='*')\n {\n return rec(i-1, j, str1, str2) || rec(i, j-1, str1, str2);\n }\n \n return false;\n \n \n }\n \n \n \n int wildCard(String pattern, String str)\n {\n StringBuilder str1 = new StringBuilder(pattern);\n StringBuilder str2 = new StringBuilder(str);\n \n \n return rec(str1.length()-1, str2.length()-1, str1, str2) ? 1 : 0;\n \n \n }\n}"
},
{
"code": null,
"e": 7732,
"s": 7704,
"text": "RECURSION WITH MEMOIZATION:"
},
{
"code": null,
"e": 9028,
"s": 7732,
"text": "class Solution\n{\n \n private int rec(int i, int j, StringBuilder str1, StringBuilder str2, int dp[][])\n {\n if(i<0 && j>=0) return 0;\n else if(i<0 && j<0) return 1;\n else if(i>=0 && j<0)\n {\n while(i>=0)\n {\n if(str1.charAt(i)!='*') return 0;\n i--;\n }\n return 1;\n }\n \n \n if(dp[i][j] != -1) return dp[i][j];\n \n if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')\n {\n return dp[i][j] = rec(i-1, j-1, str1, str2, dp);\n }\n \n if(str1.charAt(i)=='*')\n {\n return dp[i][j] = (rec(i-1, j, str1, str2, dp)==1 || rec(i, j-1, str1, str2, dp)==1) ? 1 : 0;\n }\n \n return dp[i][j] = 0;\n \n \n }\n \n \n \n int wildCard(String pattern, String str)\n {\n StringBuilder str1 = new StringBuilder(pattern);\n StringBuilder str2 = new StringBuilder(str);\n \n int n = str1.length();\n int m = str2.length();\n \n int dp[][] = new int[n][m];\n \n for(int i=0; i<n; i++)\n {\n Arrays.fill(dp[i], -1);\n }\n \n return rec(n-1, m-1, str1, str2, dp);\n \n \n }\n}"
},
{
"code": null,
"e": 9060,
"s": 9030,
"text": "2D ARRAY DYNAMIC PROGRAMMING:"
},
{
"code": null,
"e": 10426,
"s": 9060,
"text": "class Solution\n{\n int wildCard(String pattern, String str)\n {\n StringBuilder str1 = new StringBuilder(pattern);\n StringBuilder str2 = new StringBuilder(str);\n \n int n = str1.length();\n int m = str2.length();\n \n \n boolean dp[][] = new boolean[n+1][m+1];\n \n \n for(int i=0; i<=n; i++)\n {\n boolean flag = true;\n for(int x=1; x<=i; x++)\n {\n if(str1.charAt(x-1)!='*')\n {\n flag = false;\n break;\n }\n }\n \n dp[i][0] = flag;\n \n }\n \n \n for(int j=1; j<=m; j++)\n {\n dp[0][j] = false;\n }\n \n \n for(int i=1; i<=n; i++)\n {\n for(int j=1; j<=m; j++)\n {\n if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')\n {\n dp[i][j] = dp[i-1][j-1];\n }\n else if (str1.charAt(i-1)=='*')\n {\n dp[i][j] = dp[i-1][j] || dp[i][j-1];\n }\n else\n {\n dp[i][j] = false;\n }\n }\n }\n \n return dp[n][m] ? 1 : 0;\n \n }\n}"
},
{
"code": null,
"e": 10458,
"s": 10428,
"text": "1D ARRAY DYNAMIC PROGRAMMING:"
},
{
"code": null,
"e": 11979,
"s": 10460,
"text": "class Solution\n{\n int wildCard(String pattern, String str)\n {\n StringBuilder str1 = new StringBuilder(pattern);\n StringBuilder str2 = new StringBuilder(str);\n \n int n = str1.length();\n int m = str2.length();\n \n boolean prev[] = new boolean[m+1], cur[] = new boolean[m+1];\n \n prev[0] = true;\n \n for(int j=1; j<=m; j++)\n {\n prev[j] = false;\n }\n \n \n for(int i=1; i<=n; i++)\n {\n boolean flag = true;\n for(int x=1; x<=i; x++)\n {\n if(str1.charAt(x-1)!='*')\n {\n flag = false;\n break;\n }\n }\n \n cur[0] = flag;\n \n \n for(int j=1; j<=m; j++)\n {\n if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')\n {\n cur[j] = prev[j-1];\n }\n else if (str1.charAt(i-1)=='*')\n {\n cur[j] = prev[j] || cur[j-1];\n }\n else\n {\n cur[j] = false;\n }\n \n }\n \n //Copy cur into prev for next iteration\n for(int k=0; k<=m; k++)\n {\n prev[k] = cur[k];\n }\n \n }\n \n return cur[m] ? 1 : 0;\n \n }\n}"
},
{
"code": null,
"e": 11981,
"s": 11979,
"text": "0"
},
{
"code": null,
"e": 12007,
"s": 11981,
"text": "tirtha19025682 months ago"
},
{
"code": null,
"e": 13150,
"s": 12007,
"text": "class Solution\n{\n int wildCard(String pattern, String str)\n {\n boolean[][]dp = new boolean[pattern.length()+1][str.length()+1];\n dp[0][0] = true;\n \n for(int i=0;i<dp.length;i++){\n for(int j=0;j<dp[0].length;j++){\n if(i==0 && j==0) dp[i][j] = true;\n else if(i==0) dp[i][j] = false;\n else if(j==0) {\n if(pattern.charAt(i-1) == '*'){\n dp[i][j] = dp[i-1][j];\n }else{\n dp[i][j] = false;\n }\n \n }\n }\n \n }\n \n for(int i=1;i<dp.length;i++){\n for(int j=1;j<dp[0].length;j++){\n if(pattern.charAt(i-1) == '?' || pattern.charAt(i-1) == str.charAt(j-1)){\n dp[i][j] = dp[i-1][j-1];\n }\n else if(pattern.charAt(i-1) == '*'){\n dp[i][j] = dp[i][j-1] || dp[i-1][j];\n }\n else dp[i][j] = false;\n }\n }\n \n if(dp[pattern.length()][str.length()] == true ) return 1;\n return 0;\n }\n}\n"
},
{
"code": null,
"e": 13153,
"s": 13150,
"text": "+1"
},
{
"code": null,
"e": 13179,
"s": 13153,
"text": "equbalzeeshan3 months ago"
},
{
"code": null,
"e": 13213,
"s": 13179,
"text": "O(N) time and O(1) space solution"
},
{
"code": null,
"e": 13703,
"s": 13213,
"text": "Explanation: For each element in s: 1. If *s==*p or *p == ‘?’ which means this is a match, then go to next element s++ p++. 2. If *p=='*', this is also a match, but one or many chars may be available, so save this *'s position and the matched s position. 3. If not match, then we check if there is a * that previously showed up, → if there is no *, return false; → if there is an *, we set current p to the next element of *, and set current s to the next saved s position."
},
{
"code": null,
"e": 14440,
"s": 13703,
"text": "\tint wildCard(string pat,string str) {\n int S = str.length(), P = pat.length(), star_p = -1, star_s;\n int s = 0, p = 0;\n \n while(s < S) {\n if(p < P && (str[s] == pat[p] || pat[p] == '?')) {\n s++;\n p++;\n }\n else if(p < P && pat[p] == '*') {\n star_p = p;\n star_s = s; // Dont increment s '*' can match '' too\n p++;\n }\n else if(star_p != -1) {\n p = star_p + 1;\n s = star_s;\n star_s++;\n }\n else\n return false;\n }\n \n while(p < P && pat[p] == '*') p++;\n return p == P;\n }"
},
{
"code": null,
"e": 14442,
"s": 14440,
"text": "0"
},
{
"code": null,
"e": 14473,
"s": 14442,
"text": "bhaskarmaheshwari83 months ago"
},
{
"code": null,
"e": 15189,
"s": 14473,
"text": "int help(string pat,string str,int n1,int n2) { if(n1==0&&n2==0) return 1; if(n1==0) return 0; if(n2==0) { for(int i=0;i<n1;i++) { if(pat[i]!='*') return 0; } return 1; } if(pat[n1-1]==str[n2-1]||pat[n1-1]=='?') return help(pat,str,n1-1,n2-1); else if(pat[n1-1]=='*') { return help(pat,str,n1-1,n2)||help(pat,str,n1,n2-1); } else { return 0; } } int wildCard(string pattern,string str) { int n1=pattern.size(); int n2=str.size(); return help(pattern,str,n1,n2); }"
},
{
"code": null,
"e": 15191,
"s": 15189,
"text": "0"
},
{
"code": null,
"e": 15225,
"s": 15191,
"text": "choudharymanojloul8444 months ago"
},
{
"code": null,
"e": 16333,
"s": 15225,
"text": " int solve(string patt,string str,int i,int j,int pl,int sl)\n {\n if(i==pl && j==sl)\n return 1;\n \n if(j==sl)\n {\n while(i!=pl)\n {\n if(patt[i]!='*')\n return 0;\n \n i++;\n }\n return 1;\n }\n \n if(i==pl)\n return 0;\n \n if(t[i][j]!=-1)\n return t[i][j];\n \n if(patt[i]=='*')\n {\n return t[i][j]=solve(patt,str,i+1,j,pl,sl)||solve(patt,str,i,j+1,pl,sl);\n \n }\n \n if(patt[i]=='?')\n {\n return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);\n }\n \n if(patt[i]!=str[j])\n return t[i][j]=0;\n \n return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);\n }\n int wildCard(string pattern,string str)\n {\n for(int i=0;i<pattern.size();++i)\n {\n for(int j=0;j<str.size();++j)\n t[i][j]=-1;\n }\n return solve(pattern,str,0,0,pattern.size(),str.size());\n \n }"
},
{
"code": null,
"e": 16479,
"s": 16333,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 16515,
"s": 16479,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 16525,
"s": 16515,
"text": "\nProblem\n"
},
{
"code": null,
"e": 16535,
"s": 16525,
"text": "\nContest\n"
},
{
"code": null,
"e": 16598,
"s": 16535,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 16746,
"s": 16598,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 16954,
"s": 16746,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 17060,
"s": 16954,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Deploy a Kafka Cluster with Terraform and Ansible | by Marcos Lombog | Towards Data Science
|
In my previous post — Install a Kafka Cluster on Ubuntu in AWS, I have detailed the steps to manually set up your messaging backbone in AWS. This is a great step to understand how Kafka works, but it takes a long time and is not scalable.
A Kafka Cluster has several components such as Brokers, Zookeepers, Workers running on multiple instances like the example below. The simplest way to provision, deploy and manage your platform is by using tools that will automate this task.
On this post, I will explain how can we use Terraform to quickly provision multiple instances and then install Kafka on these instances using Ansible to set up your Cluster.
First, let’s quickly understand what is Terraform and Ansible in a high-level view
Terraform is an open-source infrastructure as code software tool created by HashiCorp. It enables users to define and provision infrastructure using a high-level configuration language known as Hashicorp Configuration Language (HCL), or optionally JSON.
Terraform supports a number of cloud infrastructure providers such as Amazon Web Services, Google Cloud Platform, Microsoft Azure.
Terraform generates an execution plan describing what it will do to reach the desired state, and then executes it to build the described infrastructure. As the configuration changes, Terraform is able to determine what changed and create incremental execution plans which can be applied.
Infrastructure is described using a high-level configuration syntax. This allows a blueprint of your datacenter to be versioned and treated as you would any other code. Additionally, infrastructure can be shared and re-used.
Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems.
First, let’s install Terraform and Ansible
Terraform
You can follow the instructions below or if you are on Mac, the simplest way is using brew:
brew install terraform
learn.hashicorp.com
Confirm Terraform is correctly installed with:
terraform -v
Ansible
Install Ansible using pip command. PIP is a package manager for Python packages. macOS doesn’t have pip installed by default. You have to install it first.
sudo easy_install pip
Use pip to install Ansible
sudo pip install ansible
Let’s verify Ansible is installed
ansible --version
For other OS, please use the reference below:
docs.ansible.com
Congratulations! Setup completed!
Now, let’s build the Kafka infrastructure using Terraform HCL.
The setup is based on the Enterprise Confluent Kafka using a public VPC and subnet.
All code is available in my GitHub
git clone git@github.com:mlomboglia/kafka-cluster-infra.git
Inside the terraform folder, there are the following files:
gateway.tf → Internet Gateway creation. There is no need to change this file
instances.tf → Instances to be created. There is no need to change this file
There are five types of instances with a short name in parenthesis:
Kafka Brokers (broker) → Host the Kafka broker service and maintain topic data
Zookeeper (zookeeper) →Host the quorum management service and manage topic metadata
Kafka Connect REST API (connect) → Kafka Connect, an open-source component of Kafka, is a framework for connecting Kafka with external systems such as databases, key-value stores, search indexes, and file systems.
REST Proxy (rest) → REST and HTTP/HTTPS access to additional Confluent Platform services
KSQL Server REST API (ksql) →KSQL is the streaming SQL engine that enables real-time data processing
Schema Registry REST API (schema) →The Schema Registry REST server uses content types for both requests and responses to indicate the serialization format of the data as well as the version of the API being used
Control Center (control_center) → Confluent Control Center is a web-based tool for managing and monitoring Apache Kafka®. Control Center facilitates building and monitoring production data pipelines and streaming applications.
public.tf → Subnet creation. For this example, I am using a public subnet
route.tf → Route table information
security_group.tf → Security group settings to allow for necessary network traffic into the instances. There is no need to change this file for the example.
Please keep in mind that ingress allows 0.0.0.0/0, so this is open to the public internet. You will need to restrict this to be used in a production environment.
vpc.tf → VPC creation
variables.tf contain the parameters for our terraform. You can modify this. For my example, I will provision 7 instances in AWS.
“rest” = 1 “connect” = 1 “ksql” = 1 “schema” = 1 “control_center” = 1 “broker” = 1 “zookeeper” = 1
With a prefix “staging”
Intance Type “t2.small” .
Important: Confluent recommends a minimum instance type “t2.large” to run Kafka, so if you modify this it will be out of AWS Free Tier and it will cost you money
Key Pair.
You will need an AWS Key Pair to create your instances. If you don’t have one yet, log in to your AWS account
EC2 -> Create Key Pair
Give a name and click Create.
Download your key, copy to a safe folder and update permissions
chmod 400 ~/.ssh/<Key Name>.pem
Update the section below of the variables.tf with your Key Name
variable "key_name" { description = "Key Pair" default = "<Your Key Name>"}
Now, we are good to go.
Terraform init will download your dependencies
cd kafka-cluster-infraterraform init
Terraform plan will create your deployment plan
terraform plan
Now, be careful on the next step. It will cost you money depending on your configuration.
terraform apply
Confirm with “yes”
if there is an error: ami is not found, go to your EC2 console, launch instance and update with the latest ami label:
Now you have provisioned all the instances in AWS.
Go your AWS and see all your instances running and take note of the public DNS (IPv4) of each instance. You will need this in the next section.
Now, let’s proceed to install Kafka using Ansible
To install Kafka, I will use the Confluent version.
1. Create a copy of the hosts_example.yml file.
cd ..cd cp-ansiblecp hosts_example.yml hosts.yml
2. Use your favourite IDE and edit hosts.yml file entering the hosts from your AWS Terraform installation above following the labels for each instance type, looking similar to this with your Public DNS.
Be very careful to use correct indentation on YML files:
Uncomment the following line in the hosts.yml file adding your key path
ansible_ssh_private_key_file: '~/.ssh/<Key Path>.pem'
3. Confirm Ansible can connect over SSH
ansible -i hosts.yml all -m ping
Type “yes” to trust all servers.
If there is an issue connecting to an instance, try to SSH manually with the command below:
ssh -i <Key Path> ec2-user@<Instance Public DNS>
4. Run the all.yml playbook
ansible-playbook -i hosts.yml all.yml
The Ansible playbook will perform the Kafka installation on all your instances.
After some time, you should see this message above. Everything installed!
Now, let’s test the installation:
You can SSH to any of your instances to check the services are running using:
You can SSH to any of your instances to check the services are running using:
systemctl status confluent*
To continue you can build Your First Kafka Application with my other post:
towardsdatascience.com
Don’t forget to destroy your Cluster and terminate your instances running the command below:
|
[
{
"code": null,
"e": 410,
"s": 171,
"text": "In my previous post — Install a Kafka Cluster on Ubuntu in AWS, I have detailed the steps to manually set up your messaging backbone in AWS. This is a great step to understand how Kafka works, but it takes a long time and is not scalable."
},
{
"code": null,
"e": 651,
"s": 410,
"text": "A Kafka Cluster has several components such as Brokers, Zookeepers, Workers running on multiple instances like the example below. The simplest way to provision, deploy and manage your platform is by using tools that will automate this task."
},
{
"code": null,
"e": 825,
"s": 651,
"text": "On this post, I will explain how can we use Terraform to quickly provision multiple instances and then install Kafka on these instances using Ansible to set up your Cluster."
},
{
"code": null,
"e": 908,
"s": 825,
"text": "First, let’s quickly understand what is Terraform and Ansible in a high-level view"
},
{
"code": null,
"e": 1162,
"s": 908,
"text": "Terraform is an open-source infrastructure as code software tool created by HashiCorp. It enables users to define and provision infrastructure using a high-level configuration language known as Hashicorp Configuration Language (HCL), or optionally JSON."
},
{
"code": null,
"e": 1293,
"s": 1162,
"text": "Terraform supports a number of cloud infrastructure providers such as Amazon Web Services, Google Cloud Platform, Microsoft Azure."
},
{
"code": null,
"e": 1581,
"s": 1293,
"text": "Terraform generates an execution plan describing what it will do to reach the desired state, and then executes it to build the described infrastructure. As the configuration changes, Terraform is able to determine what changed and create incremental execution plans which can be applied."
},
{
"code": null,
"e": 1806,
"s": 1581,
"text": "Infrastructure is described using a high-level configuration syntax. This allows a blueprint of your datacenter to be versioned and treated as you would any other code. Additionally, infrastructure can be shared and re-used."
},
{
"code": null,
"e": 2106,
"s": 1806,
"text": "Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems."
},
{
"code": null,
"e": 2149,
"s": 2106,
"text": "First, let’s install Terraform and Ansible"
},
{
"code": null,
"e": 2159,
"s": 2149,
"text": "Terraform"
},
{
"code": null,
"e": 2251,
"s": 2159,
"text": "You can follow the instructions below or if you are on Mac, the simplest way is using brew:"
},
{
"code": null,
"e": 2274,
"s": 2251,
"text": "brew install terraform"
},
{
"code": null,
"e": 2294,
"s": 2274,
"text": "learn.hashicorp.com"
},
{
"code": null,
"e": 2341,
"s": 2294,
"text": "Confirm Terraform is correctly installed with:"
},
{
"code": null,
"e": 2354,
"s": 2341,
"text": "terraform -v"
},
{
"code": null,
"e": 2362,
"s": 2354,
"text": "Ansible"
},
{
"code": null,
"e": 2518,
"s": 2362,
"text": "Install Ansible using pip command. PIP is a package manager for Python packages. macOS doesn’t have pip installed by default. You have to install it first."
},
{
"code": null,
"e": 2540,
"s": 2518,
"text": "sudo easy_install pip"
},
{
"code": null,
"e": 2567,
"s": 2540,
"text": "Use pip to install Ansible"
},
{
"code": null,
"e": 2592,
"s": 2567,
"text": "sudo pip install ansible"
},
{
"code": null,
"e": 2626,
"s": 2592,
"text": "Let’s verify Ansible is installed"
},
{
"code": null,
"e": 2644,
"s": 2626,
"text": "ansible --version"
},
{
"code": null,
"e": 2690,
"s": 2644,
"text": "For other OS, please use the reference below:"
},
{
"code": null,
"e": 2707,
"s": 2690,
"text": "docs.ansible.com"
},
{
"code": null,
"e": 2741,
"s": 2707,
"text": "Congratulations! Setup completed!"
},
{
"code": null,
"e": 2804,
"s": 2741,
"text": "Now, let’s build the Kafka infrastructure using Terraform HCL."
},
{
"code": null,
"e": 2888,
"s": 2804,
"text": "The setup is based on the Enterprise Confluent Kafka using a public VPC and subnet."
},
{
"code": null,
"e": 2923,
"s": 2888,
"text": "All code is available in my GitHub"
},
{
"code": null,
"e": 2983,
"s": 2923,
"text": "git clone git@github.com:mlomboglia/kafka-cluster-infra.git"
},
{
"code": null,
"e": 3043,
"s": 2983,
"text": "Inside the terraform folder, there are the following files:"
},
{
"code": null,
"e": 3120,
"s": 3043,
"text": "gateway.tf → Internet Gateway creation. There is no need to change this file"
},
{
"code": null,
"e": 3197,
"s": 3120,
"text": "instances.tf → Instances to be created. There is no need to change this file"
},
{
"code": null,
"e": 3265,
"s": 3197,
"text": "There are five types of instances with a short name in parenthesis:"
},
{
"code": null,
"e": 3344,
"s": 3265,
"text": "Kafka Brokers (broker) → Host the Kafka broker service and maintain topic data"
},
{
"code": null,
"e": 3428,
"s": 3344,
"text": "Zookeeper (zookeeper) →Host the quorum management service and manage topic metadata"
},
{
"code": null,
"e": 3642,
"s": 3428,
"text": "Kafka Connect REST API (connect) → Kafka Connect, an open-source component of Kafka, is a framework for connecting Kafka with external systems such as databases, key-value stores, search indexes, and file systems."
},
{
"code": null,
"e": 3731,
"s": 3642,
"text": "REST Proxy (rest) → REST and HTTP/HTTPS access to additional Confluent Platform services"
},
{
"code": null,
"e": 3832,
"s": 3731,
"text": "KSQL Server REST API (ksql) →KSQL is the streaming SQL engine that enables real-time data processing"
},
{
"code": null,
"e": 4044,
"s": 3832,
"text": "Schema Registry REST API (schema) →The Schema Registry REST server uses content types for both requests and responses to indicate the serialization format of the data as well as the version of the API being used"
},
{
"code": null,
"e": 4271,
"s": 4044,
"text": "Control Center (control_center) → Confluent Control Center is a web-based tool for managing and monitoring Apache Kafka®. Control Center facilitates building and monitoring production data pipelines and streaming applications."
},
{
"code": null,
"e": 4345,
"s": 4271,
"text": "public.tf → Subnet creation. For this example, I am using a public subnet"
},
{
"code": null,
"e": 4380,
"s": 4345,
"text": "route.tf → Route table information"
},
{
"code": null,
"e": 4537,
"s": 4380,
"text": "security_group.tf → Security group settings to allow for necessary network traffic into the instances. There is no need to change this file for the example."
},
{
"code": null,
"e": 4699,
"s": 4537,
"text": "Please keep in mind that ingress allows 0.0.0.0/0, so this is open to the public internet. You will need to restrict this to be used in a production environment."
},
{
"code": null,
"e": 4721,
"s": 4699,
"text": "vpc.tf → VPC creation"
},
{
"code": null,
"e": 4850,
"s": 4721,
"text": "variables.tf contain the parameters for our terraform. You can modify this. For my example, I will provision 7 instances in AWS."
},
{
"code": null,
"e": 4949,
"s": 4850,
"text": "“rest” = 1 “connect” = 1 “ksql” = 1 “schema” = 1 “control_center” = 1 “broker” = 1 “zookeeper” = 1"
},
{
"code": null,
"e": 4973,
"s": 4949,
"text": "With a prefix “staging”"
},
{
"code": null,
"e": 4999,
"s": 4973,
"text": "Intance Type “t2.small” ."
},
{
"code": null,
"e": 5161,
"s": 4999,
"text": "Important: Confluent recommends a minimum instance type “t2.large” to run Kafka, so if you modify this it will be out of AWS Free Tier and it will cost you money"
},
{
"code": null,
"e": 5171,
"s": 5161,
"text": "Key Pair."
},
{
"code": null,
"e": 5281,
"s": 5171,
"text": "You will need an AWS Key Pair to create your instances. If you don’t have one yet, log in to your AWS account"
},
{
"code": null,
"e": 5304,
"s": 5281,
"text": "EC2 -> Create Key Pair"
},
{
"code": null,
"e": 5334,
"s": 5304,
"text": "Give a name and click Create."
},
{
"code": null,
"e": 5398,
"s": 5334,
"text": "Download your key, copy to a safe folder and update permissions"
},
{
"code": null,
"e": 5430,
"s": 5398,
"text": "chmod 400 ~/.ssh/<Key Name>.pem"
},
{
"code": null,
"e": 5494,
"s": 5430,
"text": "Update the section below of the variables.tf with your Key Name"
},
{
"code": null,
"e": 5576,
"s": 5494,
"text": "variable \"key_name\" { description = \"Key Pair\" default = \"<Your Key Name>\"}"
},
{
"code": null,
"e": 5600,
"s": 5576,
"text": "Now, we are good to go."
},
{
"code": null,
"e": 5647,
"s": 5600,
"text": "Terraform init will download your dependencies"
},
{
"code": null,
"e": 5684,
"s": 5647,
"text": "cd kafka-cluster-infraterraform init"
},
{
"code": null,
"e": 5732,
"s": 5684,
"text": "Terraform plan will create your deployment plan"
},
{
"code": null,
"e": 5747,
"s": 5732,
"text": "terraform plan"
},
{
"code": null,
"e": 5837,
"s": 5747,
"text": "Now, be careful on the next step. It will cost you money depending on your configuration."
},
{
"code": null,
"e": 5853,
"s": 5837,
"text": "terraform apply"
},
{
"code": null,
"e": 5872,
"s": 5853,
"text": "Confirm with “yes”"
},
{
"code": null,
"e": 5990,
"s": 5872,
"text": "if there is an error: ami is not found, go to your EC2 console, launch instance and update with the latest ami label:"
},
{
"code": null,
"e": 6041,
"s": 5990,
"text": "Now you have provisioned all the instances in AWS."
},
{
"code": null,
"e": 6185,
"s": 6041,
"text": "Go your AWS and see all your instances running and take note of the public DNS (IPv4) of each instance. You will need this in the next section."
},
{
"code": null,
"e": 6235,
"s": 6185,
"text": "Now, let’s proceed to install Kafka using Ansible"
},
{
"code": null,
"e": 6287,
"s": 6235,
"text": "To install Kafka, I will use the Confluent version."
},
{
"code": null,
"e": 6335,
"s": 6287,
"text": "1. Create a copy of the hosts_example.yml file."
},
{
"code": null,
"e": 6384,
"s": 6335,
"text": "cd ..cd cp-ansiblecp hosts_example.yml hosts.yml"
},
{
"code": null,
"e": 6587,
"s": 6384,
"text": "2. Use your favourite IDE and edit hosts.yml file entering the hosts from your AWS Terraform installation above following the labels for each instance type, looking similar to this with your Public DNS."
},
{
"code": null,
"e": 6644,
"s": 6587,
"text": "Be very careful to use correct indentation on YML files:"
},
{
"code": null,
"e": 6716,
"s": 6644,
"text": "Uncomment the following line in the hosts.yml file adding your key path"
},
{
"code": null,
"e": 6770,
"s": 6716,
"text": "ansible_ssh_private_key_file: '~/.ssh/<Key Path>.pem'"
},
{
"code": null,
"e": 6810,
"s": 6770,
"text": "3. Confirm Ansible can connect over SSH"
},
{
"code": null,
"e": 6843,
"s": 6810,
"text": "ansible -i hosts.yml all -m ping"
},
{
"code": null,
"e": 6876,
"s": 6843,
"text": "Type “yes” to trust all servers."
},
{
"code": null,
"e": 6968,
"s": 6876,
"text": "If there is an issue connecting to an instance, try to SSH manually with the command below:"
},
{
"code": null,
"e": 7017,
"s": 6968,
"text": "ssh -i <Key Path> ec2-user@<Instance Public DNS>"
},
{
"code": null,
"e": 7045,
"s": 7017,
"text": "4. Run the all.yml playbook"
},
{
"code": null,
"e": 7083,
"s": 7045,
"text": "ansible-playbook -i hosts.yml all.yml"
},
{
"code": null,
"e": 7163,
"s": 7083,
"text": "The Ansible playbook will perform the Kafka installation on all your instances."
},
{
"code": null,
"e": 7237,
"s": 7163,
"text": "After some time, you should see this message above. Everything installed!"
},
{
"code": null,
"e": 7271,
"s": 7237,
"text": "Now, let’s test the installation:"
},
{
"code": null,
"e": 7349,
"s": 7271,
"text": "You can SSH to any of your instances to check the services are running using:"
},
{
"code": null,
"e": 7427,
"s": 7349,
"text": "You can SSH to any of your instances to check the services are running using:"
},
{
"code": null,
"e": 7455,
"s": 7427,
"text": "systemctl status confluent*"
},
{
"code": null,
"e": 7530,
"s": 7455,
"text": "To continue you can build Your First Kafka Application with my other post:"
},
{
"code": null,
"e": 7553,
"s": 7530,
"text": "towardsdatascience.com"
}
] |
C | Misc | Question 7 - GeeksforGeeks
|
01 Sep, 2021
The number of tokens in the following C statement is (GATE 2000)
printf("i = %d, &i = %x", i, &i);
(A) 3(B) 26(C) 10(D) 21Answer: (C)Explanation: In a C source program, the basic element recognized by the compiler is the “token.” A token is source-program text that the compiler does not break down into component elements.There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators. There are total 10 tokens in the above printf statement.Below are tokens in above program.
printf
(
"i = %d, &i = %x"
,
i
,
&
i
)
;
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE Previous Year Questions PYQ - Lexical Analysis | Compiler DesignWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:44 / 42:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xcubPntmL3Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
C-Misc
Misc
C Quiz
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C | Structure & Union | Question 4
C | File Handling | Question 5
C | Dynamic Memory Allocation | Question 5
C | Advanced Pointer | Question 2
C | Pointer Basics | Question 6
C | Pointer Basics | Question 4
C | Operators | Question 1
C | Advanced Pointer | Question 1
C | Pointer Basics | Question 2
C | Pointer Basics | Question 1
|
[
{
"code": null,
"e": 24426,
"s": 24398,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 24491,
"s": 24426,
"text": "The number of tokens in the following C statement is (GATE 2000)"
},
{
"code": "printf(\"i = %d, &i = %x\", i, &i);",
"e": 24525,
"s": 24491,
"text": null
},
{
"code": null,
"e": 24955,
"s": 24525,
"text": "(A) 3(B) 26(C) 10(D) 21Answer: (C)Explanation: In a C source program, the basic element recognized by the compiler is the “token.” A token is source-program text that the compiler does not break down into component elements.There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators. There are total 10 tokens in the above printf statement.Below are tokens in above program."
},
{
"code": null,
"e": 24997,
"s": 24955,
"text": "printf\n(\n\"i = %d, &i = %x\"\n, \ni\n,\n&\ni\n)\n;"
},
{
"code": null,
"e": 25895,
"s": 24997,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE Previous Year Questions PYQ - Lexical Analysis | Compiler DesignWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:44 / 42:38•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xcubPntmL3Y\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25902,
"s": 25895,
"text": "C-Misc"
},
{
"code": null,
"e": 25907,
"s": 25902,
"text": "Misc"
},
{
"code": null,
"e": 25914,
"s": 25907,
"text": "C Quiz"
},
{
"code": null,
"e": 25919,
"s": 25914,
"text": "Misc"
},
{
"code": null,
"e": 25924,
"s": 25919,
"text": "Misc"
},
{
"code": null,
"e": 26022,
"s": 25924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26031,
"s": 26022,
"text": "Comments"
},
{
"code": null,
"e": 26044,
"s": 26031,
"text": "Old Comments"
},
{
"code": null,
"e": 26079,
"s": 26044,
"text": "C | Structure & Union | Question 4"
},
{
"code": null,
"e": 26110,
"s": 26079,
"text": "C | File Handling | Question 5"
},
{
"code": null,
"e": 26153,
"s": 26110,
"text": "C | Dynamic Memory Allocation | Question 5"
},
{
"code": null,
"e": 26187,
"s": 26153,
"text": "C | Advanced Pointer | Question 2"
},
{
"code": null,
"e": 26219,
"s": 26187,
"text": "C | Pointer Basics | Question 6"
},
{
"code": null,
"e": 26251,
"s": 26219,
"text": "C | Pointer Basics | Question 4"
},
{
"code": null,
"e": 26278,
"s": 26251,
"text": "C | Operators | Question 1"
},
{
"code": null,
"e": 26312,
"s": 26278,
"text": "C | Advanced Pointer | Question 1"
},
{
"code": null,
"e": 26344,
"s": 26312,
"text": "C | Pointer Basics | Question 2"
}
] |
How to Visualize a Neural Network in Python using Graphviz ? - GeeksforGeeks
|
24 Jan, 2021
In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It’s representing structural information as diagrams of abstract graphs and networks means you only need to provide an only textual description of the graph regarding its topological structure and this will automatically read and create an image.
Installation:
For window terminal:
pip install graphviz
For anaconda terminal:
conda install -c anaconda graphviz
Approach:
Import module.
Create a new object of Diagraph.
Add node() and edge() into graph object.
Save the source code with render() object.
Below is the implementation:
Python3
# import modulefrom graphviz import Digraph # instantiating objectdot = Digraph(comment='A Round Graph') # Adding nodesdot.node('A', 'Alex')dot.node('B', 'Rishu')dot.node('C', 'Mohe')dot.node('D', 'Satyam') # Adding edgesdot.edges(['AB', 'AC', 'AD'])dot.edge('B', 'C', constraint = 'false')dot.edge('C', 'D', constraint = 'false') # saving source codedot.format = 'png'dot.render('Graph', view = True)
Output:
Graph.png
We can check the generated source code with dot.source methods:
Python3
print(dot.source)
Output:
// A Round Graph
digraph {
A [label=Alex]
B [label=Rishu]
C [label=Mohe]
D [label=Satyam]
A -> B
A -> C
A -> D
B -> C [constraint=false]
C -> D [constraint=false]
}
Here we are using source code for implementation which we see in the above examples:
Let’s discussed the approach:
Create a digraph object.
Define the direction of the graph using rankdir.
Create a subgraph with the following things:Set color.Set node properties.Set Level of the subgraph
Set color.
Set node properties.
Set Level of the subgraph
Create the edge of between the object with (->).
This source code must be saved in a .txt file(myfile.txt) and run `dot -Tpng -O myfile.txt` from the command-line to get a .png figure with the diagram.
Example 1:
digraph G {
rankdir=LR
splines=line
node [fixedsize=true, label=""];
subgraph cluster_0 {
color=white;
node [style=solid,color=blue4, shape=circle];
x1 x2 x3 x4;
label = "layer 1 (Input layer)";
}
subgraph cluster_1 {
color=white;
node [style=solid,color=red2, shape=circle];
a12 a22 a32;
label = "layer 2 (hidden layer)";
}
subgraph cluster_2 {
color=white;
node [style=solid,color=seagreen2, shape=circle];
O;
label="layer 3 (output layer)";
}
x1 -> a12;
x1 -> a22;
x1 -> a32;
x2 -> a12;
x2 -> a22;
x2 -> a32;
x3 -> a12;
x3 -> a22;
x3 -> a32;
x4 -> a12;
x4 -> a22;
x4 -> a32;
a12 -> O
a22 -> O
a32 -> O
}
Run this into the terminal:
dot -Tpng -O myfile.txt
Output:
Example 2:
digraph G {
rankdir=LR
splines=line
nodesep=.05;
node [label=""];
subgraph cluster_0 {
color=white;
node [style=solid,color=blue4, shape=circle];
x1 x2 x3;
label = "layer 1";
}
subgraph cluster_1 {
color=white;
node [style=solid,color=red2, shape=circle];
a12 a22 a32 a42 a52;
label = "layer 2";
}
subgraph cluster_2 {
color=white;
node [style=solid,color=red2, shape=circle];
a13 a23 a33 a43 a53;
label = "layer 3";
}
subgraph cluster_3 {
color=white;
node [style=solid,color=seagreen2, shape=circle];
O1 O2 O3 O4;
label="layer 4";
}
x1 -> a12;
x1 -> a22;
x1 -> a32;
x1 -> a42;
x1 -> a52;
x2 -> a12;
x2 -> a22;
x2 -> a32;
x2 -> a42;
x2 -> a52;
x3 -> a12;
x3 -> a22;
x3 -> a32;
x3 -> a42;
x3 -> a52;
a12 -> a13
a22 -> a13
a32 -> a13
a42 -> a13
a52 -> a13
a12 -> a23
a22 -> a23
a32 -> a23
a42 -> a23
a52 -> a23
a12 -> a33
a22 -> a33
a32 -> a33
a42 -> a33
a52 -> a33
a12 -> a43
a22 -> a43
a32 -> a43
a42 -> a43
a52 -> a43
a12 -> a53
a22 -> a53
a32 -> a53
a42 -> a53
a52 -> a53
a13 -> O1
a23 -> O2
a33 -> O3
a43 -> O4
a53 -> O4
}
Output:
Data Visualization
python-modules
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Singular Value Decomposition (SVD)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25699,
"s": 25671,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 26186,
"s": 25699,
"text": "In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It’s representing structural information as diagrams of abstract graphs and networks means you only need to provide an only textual description of the graph regarding its topological structure and this will automatically read and create an image."
},
{
"code": null,
"e": 26200,
"s": 26186,
"text": "Installation:"
},
{
"code": null,
"e": 26221,
"s": 26200,
"text": "For window terminal:"
},
{
"code": null,
"e": 26242,
"s": 26221,
"text": "pip install graphviz"
},
{
"code": null,
"e": 26265,
"s": 26242,
"text": "For anaconda terminal:"
},
{
"code": null,
"e": 26300,
"s": 26265,
"text": "conda install -c anaconda graphviz"
},
{
"code": null,
"e": 26310,
"s": 26300,
"text": "Approach:"
},
{
"code": null,
"e": 26325,
"s": 26310,
"text": "Import module."
},
{
"code": null,
"e": 26358,
"s": 26325,
"text": "Create a new object of Diagraph."
},
{
"code": null,
"e": 26399,
"s": 26358,
"text": "Add node() and edge() into graph object."
},
{
"code": null,
"e": 26442,
"s": 26399,
"text": "Save the source code with render() object."
},
{
"code": null,
"e": 26471,
"s": 26442,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26479,
"s": 26471,
"text": "Python3"
},
{
"code": "# import modulefrom graphviz import Digraph # instantiating objectdot = Digraph(comment='A Round Graph') # Adding nodesdot.node('A', 'Alex')dot.node('B', 'Rishu')dot.node('C', 'Mohe')dot.node('D', 'Satyam') # Adding edgesdot.edges(['AB', 'AC', 'AD'])dot.edge('B', 'C', constraint = 'false')dot.edge('C', 'D', constraint = 'false') # saving source codedot.format = 'png'dot.render('Graph', view = True) ",
"e": 26886,
"s": 26479,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26886,
"text": "Output:"
},
{
"code": null,
"e": 26904,
"s": 26894,
"text": "Graph.png"
},
{
"code": null,
"e": 26968,
"s": 26904,
"text": "We can check the generated source code with dot.source methods:"
},
{
"code": null,
"e": 26976,
"s": 26968,
"text": "Python3"
},
{
"code": "print(dot.source)",
"e": 26994,
"s": 26976,
"text": null
},
{
"code": null,
"e": 27002,
"s": 26994,
"text": "Output:"
},
{
"code": null,
"e": 27203,
"s": 27002,
"text": "// A Round Graph\ndigraph {\n A [label=Alex]\n B [label=Rishu]\n C [label=Mohe]\n D [label=Satyam]\n A -> B\n A -> C\n A -> D\n B -> C [constraint=false]\n C -> D [constraint=false]\n}"
},
{
"code": null,
"e": 27288,
"s": 27203,
"text": "Here we are using source code for implementation which we see in the above examples:"
},
{
"code": null,
"e": 27318,
"s": 27288,
"text": "Let’s discussed the approach:"
},
{
"code": null,
"e": 27343,
"s": 27318,
"text": "Create a digraph object."
},
{
"code": null,
"e": 27392,
"s": 27343,
"text": "Define the direction of the graph using rankdir."
},
{
"code": null,
"e": 27492,
"s": 27392,
"text": "Create a subgraph with the following things:Set color.Set node properties.Set Level of the subgraph"
},
{
"code": null,
"e": 27503,
"s": 27492,
"text": "Set color."
},
{
"code": null,
"e": 27524,
"s": 27503,
"text": "Set node properties."
},
{
"code": null,
"e": 27550,
"s": 27524,
"text": "Set Level of the subgraph"
},
{
"code": null,
"e": 27599,
"s": 27550,
"text": "Create the edge of between the object with (->)."
},
{
"code": null,
"e": 27752,
"s": 27599,
"text": "This source code must be saved in a .txt file(myfile.txt) and run `dot -Tpng -O myfile.txt` from the command-line to get a .png figure with the diagram."
},
{
"code": null,
"e": 27763,
"s": 27752,
"text": "Example 1:"
},
{
"code": null,
"e": 28651,
"s": 27763,
"text": "digraph G {\n\n rankdir=LR\n splines=line\n \n node [fixedsize=true, label=\"\"];\n\n subgraph cluster_0 {\n color=white;\n node [style=solid,color=blue4, shape=circle];\n x1 x2 x3 x4;\n label = \"layer 1 (Input layer)\";\n }\n\n subgraph cluster_1 {\n color=white;\n node [style=solid,color=red2, shape=circle];\n a12 a22 a32;\n label = \"layer 2 (hidden layer)\";\n }\n\n subgraph cluster_2 {\n color=white;\n node [style=solid,color=seagreen2, shape=circle];\n O;\n label=\"layer 3 (output layer)\";\n }\n\n x1 -> a12;\n x1 -> a22;\n x1 -> a32;\n x2 -> a12;\n x2 -> a22;\n x2 -> a32;\n x3 -> a12;\n x3 -> a22;\n x3 -> a32;\n x4 -> a12;\n x4 -> a22;\n x4 -> a32;\n \n\n a12 -> O\n a22 -> O\n a32 -> O\n\n}"
},
{
"code": null,
"e": 28679,
"s": 28651,
"text": "Run this into the terminal:"
},
{
"code": null,
"e": 28703,
"s": 28679,
"text": "dot -Tpng -O myfile.txt"
},
{
"code": null,
"e": 28711,
"s": 28703,
"text": "Output:"
},
{
"code": null,
"e": 28722,
"s": 28711,
"text": "Example 2:"
},
{
"code": null,
"e": 30330,
"s": 28722,
"text": "digraph G {\n\n rankdir=LR\n splines=line\n nodesep=.05;\n \n node [label=\"\"];\n \n subgraph cluster_0 {\n color=white;\n node [style=solid,color=blue4, shape=circle];\n x1 x2 x3;\n label = \"layer 1\";\n }\n\n subgraph cluster_1 {\n color=white;\n node [style=solid,color=red2, shape=circle];\n a12 a22 a32 a42 a52;\n label = \"layer 2\";\n }\n\n subgraph cluster_2 {\n color=white;\n node [style=solid,color=red2, shape=circle];\n a13 a23 a33 a43 a53;\n label = \"layer 3\";\n }\n\n subgraph cluster_3 {\n color=white;\n node [style=solid,color=seagreen2, shape=circle];\n O1 O2 O3 O4;\n label=\"layer 4\";\n }\n\n x1 -> a12;\n x1 -> a22;\n x1 -> a32;\n x1 -> a42;\n x1 -> a52;\n\n x2 -> a12;\n x2 -> a22;\n x2 -> a32;\n x2 -> a42;\n x2 -> a52;\n \n x3 -> a12;\n x3 -> a22;\n x3 -> a32;\n x3 -> a42;\n x3 -> a52;\n\n a12 -> a13\n a22 -> a13\n a32 -> a13\n a42 -> a13\n a52 -> a13\n\n a12 -> a23\n a22 -> a23\n a32 -> a23\n a42 -> a23\n a52 -> a23\n\n a12 -> a33\n a22 -> a33\n a32 -> a33\n a42 -> a33\n a52 -> a33\n\n a12 -> a43\n a22 -> a43\n a32 -> a43\n a42 -> a43\n a52 -> a43\n\n a12 -> a53\n a22 -> a53\n a32 -> a53\n a42 -> a53\n a52 -> a53\n\n a13 -> O1\n a23 -> O2\n a33 -> O3\n a43 -> O4\n a53 -> O4\n\n}"
},
{
"code": null,
"e": 30338,
"s": 30330,
"text": "Output:"
},
{
"code": null,
"e": 30357,
"s": 30338,
"text": "Data Visualization"
},
{
"code": null,
"e": 30372,
"s": 30357,
"text": "python-modules"
},
{
"code": null,
"e": 30389,
"s": 30372,
"text": "Machine Learning"
},
{
"code": null,
"e": 30396,
"s": 30389,
"text": "Python"
},
{
"code": null,
"e": 30413,
"s": 30396,
"text": "Machine Learning"
},
{
"code": null,
"e": 30511,
"s": 30413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30544,
"s": 30511,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 30585,
"s": 30544,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 30613,
"s": 30585,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 30649,
"s": 30613,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 30684,
"s": 30649,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 30712,
"s": 30684,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30762,
"s": 30712,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30784,
"s": 30762,
"text": "Python map() function"
}
] |
How to draw a Clock using StillClock in Java - GeeksforGeeks
|
07 Feb, 2020
StillClock class is used to displays an analog clock and uses the MessagePanel to display the hour, minute, and second in a panel. We use javax.swing.JPanel to display the StillClock.
This article helps to develop a class that displays a clock on a panel.
Steps used to draw the clock:
To draw a clock, draw a circle and three hands for a second, minute and hour.
One end is the center of the clock at (xCenter, yCenter) and the other end (xEnd, yEnd) is determined by,xEndpart = yCenter + handLength X sin(0)
yEndpart = yCenter + handLength X cos(0)
xEndpart = yCenter + handLength X sin(0)
yEndpart = yCenter + handLength X cos(0)
The angle for the second hand(Sixty seconds in one minute),second*(2*pi/60)
second*(2*pi/60)
The angle for the minute hand is,(minute + second/60)*(2*pi/60)
(minute + second/60)*(2*pi/60)
Since, one circle is divided into twelve hours, the angle for the hour hand is,(hour + minute/60 + second/(60*60)) * (2*pi/12)
(hour + minute/60 + second/(60*60)) * (2*pi/12)
Below is the implementation of the above approach:
Example:
// Java program to draw a Clock// using StillClock in Java import java.awt.*;import javax.swing.*;import java.util.*; // Class StillClockpublic class StillClock extends JPanel { private int hour; private int minute; private int second; // Default Constructor public StillClock() { setCurrentTime(); } // Construct a clock with specified // hour, minute and second public StillCLock(int hour, int minute, int second) { this.hour = hour; this.minute = minute; this.second = second; } // Returning hour public int getHour() { return hour; } // Setting a new hour public void setHour(int hour) { this.hour = hour; repaint(); } // Returning Minute public int getMinute() { return minute; } // Setting a new minute public void setMinute(int minute) { this.minute = minute; repaint(); } // Return second public int getSecond(int second) { this.second = second; repaint(); } // Draw the clock protected void paintComponents(Graphics gr) { super.paintComponent(gr); // Initialize clock parameters int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5); int xCenter = getWidth() / 2; int yCenter = getHeight() / 2; gr.setColor(Color.black); gr.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius); gr.drawString("11", xCenter - 5, yCenter - clockRadius + 12); gr.drawString("8", xCenter - clockRadius + 3, yCenter + 5); gr.drawString("4", xCenter + clockRadius - 10, yCenter + 3); gr.drawString("5", xCenter - 3, yCenter + clockRadius - 3); // Draw the second hand int sLength = (int)(clockRadius * 0.8); int xSecond = (int)(xCenter + sLength * Math.sin( second * (2 * Math.PI / 60))); int ySecond = (int)(yCenter - sLength * Math.cos( second * (2 * Math.PI / 60))); gr.setColor(Color.orange); gr.drawLine(xCenter, yCenter, xSecond, ySecond); // Draw the minute hand int mLength = (int)(clockRadius * 0.8); int xMinute = (int)(xCenter + mLength * Math.sin( minute * (2 * Math.PI / 60))); int yMinute = (int)(yCenter - mLength * Math.cos( minute * (2 * Math.PI / 60))); gr.setColor(Color.yellow); gr.drawLine(xCenter, yCenter, xMinute, yMinute); // Draw the hour hand int hLength = (int)(clockRadius * 0.5); int xHour = (int)(xCenter + hLength * Math.sin( (hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); int yHour = (int)(yCenter - hLength * Math.cos( (hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); gr.setColor(Color.blue); gr.drawLine(xCenter, yCenter, xHour, yHour); } // Function to set the current time on the clock public void setCurrentTime() { Calendar cal = new GregorianCalendar(); this.hour = cal.get(Calendar.HOUR_OF_DAY); this.minute = cal.get(Calendar.MINUTE); this.second = cal.get(Calendar.SECOND); } public Dimension getPreferedsize() { return new Dimension(300, 300); }}
Output:
java-advanced
java-swing
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 25421,
"s": 25237,
"text": "StillClock class is used to displays an analog clock and uses the MessagePanel to display the hour, minute, and second in a panel. We use javax.swing.JPanel to display the StillClock."
},
{
"code": null,
"e": 25493,
"s": 25421,
"text": "This article helps to develop a class that displays a clock on a panel."
},
{
"code": null,
"e": 25523,
"s": 25493,
"text": "Steps used to draw the clock:"
},
{
"code": null,
"e": 25601,
"s": 25523,
"text": "To draw a clock, draw a circle and three hands for a second, minute and hour."
},
{
"code": null,
"e": 25789,
"s": 25601,
"text": "One end is the center of the clock at (xCenter, yCenter) and the other end (xEnd, yEnd) is determined by,xEndpart = yCenter + handLength X sin(0)\nyEndpart = yCenter + handLength X cos(0)\n"
},
{
"code": null,
"e": 25872,
"s": 25789,
"text": "xEndpart = yCenter + handLength X sin(0)\nyEndpart = yCenter + handLength X cos(0)\n"
},
{
"code": null,
"e": 25949,
"s": 25872,
"text": "The angle for the second hand(Sixty seconds in one minute),second*(2*pi/60)\n"
},
{
"code": null,
"e": 25967,
"s": 25949,
"text": "second*(2*pi/60)\n"
},
{
"code": null,
"e": 26032,
"s": 25967,
"text": "The angle for the minute hand is,(minute + second/60)*(2*pi/60)\n"
},
{
"code": null,
"e": 26064,
"s": 26032,
"text": "(minute + second/60)*(2*pi/60)\n"
},
{
"code": null,
"e": 26192,
"s": 26064,
"text": "Since, one circle is divided into twelve hours, the angle for the hour hand is,(hour + minute/60 + second/(60*60)) * (2*pi/12)\n"
},
{
"code": null,
"e": 26241,
"s": 26192,
"text": "(hour + minute/60 + second/(60*60)) * (2*pi/12)\n"
},
{
"code": null,
"e": 26292,
"s": 26241,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26301,
"s": 26292,
"text": "Example:"
},
{
"code": "// Java program to draw a Clock// using StillClock in Java import java.awt.*;import javax.swing.*;import java.util.*; // Class StillClockpublic class StillClock extends JPanel { private int hour; private int minute; private int second; // Default Constructor public StillClock() { setCurrentTime(); } // Construct a clock with specified // hour, minute and second public StillCLock(int hour, int minute, int second) { this.hour = hour; this.minute = minute; this.second = second; } // Returning hour public int getHour() { return hour; } // Setting a new hour public void setHour(int hour) { this.hour = hour; repaint(); } // Returning Minute public int getMinute() { return minute; } // Setting a new minute public void setMinute(int minute) { this.minute = minute; repaint(); } // Return second public int getSecond(int second) { this.second = second; repaint(); } // Draw the clock protected void paintComponents(Graphics gr) { super.paintComponent(gr); // Initialize clock parameters int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5); int xCenter = getWidth() / 2; int yCenter = getHeight() / 2; gr.setColor(Color.black); gr.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius); gr.drawString(\"11\", xCenter - 5, yCenter - clockRadius + 12); gr.drawString(\"8\", xCenter - clockRadius + 3, yCenter + 5); gr.drawString(\"4\", xCenter + clockRadius - 10, yCenter + 3); gr.drawString(\"5\", xCenter - 3, yCenter + clockRadius - 3); // Draw the second hand int sLength = (int)(clockRadius * 0.8); int xSecond = (int)(xCenter + sLength * Math.sin( second * (2 * Math.PI / 60))); int ySecond = (int)(yCenter - sLength * Math.cos( second * (2 * Math.PI / 60))); gr.setColor(Color.orange); gr.drawLine(xCenter, yCenter, xSecond, ySecond); // Draw the minute hand int mLength = (int)(clockRadius * 0.8); int xMinute = (int)(xCenter + mLength * Math.sin( minute * (2 * Math.PI / 60))); int yMinute = (int)(yCenter - mLength * Math.cos( minute * (2 * Math.PI / 60))); gr.setColor(Color.yellow); gr.drawLine(xCenter, yCenter, xMinute, yMinute); // Draw the hour hand int hLength = (int)(clockRadius * 0.5); int xHour = (int)(xCenter + hLength * Math.sin( (hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); int yHour = (int)(yCenter - hLength * Math.cos( (hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); gr.setColor(Color.blue); gr.drawLine(xCenter, yCenter, xHour, yHour); } // Function to set the current time on the clock public void setCurrentTime() { Calendar cal = new GregorianCalendar(); this.hour = cal.get(Calendar.HOUR_OF_DAY); this.minute = cal.get(Calendar.MINUTE); this.second = cal.get(Calendar.SECOND); } public Dimension getPreferedsize() { return new Dimension(300, 300); }}",
"e": 30394,
"s": 26301,
"text": null
},
{
"code": null,
"e": 30402,
"s": 30394,
"text": "Output:"
},
{
"code": null,
"e": 30416,
"s": 30402,
"text": "java-advanced"
},
{
"code": null,
"e": 30427,
"s": 30416,
"text": "java-swing"
},
{
"code": null,
"e": 30432,
"s": 30427,
"text": "Java"
},
{
"code": null,
"e": 30451,
"s": 30432,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30456,
"s": 30451,
"text": "Java"
},
{
"code": null,
"e": 30554,
"s": 30456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30569,
"s": 30554,
"text": "Stream In Java"
},
{
"code": null,
"e": 30590,
"s": 30569,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30609,
"s": 30590,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30639,
"s": 30609,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30685,
"s": 30639,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30702,
"s": 30685,
"text": "Generics in Java"
},
{
"code": null,
"e": 30723,
"s": 30702,
"text": "Introduction to Java"
},
{
"code": null,
"e": 30766,
"s": 30723,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30788,
"s": 30766,
"text": "PriorityQueue in Java"
}
] |
What is the difference between equals and compareTo in Java?
|
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.
The result is a negative integer if this String object lexicographically precedes the argument string.
The result is a positive integer if this String object lexicographically follows the argument string.
The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true.
Live Demo
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is greater than str2");
} else if (retval == 0) {
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is less than str2");
}
}
}
str1 is less than str2
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string."
},
{
"code": null,
"e": 1456,
"s": 1353,
"text": "The result is a negative integer if this String object lexicographically precedes the argument string."
},
{
"code": null,
"e": 1559,
"s": 1456,
"text": " The result is a positive integer if this String object lexicographically follows the argument string."
},
{
"code": null,
"e": 1683,
"s": 1559,
"text": " The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true."
},
{
"code": null,
"e": 1693,
"s": 1683,
"text": "Live Demo"
},
{
"code": null,
"e": 2192,
"s": 1693,
"text": "public class StringDemo {\n public static void main(String[] args) {\n String str1 = \"tutorials\", str2 = \"point\";\n\n // comparing str1 and str2\n int retval = str1.compareTo(str2);\n\n // prints the return value of the comparison\n if (retval < 0) {\n System.out.println(\"str1 is greater than str2\");\n } else if (retval == 0) {\n System.out.println(\"str1 is equal to str2\");\n } else {\n System.out.println(\"str1 is less than str2\");\n }\n }\n}"
},
{
"code": null,
"e": 2215,
"s": 2192,
"text": "str1 is less than str2"
}
] |
How to do bitwise complement on a 16-bit signal using Python?
|
If you want to get an inversion of only first 16 bits of a number, you can take a xor of that number with 65535(16 1s in binary).
a = 3 # 11 in binary
b = a ^ 65535
print(bin(b))
This will give the output −
0b1111111111111100
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "If you want to get an inversion of only first 16 bits of a number, you can take a xor of that number with 65535(16 1s in binary). "
},
{
"code": null,
"e": 1242,
"s": 1193,
"text": "a = 3 # 11 in binary\nb = a ^ 65535\nprint(bin(b))"
},
{
"code": null,
"e": 1270,
"s": 1242,
"text": "This will give the output −"
},
{
"code": null,
"e": 1289,
"s": 1270,
"text": "0b1111111111111100"
}
] |
C Program to sort rows of the Matrix - GeeksforGeeks
|
10 Jan, 2022
Given a matrix arr[][] of dimensions N * M, the task is to sort the matrix such that each row is sorted and the first element of each row is greater than or equal to the last element of the previous row.
Examples:
Input: N = 3, M = 3, arr[][] = {{7, 8, 9}, {5, 6, 4}, {3, 1, 2}}Output:1 2 34 5 67 8 9
Approach: Follow the steps below to solve the problem:
Traverse the matrixFor every matrix element, consider it to be the minimum element in the matrix. Check if there is a smaller element present in the rest of the matrix.If found to be true, swap the current element and the minimum element in the matrix.Finally, print the sorted matrix.
Traverse the matrix
For every matrix element, consider it to be the minimum element in the matrix. Check if there is a smaller element present in the rest of the matrix.
If found to be true, swap the current element and the minimum element in the matrix.
Finally, print the sorted matrix.
Below is the implementation for the above approach:
C
// C program for the above approach#include <stdio.h>#include <stdlib.h> #define SIZE 100 // Function to sort a matrixvoid sort_matrix(int arr[SIZE][SIZE], int N, int M){ // Traverse over the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Current minimum element int minimum = arr[i][j]; // Index of the current // minimum element int z = i; int q = j; // Check if any smaller element // is present in the matrix int w = j; for (int k = i; k < N; k++) { for (; w < M; w++) { // Update the minimum element if (arr[k][w] < minimum) { minimum = arr[k][w]; // Update the index of // the minimum element z = k; q = w; } } w = 0; } // Swap the current element // and the minimum element int temp = arr[i][j]; arr[i][j] = arr[z][q]; arr[z][q] = temp; } }} // Function to print the sorted matrixvoid printMat(int arr[SIZE][SIZE], int N, int M){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { printf("%d ", arr[i][j]); } printf("\n"); }} // Driver Codeint main(){ int N = 3, M = 3; int arr[SIZE][SIZE] = { { 7, 8, 9 }, { 5, 6, 4 }, { 3, 1, 2 } }; // Sort the matrix sort_matrix(arr, N, M); // Print the sorted matrix printMat(arr, N, M); return 0;}
1 2 3
4 5 6
7 8 9
Time Complexity: O(N4)Auxiliary Space: O(1)
simmytarika5
C Language
Mathematical
Matrix
School Programming
Searching
Sorting
Searching
Mathematical
Sorting
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 24286,
"s": 24258,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 24490,
"s": 24286,
"text": "Given a matrix arr[][] of dimensions N * M, the task is to sort the matrix such that each row is sorted and the first element of each row is greater than or equal to the last element of the previous row."
},
{
"code": null,
"e": 24500,
"s": 24490,
"text": "Examples:"
},
{
"code": null,
"e": 24587,
"s": 24500,
"text": "Input: N = 3, M = 3, arr[][] = {{7, 8, 9}, {5, 6, 4}, {3, 1, 2}}Output:1 2 34 5 67 8 9"
},
{
"code": null,
"e": 24642,
"s": 24587,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 24928,
"s": 24642,
"text": "Traverse the matrixFor every matrix element, consider it to be the minimum element in the matrix. Check if there is a smaller element present in the rest of the matrix.If found to be true, swap the current element and the minimum element in the matrix.Finally, print the sorted matrix."
},
{
"code": null,
"e": 24948,
"s": 24928,
"text": "Traverse the matrix"
},
{
"code": null,
"e": 25098,
"s": 24948,
"text": "For every matrix element, consider it to be the minimum element in the matrix. Check if there is a smaller element present in the rest of the matrix."
},
{
"code": null,
"e": 25183,
"s": 25098,
"text": "If found to be true, swap the current element and the minimum element in the matrix."
},
{
"code": null,
"e": 25217,
"s": 25183,
"text": "Finally, print the sorted matrix."
},
{
"code": null,
"e": 25269,
"s": 25217,
"text": "Below is the implementation for the above approach:"
},
{
"code": null,
"e": 25271,
"s": 25269,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h>#include <stdlib.h> #define SIZE 100 // Function to sort a matrixvoid sort_matrix(int arr[SIZE][SIZE], int N, int M){ // Traverse over the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Current minimum element int minimum = arr[i][j]; // Index of the current // minimum element int z = i; int q = j; // Check if any smaller element // is present in the matrix int w = j; for (int k = i; k < N; k++) { for (; w < M; w++) { // Update the minimum element if (arr[k][w] < minimum) { minimum = arr[k][w]; // Update the index of // the minimum element z = k; q = w; } } w = 0; } // Swap the current element // and the minimum element int temp = arr[i][j]; arr[i][j] = arr[z][q]; arr[z][q] = temp; } }} // Function to print the sorted matrixvoid printMat(int arr[SIZE][SIZE], int N, int M){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { printf(\"%d \", arr[i][j]); } printf(\"\\n\"); }} // Driver Codeint main(){ int N = 3, M = 3; int arr[SIZE][SIZE] = { { 7, 8, 9 }, { 5, 6, 4 }, { 3, 1, 2 } }; // Sort the matrix sort_matrix(arr, N, M); // Print the sorted matrix printMat(arr, N, M); return 0;}",
"e": 27016,
"s": 25271,
"text": null
},
{
"code": null,
"e": 27037,
"s": 27016,
"text": "1 2 3 \n4 5 6 \n7 8 9\n"
},
{
"code": null,
"e": 27081,
"s": 27037,
"text": "Time Complexity: O(N4)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27094,
"s": 27081,
"text": "simmytarika5"
},
{
"code": null,
"e": 27105,
"s": 27094,
"text": "C Language"
},
{
"code": null,
"e": 27118,
"s": 27105,
"text": "Mathematical"
},
{
"code": null,
"e": 27125,
"s": 27118,
"text": "Matrix"
},
{
"code": null,
"e": 27144,
"s": 27125,
"text": "School Programming"
},
{
"code": null,
"e": 27154,
"s": 27144,
"text": "Searching"
},
{
"code": null,
"e": 27162,
"s": 27154,
"text": "Sorting"
},
{
"code": null,
"e": 27172,
"s": 27162,
"text": "Searching"
},
{
"code": null,
"e": 27185,
"s": 27172,
"text": "Mathematical"
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Sorting"
},
{
"code": null,
"e": 27200,
"s": 27193,
"text": "Matrix"
},
{
"code": null,
"e": 27298,
"s": 27200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27307,
"s": 27298,
"text": "Comments"
},
{
"code": null,
"e": 27320,
"s": 27307,
"text": "Old Comments"
},
{
"code": null,
"e": 27358,
"s": 27320,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27384,
"s": 27358,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27404,
"s": 27384,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27426,
"s": 27404,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27464,
"s": 27426,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27494,
"s": 27464,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 27554,
"s": 27494,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 27569,
"s": 27554,
"text": "C++ Data Types"
},
{
"code": null,
"e": 27612,
"s": 27569,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to detect the screen resolution with JavaScript?
|
To detect the screen resolution, use the concept of window.screen.
For width, use the following −
window.screen.availWidth
For height −
window.screen.availHeight
Following is the code to detect the screen resolution −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
console.log("Available Width="+window.screen.availWidth);
console.log("Available Height="+window.screen.availHeight);
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To detect the screen resolution, use the concept of window.screen."
},
{
"code": null,
"e": 1160,
"s": 1129,
"text": "For width, use the following −"
},
{
"code": null,
"e": 1185,
"s": 1160,
"text": "window.screen.availWidth"
},
{
"code": null,
"e": 1198,
"s": 1185,
"text": "For height −"
},
{
"code": null,
"e": 1224,
"s": 1198,
"text": "window.screen.availHeight"
},
{
"code": null,
"e": 1280,
"s": 1224,
"text": "Following is the code to detect the screen resolution −"
},
{
"code": null,
"e": 1291,
"s": 1280,
"text": " Live Demo"
},
{
"code": null,
"e": 1843,
"s": 1291,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<script>\n console.log(\"Available Width=\"+window.screen.availWidth);\n console.log(\"Available Height=\"+window.screen.availHeight);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2005,
"s": 1843,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2046,
"s": 2005,
"text": "This will produce the following output −"
}
] |
How to start an android application at boot time?
|
This example demonstrates how do I start an android application at boot time.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="24sp"
android:layout_centerInParent="true"
android:textStyle="bold"/>
</RelativeLayout>
Step 3 – Create a new Java class (StartAppOnBoot.java) and add the following code −
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartAppOnBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Step 4 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".StartAppOnBoot" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "This example demonstrates how do I start an android application at boot time."
},
{
"code": null,
"e": 1269,
"s": 1140,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1891,
"s": 1334,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World\"\n android:textSize=\"24sp\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1975,
"s": 1891,
"text": "Step 3 – Create a new Java class (StartAppOnBoot.java) and add the following code −"
},
{
"code": null,
"e": 2440,
"s": 1975,
"text": "import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\npublic class StartAppOnBoot extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {\n Intent i = new Intent(context, MainActivity.class);\n i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n context.startActivity(i);\n }\n }\n}"
},
{
"code": null,
"e": 2497,
"s": 2440,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2787,
"s": 2497,
"text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 2842,
"s": 2787,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3863,
"s": 2842,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver android:name=\".StartAppOnBoot\" >\n <intent-filter>\n <action android:name=\"android.intent.action.BOOT_COMPLETED\" />\n <action android:name=\"android.intent.action.QUICKBOOT_POWERON\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4210,
"s": 3863,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4251,
"s": 4210,
"text": "Click here to download the project code."
}
] |
iText - Formatting Cell Contents
|
In this chapter, we will see how to create a PDF document and add a table and format the contents of a cell in the table using the iText library.
You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method. You can format the contents of a cell in a table using the methods of the Cell class.
Following are the steps to format the contents of a cell in a table.
The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created.
Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below.
// Creating a PdfWriter
String dest = "C:/itextExamples/addingBackground.pdf";
PdfWriter writer = new PdfWriter(dest);
When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified.
The PdfDocument class is the class that represents the PDFDocument in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor.
Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below.
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class.
The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument.
Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below.
// Creating a Document
Document document = new Document(pdfDoc);
The Table class represents a two-dimensional grid filled with cells, ordered in rows and columns. It belongs to the package com.itextpdf.layout.element.
Instantiate the Table class as shown below.
// Creating a table
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element. Add the contents of the cell using the add() method of the Cell class, as shown below.
// Adding cell 1 to the table
Cell cell1 = new Cell(); // Creating a cell
cell1.add("Name"); // Adding content to the cell
// Adding cell 2 to the table
Cell cell2 = new Cell(); // Creating a cell
cell2.add("Raju"); // Adding content to the cell
Once you created the cell and added contents to it, you can format the cell. For example, you can set its background, align the text inside the cell, change the text color, etc., using different methods of the cell class such as setBackgroundColor(), setBorder(), setTextAlignment().
You can set the background color, border, and text alignment to the cell created in the previous step, as shown below.
c1.setBackgroundColor(Color.DARK_GRAY); // Setting background color to cell1
c1.setBorder(Border.NO_BORDER); // Setting border to cell1
c1.setTextAlignment(TextAlignment.CENTER); // Setting text alignment to cell1
Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below.
table.addCell(c1);
Add the table object created in the previous step using the add() method of the Document class as shown below.
// Adding list to the document
document.add(table);
Close the document using the close() method of the Document class, as shown below.
// Closing the document
document.close();
The following Java program demonstrates how to format the contents of a cell in a table using the iText library. It creates a PDF document with the name addingBackground.pdf, adds a table to it, formats the contents of its cells, and saves it in the path C:/itextExamples/
Save this code in a file with the name BackgroundToTable.java.
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
public class BackgroundToTable {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/addingBackground.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
// Populating row 1 and adding it to the table
Cell c1 = new Cell(); // Creating cell 1
c1.add("Name"); // Adding name to cell 1
c1.setBackgroundColor(Color.DARK_GRAY); // Setting background color
c1.setBorder(Border.NO_BORDER); // Setting border
c1.setTextAlignment(TextAlignment.CENTER); // Setting text alignment
table.addCell(c1); // Adding cell 1 to the table
Cell c2 = new
Cell();
c2.add("Raju");
c2.setBackgroundColor(Color.GRAY);
c2.setBorder(Border.NO_BORDER);
c2.setTextAlignment(TextAlignment.CENTER);
table.addCell(c2);
// Populating row 2 and adding it to the table
Cell c3 = new Cell();
c3.add("Id");
c3.setBackgroundColor(Color.WHITE);
c3.setBorder(Border.NO_BORDER);
c3.setTextAlignment(TextAlignment.CENTER);
table.addCell(c3);
Cell c4 = new Cell();
c4.add("001");
c4.setBackgroundColor(Color.WHITE);
c4.setBorder(Border.NO_BORDER);
c4.setTextAlignment(TextAlignment.CENTER);
table.addCell(c4);
// Populating row 3 and adding it to the table
Cell c5 = new Cell();
c5.add("Designation");
c5.setBackgroundColor(Color.DARK_GRAY);
c5.setBorder(Border.NO_BORDER);
c5.setTextAlignment(TextAlignment.CENTER);
table.addCell(c5);
Cell c6 = new Cell();
c6.add("Programmer");
c6.setBackgroundColor(Color.GRAY);
c6.setBorder(Border.NO_BORDER);
c6.setTextAlignment(TextAlignment.CENTER);
table.addCell(c6);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Background added successfully..");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac BackgroundToTable.java
java BackgroundToTable
Upon execution, the above program creates a PDF document, displaying the following message.
Background added successfully..
If you verify the specified path, you can find the created PDF document, as shown below.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2514,
"s": 2368,
"text": "In this chapter, we will see how to create a PDF document and add a table and format the contents of a cell in the table using the iText library."
},
{
"code": null,
"e": 2918,
"s": 2514,
"text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method. You can format the contents of a cell in a table using the methods of the Cell class."
},
{
"code": null,
"e": 2987,
"s": 2918,
"text": "Following are the steps to format the contents of a cell in a table."
},
{
"code": null,
"e": 3216,
"s": 2987,
"text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created."
},
{
"code": null,
"e": 3365,
"s": 3216,
"text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below."
},
{
"code": null,
"e": 3488,
"s": 3365,
"text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/addingBackground.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n"
},
{
"code": null,
"e": 3628,
"s": 3488,
"text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified."
},
{
"code": null,
"e": 3879,
"s": 3628,
"text": "The PdfDocument class is the class that represents the PDFDocument in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor."
},
{
"code": null,
"e": 3995,
"s": 3879,
"text": "Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below."
},
{
"code": null,
"e": 4071,
"s": 3995,
"text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n"
},
{
"code": null,
"e": 4242,
"s": 4071,
"text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class."
},
{
"code": null,
"e": 4436,
"s": 4242,
"text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument."
},
{
"code": null,
"e": 4561,
"s": 4436,
"text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below."
},
{
"code": null,
"e": 4631,
"s": 4561,
"text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n"
},
{
"code": null,
"e": 4784,
"s": 4631,
"text": "The Table class represents a two-dimensional grid filled with cells, ordered in rows and columns. It belongs to the package com.itextpdf.layout.element."
},
{
"code": null,
"e": 4828,
"s": 4784,
"text": "Instantiate the Table class as shown below."
},
{
"code": null,
"e": 4939,
"s": 4828,
"text": "// Creating a table \nfloat [] pointColumnWidths = {200F, 200F}; \nTable table = new Table(pointColumnWidths); \n"
},
{
"code": null,
"e": 5123,
"s": 4939,
"text": "Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element. Add the contents of the cell using the add() method of the Cell class, as shown below."
},
{
"code": null,
"e": 5411,
"s": 5123,
"text": "// Adding cell 1 to the table \nCell cell1 = new Cell(); // Creating a cell \ncell1.add(\"Name\"); // Adding content to the cell \n\n// Adding cell 2 to the table \nCell cell2 = new Cell(); // Creating a cell \ncell2.add(\"Raju\"); // Adding content to the cell \n"
},
{
"code": null,
"e": 5695,
"s": 5411,
"text": "Once you created the cell and added contents to it, you can format the cell. For example, you can set its background, align the text inside the cell, change the text color, etc., using different methods of the cell class such as setBackgroundColor(), setBorder(), setTextAlignment()."
},
{
"code": null,
"e": 5814,
"s": 5695,
"text": "You can set the background color, border, and text alignment to the cell created in the previous step, as shown below."
},
{
"code": null,
"e": 6046,
"s": 5814,
"text": "c1.setBackgroundColor(Color.DARK_GRAY); // Setting background color to cell1 \nc1.setBorder(Border.NO_BORDER); // Setting border to cell1 \nc1.setTextAlignment(TextAlignment.CENTER); // Setting text alignment to cell1 \n"
},
{
"code": null,
"e": 6203,
"s": 6046,
"text": "Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below."
},
{
"code": null,
"e": 6223,
"s": 6203,
"text": "table.addCell(c1);\n"
},
{
"code": null,
"e": 6334,
"s": 6223,
"text": "Add the table object created in the previous step using the add() method of the Document class as shown below."
},
{
"code": null,
"e": 6388,
"s": 6334,
"text": "// Adding list to the document \ndocument.add(table);\n"
},
{
"code": null,
"e": 6471,
"s": 6388,
"text": "Close the document using the close() method of the Document class, as shown below."
},
{
"code": null,
"e": 6515,
"s": 6471,
"text": "// Closing the document \ndocument.close();\n"
},
{
"code": null,
"e": 6788,
"s": 6515,
"text": "The following Java program demonstrates how to format the contents of a cell in a table using the iText library. It creates a PDF document with the name addingBackground.pdf, adds a table to it, formats the contents of its cells, and saves it in the path C:/itextExamples/"
},
{
"code": null,
"e": 6851,
"s": 6788,
"text": "Save this code in a file with the name BackgroundToTable.java."
},
{
"code": null,
"e": 10110,
"s": 6851,
"text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document;\nimport com.itextpdf.layout.border.Border; \nimport com.itextpdf.layout.element.Cell; \nimport com.itextpdf.layout.element.Table; \nimport com.itextpdf.layout.property.TextAlignment; \n\npublic class BackgroundToTable { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter object \n String dest = \"C:/itextExamples/addingBackground.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(writer); \n \n // Creating a Document object \n Document doc = new Document(pdfDoc); \n \n // Creating a table \n float [] pointColumnWidths = {200F, 200F}; \n Table table = new Table(pointColumnWidths);\n \n // Populating row 1 and adding it to the table \n Cell c1 = new Cell(); // Creating cell 1 \n c1.add(\"Name\"); // Adding name to cell 1 \n c1.setBackgroundColor(Color.DARK_GRAY); // Setting background color\n c1.setBorder(Border.NO_BORDER); // Setting border\n c1.setTextAlignment(TextAlignment.CENTER); // Setting text alignment \n table.addCell(c1); // Adding cell 1 to the table \n \n Cell c2 = new \n Cell(); \n c2.add(\"Raju\"); \n c2.setBackgroundColor(Color.GRAY); \n c2.setBorder(Border.NO_BORDER); \n c2.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c2); \n \n // Populating row 2 and adding it to the table \n Cell c3 = new Cell(); \n c3.add(\"Id\"); \n c3.setBackgroundColor(Color.WHITE); \n c3.setBorder(Border.NO_BORDER); \n c3.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c3); \n \n Cell c4 = new Cell(); \n c4.add(\"001\"); \n c4.setBackgroundColor(Color.WHITE); \n c4.setBorder(Border.NO_BORDER); \n c4.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c4); \n \n // Populating row 3 and adding it to the table \n Cell c5 = new Cell(); \n c5.add(\"Designation\"); \n c5.setBackgroundColor(Color.DARK_GRAY); \n c5.setBorder(Border.NO_BORDER); \n c5.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c5); \n \n Cell c6 = new Cell(); \n c6.add(\"Programmer\"); \n c6.setBackgroundColor(Color.GRAY); \n c6.setBorder(Border.NO_BORDER); \n c6.setTextAlignment(TextAlignment.CENTER); \n table.addCell(c6); \n \n // Adding Table to document \n doc.add(table); \n \n // Closing the document \n doc.close(); \n \n System.out.println(\"Background added successfully..\"); \n } \n} "
},
{
"code": null,
"e": 10205,
"s": 10110,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 10260,
"s": 10205,
"text": "javac BackgroundToTable.java \njava BackgroundToTable \n"
},
{
"code": null,
"e": 10352,
"s": 10260,
"text": "Upon execution, the above program creates a PDF document, displaying the following message."
},
{
"code": null,
"e": 10385,
"s": 10352,
"text": "Background added successfully..\n"
},
{
"code": null,
"e": 10474,
"s": 10385,
"text": "If you verify the specified path, you can find the created PDF document, as shown below."
},
{
"code": null,
"e": 10481,
"s": 10474,
"text": " Print"
},
{
"code": null,
"e": 10492,
"s": 10481,
"text": " Add Notes"
}
] |
How to Generate Data Accessing API Endpoints Without Even Coding | by Christopher Tao | Towards Data Science
|
As the most common architecture of any Web or Mobile applications, database + backend API + frontend is very typical and classic. While different applications will definitely have their own front-end design, the backend API is usually very similar. That is, they must be able to access the data in the database. In other words, the major responsibility of the backend API is acting as a middleware to receive the requests from the front-end and retrieve the database based on the requests, and then return the results to the front-end so that the users can consume.
Of course, for most of the applications, the backend API also needs a certain level of customising, especially the security requirement such as JWT and so on. However, when there is not too much security concern, there is a way to “generate” your backend API that can access your database without even coding.
In this article, I’ll introduce a Python library can do this for you. Imagine that you are a front-end developer, you just want to test some front-end features in your testing environment and don’t want to waste too much time on writing your own backend API. In this case, the Python library sandman2 is one of the best choices!
The sandman2 library supports many database management systems, such as:
SQLite
MySQL
PostgreSQL
Oracle
MS SQL Server
Sybase
Drizzle
Firebird
The sandman2 library supports them as different SQL “dialect”, which means that we don’t need to worry about which database we’re using, just tell sandman2 which database it is and it will work out-of-box.
In this article, I will use SQLite as an example because it is the easiest one, which I don’t need to download, install and configure anything.
In one of my previous article, I have introduced a Python built-in library sqlite3 that can generate an SQLite database very easily. I will skip introducing the SQLite library in Python. You can check out my article below for details.
towardsdatascience.com
Let’s create a database called “my-test”.
import sqlite3 as slcon = sl.connect('sandman2/my-test.db')
Then, create a table called USER for demonstrating purposes.
with con: con.execute(""" CREATE TABLE USER ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER ); """)
After that, let’s insert some sample rows.
sql = 'INSERT INTO USER (id, name, age) values(?, ?, ?)'data = [ (1, 'Alice', 21), (2, 'Bob', 22), (3, 'Chris', 23)]with con: con.executemany(sql, data)
OK. Now, we can query the table.
with con: data = con.execute("SELECT * FROM USER") for row in data: print(row)# Output:# (1, 'Alice', 21)# (2, 'Bob', 22)# (3, 'Chris', 23)
We have got a database with a populated table now. Let’s start to demo the sandman2 library in the next section.
Before everything, we need to install the sandman2 library. Just using pip.
pip install sandman2
Then, as I stated in the title, we don’t need to write ANY code, just using the command-line interface.
$ sandman2ctl sqlite+pysqlite:///sandman2/my-test.db
The illustration below shows how the connection string is constructed.
Please be noticed that the DB driver is optional. If we keep it empty, SQLAlchemy (sandman2 is built on top of SQLAlchemy) will try to use the default driver. However, it might complain if the driver does not exist. Don’t worry, we can get the name of the default driver library so that we can using pip to install it.
After running the command, the web services started.
Let’s try the web client using any browser to access the admin console.
http://localhost:5000/admin/
We can see that there is already an object USER on the page. That is because we have created this table. If we click USER, we can see that the three rows we inserted previously are displaying in a data table.
On this page, we can click the “Create” button to insert a new row, update an existing row or bulk deleting rows. You will be able to find these features easily, so let me skip those things and show you the most important feature in the next section.
The coolest feature of sandman2 must be the automatically generated RESTful API endpoints of the database we have connected to.
In the above section, keep the web service running, then the API is already there for us to use. You may prefer API testing tools such as Postman or Insomnia, but in this article, I’ll just use “curl” command to keep it simple, so you don’t have to download anything if you just want to test the API endpoints.
Remember we have a table called USER? Now, we can simply send GET request to the following URL to get a list of entries.
http://localhost:5000/user/
Please be noticed that
Most of the DBMS such as SQLite and MySQL are not case sensitive, so we can use lower case for the table names safely.The forward slash / at the end of the URL must not be missed.
Most of the DBMS such as SQLite and MySQL are not case sensitive, so we can use lower case for the table names safely.
The forward slash / at the end of the URL must not be missed.
Then, let’s test the GET API using curl.
curl http://localhost:5000/user/
It returned all records in the table. However, what if we have too many entries in a table and want to do the pagination? Yes, sandman2 supports that out-of-box!
curl "http://localhost:5000/user/?page=1&limit=2"curl "http://localhost:5000/user/?page=2&limit=2"
In this example, we use page parameter to specify the page number and the limit parameter to specify the page size. In page 1, we got the first two users Alice and Bob. Then, on page 2, we got the third row for Chris and only 1 row returned because there are no more rows.
Since we defined the primary key, we can also query the table by it.
curl http://localhost:5000/user/3
We can also filter the rows by any fields.
curl "http://localhost:5000/user/?name=Chris"
Currently, there is a limitation that filter on comparison >, <, >=, <= is not supported.
To insert a new row, we need to use the POST method.
curl -X POST -d "{\"age\":24, \"name\":\"David\"}" -H "Content-Type: application/json" http://localhost:5000/user/
Please be noticed that I’m using Windows so that the single quote won’t work in the cmd and I have to use backwards slashes to escape the double-quotes. You may not need those if you’re using Linux or Mac OS.
Also, we have set the “id” field as auto-increment when we create the USER table, so we don’t need to pass in the “id” values.
We can not go to the Web-based SQL client to check the table. The new user David is successfully inserted.
We can use the PATCH method to update a row.
curl -X PATCH -d "{\"age\":30}" -H "Content-Type: application/json" http://localhost:5000/user/3
As shown in the example, it is important to pass the current primary key “id” in the URL, which is “3” in our example. Sandman2 relies on the primary key to find the record to be updated.
If we go back to the web client, it can be seen that the age of Chris has been updated.
We can use the DELETE method to delete a row.
curl -X DELETE -H "Content-Type: application/json" http://localhost:5000/user/3
After running the above CURL command, the user with “id=3” has been deleted.
The sandman2 library supports not only the general data accessing API but also some other advanced API, such as getting the metadata of a table.
curl http://localhost:5000/user/meta
Finally, it also supports exporting data to a CSV file.
curl -o user.csv "http://localhost:5000/user/?export"
In this article, I have introduced an amazing Python library called sandman2. It is written in Python but you don’t need to write ANY Python code to use it. By simply running it with a valid database connection string, you will get
A Web-based SQL client
An entire set of data accessing RESTful API
It turns out that there is not too much security implementation in sandman2, so please never use it in production. However, security concerns usually mean customised implementation which is almost impossible to be generalised in an out-of-box toolset. Therefore, sandmand2 is one of the excellent libraries that can save us a lot of time in testing and experimenting.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
|
[
{
"code": null,
"e": 737,
"s": 171,
"text": "As the most common architecture of any Web or Mobile applications, database + backend API + frontend is very typical and classic. While different applications will definitely have their own front-end design, the backend API is usually very similar. That is, they must be able to access the data in the database. In other words, the major responsibility of the backend API is acting as a middleware to receive the requests from the front-end and retrieve the database based on the requests, and then return the results to the front-end so that the users can consume."
},
{
"code": null,
"e": 1047,
"s": 737,
"text": "Of course, for most of the applications, the backend API also needs a certain level of customising, especially the security requirement such as JWT and so on. However, when there is not too much security concern, there is a way to “generate” your backend API that can access your database without even coding."
},
{
"code": null,
"e": 1376,
"s": 1047,
"text": "In this article, I’ll introduce a Python library can do this for you. Imagine that you are a front-end developer, you just want to test some front-end features in your testing environment and don’t want to waste too much time on writing your own backend API. In this case, the Python library sandman2 is one of the best choices!"
},
{
"code": null,
"e": 1449,
"s": 1376,
"text": "The sandman2 library supports many database management systems, such as:"
},
{
"code": null,
"e": 1456,
"s": 1449,
"text": "SQLite"
},
{
"code": null,
"e": 1462,
"s": 1456,
"text": "MySQL"
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1480,
"s": 1473,
"text": "Oracle"
},
{
"code": null,
"e": 1494,
"s": 1480,
"text": "MS SQL Server"
},
{
"code": null,
"e": 1501,
"s": 1494,
"text": "Sybase"
},
{
"code": null,
"e": 1509,
"s": 1501,
"text": "Drizzle"
},
{
"code": null,
"e": 1518,
"s": 1509,
"text": "Firebird"
},
{
"code": null,
"e": 1724,
"s": 1518,
"text": "The sandman2 library supports them as different SQL “dialect”, which means that we don’t need to worry about which database we’re using, just tell sandman2 which database it is and it will work out-of-box."
},
{
"code": null,
"e": 1868,
"s": 1724,
"text": "In this article, I will use SQLite as an example because it is the easiest one, which I don’t need to download, install and configure anything."
},
{
"code": null,
"e": 2103,
"s": 1868,
"text": "In one of my previous article, I have introduced a Python built-in library sqlite3 that can generate an SQLite database very easily. I will skip introducing the SQLite library in Python. You can check out my article below for details."
},
{
"code": null,
"e": 2126,
"s": 2103,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2168,
"s": 2126,
"text": "Let’s create a database called “my-test”."
},
{
"code": null,
"e": 2228,
"s": 2168,
"text": "import sqlite3 as slcon = sl.connect('sandman2/my-test.db')"
},
{
"code": null,
"e": 2289,
"s": 2228,
"text": "Then, create a table called USER for demonstrating purposes."
},
{
"code": null,
"e": 2466,
"s": 2289,
"text": "with con: con.execute(\"\"\" CREATE TABLE USER ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER ); \"\"\")"
},
{
"code": null,
"e": 2509,
"s": 2466,
"text": "After that, let’s insert some sample rows."
},
{
"code": null,
"e": 2674,
"s": 2509,
"text": "sql = 'INSERT INTO USER (id, name, age) values(?, ?, ?)'data = [ (1, 'Alice', 21), (2, 'Bob', 22), (3, 'Chris', 23)]with con: con.executemany(sql, data)"
},
{
"code": null,
"e": 2707,
"s": 2674,
"text": "OK. Now, we can query the table."
},
{
"code": null,
"e": 2860,
"s": 2707,
"text": "with con: data = con.execute(\"SELECT * FROM USER\") for row in data: print(row)# Output:# (1, 'Alice', 21)# (2, 'Bob', 22)# (3, 'Chris', 23)"
},
{
"code": null,
"e": 2973,
"s": 2860,
"text": "We have got a database with a populated table now. Let’s start to demo the sandman2 library in the next section."
},
{
"code": null,
"e": 3049,
"s": 2973,
"text": "Before everything, we need to install the sandman2 library. Just using pip."
},
{
"code": null,
"e": 3070,
"s": 3049,
"text": "pip install sandman2"
},
{
"code": null,
"e": 3174,
"s": 3070,
"text": "Then, as I stated in the title, we don’t need to write ANY code, just using the command-line interface."
},
{
"code": null,
"e": 3227,
"s": 3174,
"text": "$ sandman2ctl sqlite+pysqlite:///sandman2/my-test.db"
},
{
"code": null,
"e": 3298,
"s": 3227,
"text": "The illustration below shows how the connection string is constructed."
},
{
"code": null,
"e": 3617,
"s": 3298,
"text": "Please be noticed that the DB driver is optional. If we keep it empty, SQLAlchemy (sandman2 is built on top of SQLAlchemy) will try to use the default driver. However, it might complain if the driver does not exist. Don’t worry, we can get the name of the default driver library so that we can using pip to install it."
},
{
"code": null,
"e": 3670,
"s": 3617,
"text": "After running the command, the web services started."
},
{
"code": null,
"e": 3742,
"s": 3670,
"text": "Let’s try the web client using any browser to access the admin console."
},
{
"code": null,
"e": 3771,
"s": 3742,
"text": "http://localhost:5000/admin/"
},
{
"code": null,
"e": 3980,
"s": 3771,
"text": "We can see that there is already an object USER on the page. That is because we have created this table. If we click USER, we can see that the three rows we inserted previously are displaying in a data table."
},
{
"code": null,
"e": 4231,
"s": 3980,
"text": "On this page, we can click the “Create” button to insert a new row, update an existing row or bulk deleting rows. You will be able to find these features easily, so let me skip those things and show you the most important feature in the next section."
},
{
"code": null,
"e": 4359,
"s": 4231,
"text": "The coolest feature of sandman2 must be the automatically generated RESTful API endpoints of the database we have connected to."
},
{
"code": null,
"e": 4670,
"s": 4359,
"text": "In the above section, keep the web service running, then the API is already there for us to use. You may prefer API testing tools such as Postman or Insomnia, but in this article, I’ll just use “curl” command to keep it simple, so you don’t have to download anything if you just want to test the API endpoints."
},
{
"code": null,
"e": 4791,
"s": 4670,
"text": "Remember we have a table called USER? Now, we can simply send GET request to the following URL to get a list of entries."
},
{
"code": null,
"e": 4819,
"s": 4791,
"text": "http://localhost:5000/user/"
},
{
"code": null,
"e": 4842,
"s": 4819,
"text": "Please be noticed that"
},
{
"code": null,
"e": 5022,
"s": 4842,
"text": "Most of the DBMS such as SQLite and MySQL are not case sensitive, so we can use lower case for the table names safely.The forward slash / at the end of the URL must not be missed."
},
{
"code": null,
"e": 5141,
"s": 5022,
"text": "Most of the DBMS such as SQLite and MySQL are not case sensitive, so we can use lower case for the table names safely."
},
{
"code": null,
"e": 5203,
"s": 5141,
"text": "The forward slash / at the end of the URL must not be missed."
},
{
"code": null,
"e": 5244,
"s": 5203,
"text": "Then, let’s test the GET API using curl."
},
{
"code": null,
"e": 5277,
"s": 5244,
"text": "curl http://localhost:5000/user/"
},
{
"code": null,
"e": 5439,
"s": 5277,
"text": "It returned all records in the table. However, what if we have too many entries in a table and want to do the pagination? Yes, sandman2 supports that out-of-box!"
},
{
"code": null,
"e": 5538,
"s": 5439,
"text": "curl \"http://localhost:5000/user/?page=1&limit=2\"curl \"http://localhost:5000/user/?page=2&limit=2\""
},
{
"code": null,
"e": 5811,
"s": 5538,
"text": "In this example, we use page parameter to specify the page number and the limit parameter to specify the page size. In page 1, we got the first two users Alice and Bob. Then, on page 2, we got the third row for Chris and only 1 row returned because there are no more rows."
},
{
"code": null,
"e": 5880,
"s": 5811,
"text": "Since we defined the primary key, we can also query the table by it."
},
{
"code": null,
"e": 5914,
"s": 5880,
"text": "curl http://localhost:5000/user/3"
},
{
"code": null,
"e": 5957,
"s": 5914,
"text": "We can also filter the rows by any fields."
},
{
"code": null,
"e": 6003,
"s": 5957,
"text": "curl \"http://localhost:5000/user/?name=Chris\""
},
{
"code": null,
"e": 6093,
"s": 6003,
"text": "Currently, there is a limitation that filter on comparison >, <, >=, <= is not supported."
},
{
"code": null,
"e": 6146,
"s": 6093,
"text": "To insert a new row, we need to use the POST method."
},
{
"code": null,
"e": 6261,
"s": 6146,
"text": "curl -X POST -d \"{\\\"age\\\":24, \\\"name\\\":\\\"David\\\"}\" -H \"Content-Type: application/json\" http://localhost:5000/user/"
},
{
"code": null,
"e": 6470,
"s": 6261,
"text": "Please be noticed that I’m using Windows so that the single quote won’t work in the cmd and I have to use backwards slashes to escape the double-quotes. You may not need those if you’re using Linux or Mac OS."
},
{
"code": null,
"e": 6597,
"s": 6470,
"text": "Also, we have set the “id” field as auto-increment when we create the USER table, so we don’t need to pass in the “id” values."
},
{
"code": null,
"e": 6704,
"s": 6597,
"text": "We can not go to the Web-based SQL client to check the table. The new user David is successfully inserted."
},
{
"code": null,
"e": 6749,
"s": 6704,
"text": "We can use the PATCH method to update a row."
},
{
"code": null,
"e": 6846,
"s": 6749,
"text": "curl -X PATCH -d \"{\\\"age\\\":30}\" -H \"Content-Type: application/json\" http://localhost:5000/user/3"
},
{
"code": null,
"e": 7034,
"s": 6846,
"text": "As shown in the example, it is important to pass the current primary key “id” in the URL, which is “3” in our example. Sandman2 relies on the primary key to find the record to be updated."
},
{
"code": null,
"e": 7122,
"s": 7034,
"text": "If we go back to the web client, it can be seen that the age of Chris has been updated."
},
{
"code": null,
"e": 7168,
"s": 7122,
"text": "We can use the DELETE method to delete a row."
},
{
"code": null,
"e": 7248,
"s": 7168,
"text": "curl -X DELETE -H \"Content-Type: application/json\" http://localhost:5000/user/3"
},
{
"code": null,
"e": 7325,
"s": 7248,
"text": "After running the above CURL command, the user with “id=3” has been deleted."
},
{
"code": null,
"e": 7470,
"s": 7325,
"text": "The sandman2 library supports not only the general data accessing API but also some other advanced API, such as getting the metadata of a table."
},
{
"code": null,
"e": 7507,
"s": 7470,
"text": "curl http://localhost:5000/user/meta"
},
{
"code": null,
"e": 7563,
"s": 7507,
"text": "Finally, it also supports exporting data to a CSV file."
},
{
"code": null,
"e": 7617,
"s": 7563,
"text": "curl -o user.csv \"http://localhost:5000/user/?export\""
},
{
"code": null,
"e": 7849,
"s": 7617,
"text": "In this article, I have introduced an amazing Python library called sandman2. It is written in Python but you don’t need to write ANY Python code to use it. By simply running it with a valid database connection string, you will get"
},
{
"code": null,
"e": 7872,
"s": 7849,
"text": "A Web-based SQL client"
},
{
"code": null,
"e": 7916,
"s": 7872,
"text": "An entire set of data accessing RESTful API"
},
{
"code": null,
"e": 8284,
"s": 7916,
"text": "It turns out that there is not too much security implementation in sandman2, so please never use it in production. However, security concerns usually mean customised implementation which is almost impossible to be generalised in an out-of-box toolset. Therefore, sandmand2 is one of the excellent libraries that can save us a lot of time in testing and experimenting."
},
{
"code": null,
"e": 8295,
"s": 8284,
"text": "medium.com"
}
] |
Selenium Webdriver - Headless Execution
|
Selenium supports headless execution. In the Chrome browser, the headless execution can be implemented with the help of the ChromeOptions class. We have to create an object of this class and apply the add_arguments method on it. Finally, pass the parameter --headless to this method.
Let us obtain the title - About Careers at Tutorials Point - Tutorialspoint of the page launched in a headless mode −
The code implementation for the headless execution is as follows −
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
c = Options()
#passing headless parameter
c.add_argument("--headless")
#adding headless parameter to webdriver object
driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=c)
# implicit wait time
driver.implicitly_wait(5)
# url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
print('Page title: ' + driver.title)
# driver quit
driver.quit()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Careers at Tutorials Point - Tutorialspoint gets printed in the console.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2487,
"s": 2203,
"text": "Selenium supports headless execution. In the Chrome browser, the headless execution can be implemented with the help of the ChromeOptions class. We have to create an object of this class and apply the add_arguments method on it. Finally, pass the parameter --headless to this method."
},
{
"code": null,
"e": 2605,
"s": 2487,
"text": "Let us obtain the title - About Careers at Tutorials Point - Tutorialspoint of the page launched in a headless mode −"
},
{
"code": null,
"e": 2672,
"s": 2605,
"text": "The code implementation for the headless execution is as follows −"
},
{
"code": null,
"e": 3174,
"s": 2672,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#object of Options class\nc = Options()\n#passing headless parameter\nc.add_argument(\"--headless\")\n#adding headless parameter to webdriver object\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=c)\n# implicit wait time\ndriver.implicitly_wait(5)\n# url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\nprint('Page title: ' + driver.title)\n# driver quit\ndriver.quit()"
},
{
"code": null,
"e": 3448,
"s": 3174,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Careers at Tutorials Point - Tutorialspoint gets printed in the console."
},
{
"code": null,
"e": 3483,
"s": 3448,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3495,
"s": 3483,
"text": " Aditya Dua"
},
{
"code": null,
"e": 3531,
"s": 3495,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3545,
"s": 3531,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3582,
"s": 3545,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3604,
"s": 3582,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3637,
"s": 3604,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3651,
"s": 3637,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3686,
"s": 3651,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3700,
"s": 3686,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3737,
"s": 3700,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3751,
"s": 3737,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3758,
"s": 3751,
"text": " Print"
},
{
"code": null,
"e": 3769,
"s": 3758,
"text": " Add Notes"
}
] |
Prim’s Algorithm (Simple Implementation for Adjacency Matrix Representation) in C++
|
Prim’s Algorithm is a greedy method that is used to find minimum spanning tree for a given weighted undirected graph.
Weighted graph is a graph that has all edges with weight values.
Undirected graph is a special type of graph in which all edges are bidirectional.
Minimum spanning tree is a subset that contains all edges and vertices but no cycle and has the least possible total edge weight.
In this article, we will learn about prim’s algorithm to find minimum spanning tree. Usually, the algorithm uses two arrays but in this solution, we will use only one.
Program to show the implementation of prim’s algorithm.
Live Demo
#include <bits/stdc++.h>
using namespace std;
#define V 5
bool createsMST(int u, int v, vector<bool> inMST){
if (u == v)
return false;
if (inMST[u] == false && inMST[v] == false)
return false;
else if (inMST[u] == true && inMST[v] == true)
return false;
return true;
}
void printMinSpanningTree(int cost[][V]){
vector<bool> inMST(V, false);
inMST[0] = true;
int edgeNo = 0, MSTcost = 0;
while (edgeNo < V - 1) {
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (cost[i][j] < min) {
if (createsMST(i, j, inMST)) {
min = cost[i][j];
a = i;
b = j;
}
}
}
}
if (a != -1 && b != -1) {
cout<<"Edge "<<edgeNo++<<" : ("<<a<<" , "<<b<<" ) : cost = "<<min<<endl;
MSTcost += min;
inMST[b] = inMST[a] = true;
}
}
cout<<"Cost of Minimum spanning tree ="<<MSTcost;
}
int main() {
int cost[][V] = {
{ INT_MAX, 12, INT_MAX, 25, INT_MAX },
{ 12, INT_MAX, 11, 8, 12 },
{ INT_MAX, 11, INT_MAX, INT_MAX, 17 },
{ 25, 8, INT_MAX, INT_MAX, 15 },
{ INT_MAX, 12, 17, 15, INT_MAX },
};
cout<<"The Minimum spanning tree for the given tree is :\n";
printMinSpanningTree(cost);
return 0;
}
The Minimum spanning tree for the given tree is :
Edge 0 : (0 , 1 ) : cost = 12
Edge 1 : (1 , 3 ) : cost = 8
Edge 2 : (1 , 2 ) : cost = 11
Edge 3 : (1 , 4 ) : cost = 12
Cost of Minimum spanning tree =43
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Prim’s Algorithm is a greedy method that is used to find minimum spanning tree for a given weighted undirected graph."
},
{
"code": null,
"e": 1245,
"s": 1180,
"text": "Weighted graph is a graph that has all edges with weight values."
},
{
"code": null,
"e": 1327,
"s": 1245,
"text": "Undirected graph is a special type of graph in which all edges are bidirectional."
},
{
"code": null,
"e": 1457,
"s": 1327,
"text": "Minimum spanning tree is a subset that contains all edges and vertices but no cycle and has the least possible total edge weight."
},
{
"code": null,
"e": 1625,
"s": 1457,
"text": "In this article, we will learn about prim’s algorithm to find minimum spanning tree. Usually, the algorithm uses two arrays but in this solution, we will use only one."
},
{
"code": null,
"e": 1681,
"s": 1625,
"text": "Program to show the implementation of prim’s algorithm."
},
{
"code": null,
"e": 1692,
"s": 1681,
"text": " Live Demo"
},
{
"code": null,
"e": 3077,
"s": 1692,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n#define V 5\nbool createsMST(int u, int v, vector<bool> inMST){\n if (u == v)\n return false;\n if (inMST[u] == false && inMST[v] == false)\n return false;\n else if (inMST[u] == true && inMST[v] == true)\n return false;\n return true;\n}\nvoid printMinSpanningTree(int cost[][V]){\n vector<bool> inMST(V, false);\n inMST[0] = true;\n int edgeNo = 0, MSTcost = 0;\n while (edgeNo < V - 1) {\n int min = INT_MAX, a = -1, b = -1;\n for (int i = 0; i < V; i++) {\n for (int j = 0; j < V; j++) {\n if (cost[i][j] < min) {\n if (createsMST(i, j, inMST)) {\n min = cost[i][j];\n a = i;\n b = j;\n }\n }\n }\n }\n if (a != -1 && b != -1) {\n cout<<\"Edge \"<<edgeNo++<<\" : (\"<<a<<\" , \"<<b<<\" ) : cost = \"<<min<<endl;\n MSTcost += min;\n inMST[b] = inMST[a] = true;\n }\n }\n cout<<\"Cost of Minimum spanning tree =\"<<MSTcost;\n}\nint main() {\n int cost[][V] = {\n { INT_MAX, 12, INT_MAX, 25, INT_MAX },\n { 12, INT_MAX, 11, 8, 12 },\n { INT_MAX, 11, INT_MAX, INT_MAX, 17 },\n { 25, 8, INT_MAX, INT_MAX, 15 },\n { INT_MAX, 12, 17, 15, INT_MAX },\n };\n cout<<\"The Minimum spanning tree for the given tree is :\\n\";\n printMinSpanningTree(cost);\n return 0;\n}"
},
{
"code": null,
"e": 3280,
"s": 3077,
"text": "The Minimum spanning tree for the given tree is :\nEdge 0 : (0 , 1 ) : cost = 12\nEdge 1 : (1 , 3 ) : cost = 8\nEdge 2 : (1 , 2 ) : cost = 11\nEdge 3 : (1 , 4 ) : cost = 12\nCost of Minimum spanning tree =43"
}
] |
Python | Find frequency of largest element in list - GeeksforGeeks
|
20 Jul, 2021
Given a list, the task is to find the number of occurrences of the largest element of the list.Examples:
Input : [1, 2, 8, 5, 8, 7, 8]
Output :3
Input : [2, 9, 1, 3, 4, 5]
Output :1
Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list. Below is the implementation.
Python3
# Python program to find the# frequency of largest element L = [1, 2, 8, 5, 8, 7, 8] # print the frequency of largest elementfrequency = print(L.count(max(L)))
Output:
3
Method 2: Using collections.Counter() Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0.
Python3
# Python program to find the# frequency of largest element import collections L = [1, 2, 8, 5, 8, 7, 8] # find the largest elementlargest = max(L) # Storing the occurrences of each# element of list in resres = collections.Counter(L) print(res[largest])
Output:
3
Method 3: Using the dictionary In this approach, the number of occurrences of each element is stored in a dictionary as a key-value pair, where key is the element and value is the frequency.
Python3
# Python program to find the# frequency of largest element L = [1, 2, 8, 5, 8, 7, 8]d= {} # find the largest elementlargest = max(L) for i in L: if i in d: d[i] += 1 else: d[i] = 1 print(d[largest])
Output:
3
goshivank
akshaysingh98088
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
|
[
{
"code": null,
"e": 24687,
"s": 24659,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 24793,
"s": 24687,
"text": "Given a list, the task is to find the number of occurrences of the largest element of the list.Examples: "
},
{
"code": null,
"e": 24872,
"s": 24793,
"text": "Input : [1, 2, 8, 5, 8, 7, 8]\nOutput :3\n\n\nInput : [2, 9, 1, 3, 4, 5]\nOutput :1"
},
{
"code": null,
"e": 25116,
"s": 24872,
"text": "Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list. Below is the implementation. "
},
{
"code": null,
"e": 25124,
"s": 25116,
"text": "Python3"
},
{
"code": "# Python program to find the# frequency of largest element L = [1, 2, 8, 5, 8, 7, 8] # print the frequency of largest elementfrequency = print(L.count(max(L))) ",
"e": 25297,
"s": 25124,
"text": null
},
{
"code": null,
"e": 25307,
"s": 25297,
"text": "Output: "
},
{
"code": null,
"e": 25309,
"s": 25307,
"text": "3"
},
{
"code": null,
"e": 25520,
"s": 25309,
"text": "Method 2: Using collections.Counter() Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0. "
},
{
"code": null,
"e": 25528,
"s": 25520,
"text": "Python3"
},
{
"code": "# Python program to find the# frequency of largest element import collections L = [1, 2, 8, 5, 8, 7, 8] # find the largest elementlargest = max(L) # Storing the occurrences of each# element of list in resres = collections.Counter(L) print(res[largest])",
"e": 25781,
"s": 25528,
"text": null
},
{
"code": null,
"e": 25791,
"s": 25781,
"text": "Output: "
},
{
"code": null,
"e": 25793,
"s": 25791,
"text": "3"
},
{
"code": null,
"e": 25985,
"s": 25793,
"text": "Method 3: Using the dictionary In this approach, the number of occurrences of each element is stored in a dictionary as a key-value pair, where key is the element and value is the frequency. "
},
{
"code": null,
"e": 25993,
"s": 25985,
"text": "Python3"
},
{
"code": "# Python program to find the# frequency of largest element L = [1, 2, 8, 5, 8, 7, 8]d= {} # find the largest elementlargest = max(L) for i in L: if i in d: d[i] += 1 else: d[i] = 1 print(d[largest])",
"e": 26221,
"s": 25993,
"text": null
},
{
"code": null,
"e": 26231,
"s": 26221,
"text": "Output: "
},
{
"code": null,
"e": 26233,
"s": 26231,
"text": "3"
},
{
"code": null,
"e": 26245,
"s": 26235,
"text": "goshivank"
},
{
"code": null,
"e": 26262,
"s": 26245,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 26283,
"s": 26262,
"text": "Python list-programs"
},
{
"code": null,
"e": 26290,
"s": 26283,
"text": "Python"
},
{
"code": null,
"e": 26388,
"s": 26290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26397,
"s": 26388,
"text": "Comments"
},
{
"code": null,
"e": 26410,
"s": 26397,
"text": "Old Comments"
},
{
"code": null,
"e": 26428,
"s": 26410,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26450,
"s": 26428,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26485,
"s": 26450,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26507,
"s": 26485,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26549,
"s": 26507,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26574,
"s": 26549,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26606,
"s": 26574,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26622,
"s": 26606,
"text": "Deque in Python"
},
{
"code": null,
"e": 26648,
"s": 26622,
"text": "Python String | replace()"
}
] |
java.time.LocalDateTime.atZone() Method Example
|
The java.time.LocalDateTime.atZone(ZoneId zone) method combines this date-time with a time-zone to create a ZonedDateTime..
Following is the declaration for java.time.LocalDateTime.atZone(ZoneId zone) method.
public ZonedDateTime atZone(ZoneId zone)
zone − the time-zone to use, not null.
the zoned date-time formed from this date-time, not null.
The following example shows the usage of java.time.LocalDateTime.atZone(ZoneId zone) method.
package com.tutorialspoint;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.parse("2017-02-03T12:30:30");
System.out.println(date);
ZonedDateTime date1 = date.atZone(ZoneId.systemDefault());
System.out.println(date1);
}
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T12:30:30
2017-02-03T12:30:30+05:30[Asia/Calcutta]
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2039,
"s": 1915,
"text": "The java.time.LocalDateTime.atZone(ZoneId zone) method combines this date-time with a time-zone to create a ZonedDateTime.."
},
{
"code": null,
"e": 2124,
"s": 2039,
"text": "Following is the declaration for java.time.LocalDateTime.atZone(ZoneId zone) method."
},
{
"code": null,
"e": 2166,
"s": 2124,
"text": "public ZonedDateTime atZone(ZoneId zone)\n"
},
{
"code": null,
"e": 2205,
"s": 2166,
"text": "zone − the time-zone to use, not null."
},
{
"code": null,
"e": 2263,
"s": 2205,
"text": "the zoned date-time formed from this date-time, not null."
},
{
"code": null,
"e": 2356,
"s": 2263,
"text": "The following example shows the usage of java.time.LocalDateTime.atZone(ZoneId zone) method."
},
{
"code": null,
"e": 2771,
"s": 2356,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDateTime;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.parse(\"2017-02-03T12:30:30\");\n System.out.println(date); \n ZonedDateTime date1 = date.atZone(ZoneId.systemDefault());\n System.out.println(date1); \n }\n}"
},
{
"code": null,
"e": 2854,
"s": 2771,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2916,
"s": 2854,
"text": "2017-02-03T12:30:30\n2017-02-03T12:30:30+05:30[Asia/Calcutta]\n"
},
{
"code": null,
"e": 2923,
"s": 2916,
"text": " Print"
},
{
"code": null,
"e": 2934,
"s": 2923,
"text": " Add Notes"
}
] |
Creating a Weapon Detector in 5 simple steps | by Rahul Agarwal | Towards Data Science
|
Object Detection is a helpful tool to have in your coding repository.
It forms the backbone of many fantastic industrial applications. Some of them being self-driving cars, medical imaging and face detection.
In my last post on Object detection, I talked about how Object detection models evolved.
But what good is theory, if we can’t implement it?
This post is about implementing and getting an object detector on our custom dataset of weapons.
The problem we will specifically solve today is that of Instance Segmentation using Mask-RCNN.
Can we create masks for each object in the image? Specifically something like:
The most common way to solve this problem is by using Mask-RCNN. The architecture of Mask-RCNN looks like below:
Essentially, it comprises of:
A backbone network like resnet50/resnet101
A Region Proposal network
ROI-Align layers
Two output layers — one to predict masks and one to predict class and bounding box.
There is a lot more to it. If you want to learn more about the theory, read my last post.
towardsdatascience.com
This post is mostly going to be about the code.
The use case we will be working on is a weapon detector. A weapon detector is something that can be used in conjunction with street cameras as well as CCTV’s to fight crime. So it is pretty nifty.
So, I started with downloading 40 images each of guns and swords from the open image dataset and annotated them using the VIA tool. Now setting up the annotation project in VIA is petty important, so I will try to explain it step by step.
VIA is an annotation tool, using which you can annotate images both bounding boxes as well as masks. I found it as one of the best tools to do annotation as it is online and runs in the browser itself.
To use it, open http://www.robots.ox.ac.uk/~vgg/software/via/via.html
You will see a page like:
The next thing we want to do is to add the different class names in the region_attributes. Here I have added ‘gun’ and ‘sword’ as per our use case as these are the two distinct targets I want to annotate.
I have kept all the files in the folder data. Next step is to add the files we want to annotate. We can add files in the data folder using the “Add Files” button in the VIA tool. And start annotating along with labels as shown below after selecting the polyline tool.
Click on save project on the top menu of the VIA tool.
Save file as via_region_data.json by changing the project name field. This will save the annotations in COCO format.
We will need to set up the data directories first so that we can do object detection. In the code below, I am creating a directory structure that is required for the model that we are going to use.
After running the above code, we will get the data in the below folder structure:
- procdata - train - img1.jpg - img2.jpg - via_region_data.json - val - img3.jpg - img4.jpg - via_region_data.json
We will use the code from the matterport/Mask_RCNN GitHub repository. You can start by cloning the repository and installing the required libraries.
git clone https://github.com/matterport/Mask_RCNNcd Mask_RCNNpip install -r requirements.txt
Once we are done with installing the dependencies and cloning the repo, we can start with implementing our project.
We make a copy of the samples/balloon directory in Mask_RCNN folder and create a samples/guns_and_swords directory where we will continue our work:
cp -r samples/balloon samples/guns_and_swords
We start by renaming and changing balloon.py in the samples/guns_and_swords directory to gns.py. The balloon.py file right now trains for one target. I have extended it to use multiple targets. In this file, we change:
balloonconfig to gnsConfigBalloonDataset to gnsDataset : We changed some code here to get the target names from our annotation data and also give multiple targets.And some changes in thetrain function
balloonconfig to gnsConfig
BalloonDataset to gnsDataset : We changed some code here to get the target names from our annotation data and also give multiple targets.
And some changes in thetrain function
Showing only the changedgnsConfig here to get you an idea. You can take a look at the whole gns.py code here.
Once we are done with changing the gns.py file,we can visualize our masks and images. You can do simply by following this Visualize Dataset.ipynb notebook.
To train the maskRCNN model, on the Guns and Swords dataset, we need to run one of the following commands on the command line based on if we want to initialise our model with COCO weights or imagenet weights:
# Train a new model starting from pre-trained COCO weights python3 gns.py train — dataset=/path/to/dataset — weights=coco# Resume training a model that you had trained earlier python3 gns.py train — dataset=/path/to/dataset — weights=last# Train a new model starting from ImageNet weights python3 gns.py train — dataset=/path/to/dataset — weights=imagenet
The command with weights=last will resume training from the last epoch. The weights are going to be saved in the logs directory in the Mask_RCNN folder.
This is how the loss looks after our final epoch.
You can take advantage of tensorboard to visualise how your network is performing. Just run:
tensorboard --logdir ~/objectDetection/Mask_RCNN/logs/gns20191010T1234
You can get the tensorboard at
https://localhost:6006
Here is how our mask loss looks like:
We can see that the validation loss is performing pretty abruptly. This is expected as we only have kept 20 images in the validation set.
Predicting a new image is also pretty easy. Just follow the prediction.ipynb notebook for a minimal example using our trained model. Below is the main part of the code.
This is how the result looks for some images in the validation set:
The results don’t look very promising and leave a lot to be desired, but that is to be expected because of very less training data(60 images). One can try to do the below things to improve the model performance for this weapon detector.
We just trained on 60 images due to time constraints. While we used transfer learning the data is still too less — Annotate more data.Train for more epochs and longer time. See how validation loss and training loss looks like.Change hyperparameters in the mrcnn/config file in the Mask_RCNN directory. For information on what these hyperparameters mean, take a look at my previous post. The main ones you can look at:
We just trained on 60 images due to time constraints. While we used transfer learning the data is still too less — Annotate more data.
Train for more epochs and longer time. See how validation loss and training loss looks like.
Change hyperparameters in the mrcnn/config file in the Mask_RCNN directory. For information on what these hyperparameters mean, take a look at my previous post. The main ones you can look at:
# if you want to provide different weights to different lossesLOSS_WEIGHTS ={'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}# Length of square anchor side in pixelsRPN_ANCHOR_SCALES = (32, 64, 128, 256, 512)# Ratios of anchors at each cell (width/height)# A value of 1 represents a square anchor, and 0.5 is a wide anchorRPN_ANCHOR_RATIOS = [0.5, 1, 2]
In this post, I talked about how to implement Instance segmentation using Mask-RCNN for a custom dataset.
I tried to make the coding part as simple as possible and hope you find the code useful. In the next part of this post, I will deploy this model using a web app. So stay tuned.
You can download the annotated weapons data as well as the code at Github.
If you want to know more about various Object Detection techniques, motion estimation, object tracking in video etc., I would like to recommend this awesome course on Deep Learning in Computer Vision
Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
Also, a small disclaimer — There might be some affiliate links in this post to relevant resources as sharing knowledge is never a bad idea.
|
[
{
"code": null,
"e": 242,
"s": 172,
"text": "Object Detection is a helpful tool to have in your coding repository."
},
{
"code": null,
"e": 381,
"s": 242,
"text": "It forms the backbone of many fantastic industrial applications. Some of them being self-driving cars, medical imaging and face detection."
},
{
"code": null,
"e": 470,
"s": 381,
"text": "In my last post on Object detection, I talked about how Object detection models evolved."
},
{
"code": null,
"e": 521,
"s": 470,
"text": "But what good is theory, if we can’t implement it?"
},
{
"code": null,
"e": 618,
"s": 521,
"text": "This post is about implementing and getting an object detector on our custom dataset of weapons."
},
{
"code": null,
"e": 713,
"s": 618,
"text": "The problem we will specifically solve today is that of Instance Segmentation using Mask-RCNN."
},
{
"code": null,
"e": 792,
"s": 713,
"text": "Can we create masks for each object in the image? Specifically something like:"
},
{
"code": null,
"e": 905,
"s": 792,
"text": "The most common way to solve this problem is by using Mask-RCNN. The architecture of Mask-RCNN looks like below:"
},
{
"code": null,
"e": 935,
"s": 905,
"text": "Essentially, it comprises of:"
},
{
"code": null,
"e": 978,
"s": 935,
"text": "A backbone network like resnet50/resnet101"
},
{
"code": null,
"e": 1004,
"s": 978,
"text": "A Region Proposal network"
},
{
"code": null,
"e": 1021,
"s": 1004,
"text": "ROI-Align layers"
},
{
"code": null,
"e": 1105,
"s": 1021,
"text": "Two output layers — one to predict masks and one to predict class and bounding box."
},
{
"code": null,
"e": 1195,
"s": 1105,
"text": "There is a lot more to it. If you want to learn more about the theory, read my last post."
},
{
"code": null,
"e": 1218,
"s": 1195,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1266,
"s": 1218,
"text": "This post is mostly going to be about the code."
},
{
"code": null,
"e": 1463,
"s": 1266,
"text": "The use case we will be working on is a weapon detector. A weapon detector is something that can be used in conjunction with street cameras as well as CCTV’s to fight crime. So it is pretty nifty."
},
{
"code": null,
"e": 1702,
"s": 1463,
"text": "So, I started with downloading 40 images each of guns and swords from the open image dataset and annotated them using the VIA tool. Now setting up the annotation project in VIA is petty important, so I will try to explain it step by step."
},
{
"code": null,
"e": 1904,
"s": 1702,
"text": "VIA is an annotation tool, using which you can annotate images both bounding boxes as well as masks. I found it as one of the best tools to do annotation as it is online and runs in the browser itself."
},
{
"code": null,
"e": 1974,
"s": 1904,
"text": "To use it, open http://www.robots.ox.ac.uk/~vgg/software/via/via.html"
},
{
"code": null,
"e": 2000,
"s": 1974,
"text": "You will see a page like:"
},
{
"code": null,
"e": 2205,
"s": 2000,
"text": "The next thing we want to do is to add the different class names in the region_attributes. Here I have added ‘gun’ and ‘sword’ as per our use case as these are the two distinct targets I want to annotate."
},
{
"code": null,
"e": 2473,
"s": 2205,
"text": "I have kept all the files in the folder data. Next step is to add the files we want to annotate. We can add files in the data folder using the “Add Files” button in the VIA tool. And start annotating along with labels as shown below after selecting the polyline tool."
},
{
"code": null,
"e": 2528,
"s": 2473,
"text": "Click on save project on the top menu of the VIA tool."
},
{
"code": null,
"e": 2645,
"s": 2528,
"text": "Save file as via_region_data.json by changing the project name field. This will save the annotations in COCO format."
},
{
"code": null,
"e": 2843,
"s": 2645,
"text": "We will need to set up the data directories first so that we can do object detection. In the code below, I am creating a directory structure that is required for the model that we are going to use."
},
{
"code": null,
"e": 2925,
"s": 2843,
"text": "After running the above code, we will get the data in the below folder structure:"
},
{
"code": null,
"e": 3096,
"s": 2925,
"text": "- procdata - train - img1.jpg - img2.jpg - via_region_data.json - val - img3.jpg - img4.jpg - via_region_data.json"
},
{
"code": null,
"e": 3245,
"s": 3096,
"text": "We will use the code from the matterport/Mask_RCNN GitHub repository. You can start by cloning the repository and installing the required libraries."
},
{
"code": null,
"e": 3338,
"s": 3245,
"text": "git clone https://github.com/matterport/Mask_RCNNcd Mask_RCNNpip install -r requirements.txt"
},
{
"code": null,
"e": 3454,
"s": 3338,
"text": "Once we are done with installing the dependencies and cloning the repo, we can start with implementing our project."
},
{
"code": null,
"e": 3602,
"s": 3454,
"text": "We make a copy of the samples/balloon directory in Mask_RCNN folder and create a samples/guns_and_swords directory where we will continue our work:"
},
{
"code": null,
"e": 3648,
"s": 3602,
"text": "cp -r samples/balloon samples/guns_and_swords"
},
{
"code": null,
"e": 3867,
"s": 3648,
"text": "We start by renaming and changing balloon.py in the samples/guns_and_swords directory to gns.py. The balloon.py file right now trains for one target. I have extended it to use multiple targets. In this file, we change:"
},
{
"code": null,
"e": 4068,
"s": 3867,
"text": "balloonconfig to gnsConfigBalloonDataset to gnsDataset : We changed some code here to get the target names from our annotation data and also give multiple targets.And some changes in thetrain function"
},
{
"code": null,
"e": 4095,
"s": 4068,
"text": "balloonconfig to gnsConfig"
},
{
"code": null,
"e": 4233,
"s": 4095,
"text": "BalloonDataset to gnsDataset : We changed some code here to get the target names from our annotation data and also give multiple targets."
},
{
"code": null,
"e": 4271,
"s": 4233,
"text": "And some changes in thetrain function"
},
{
"code": null,
"e": 4381,
"s": 4271,
"text": "Showing only the changedgnsConfig here to get you an idea. You can take a look at the whole gns.py code here."
},
{
"code": null,
"e": 4537,
"s": 4381,
"text": "Once we are done with changing the gns.py file,we can visualize our masks and images. You can do simply by following this Visualize Dataset.ipynb notebook."
},
{
"code": null,
"e": 4746,
"s": 4537,
"text": "To train the maskRCNN model, on the Guns and Swords dataset, we need to run one of the following commands on the command line based on if we want to initialise our model with COCO weights or imagenet weights:"
},
{
"code": null,
"e": 5102,
"s": 4746,
"text": "# Train a new model starting from pre-trained COCO weights python3 gns.py train — dataset=/path/to/dataset — weights=coco# Resume training a model that you had trained earlier python3 gns.py train — dataset=/path/to/dataset — weights=last# Train a new model starting from ImageNet weights python3 gns.py train — dataset=/path/to/dataset — weights=imagenet"
},
{
"code": null,
"e": 5255,
"s": 5102,
"text": "The command with weights=last will resume training from the last epoch. The weights are going to be saved in the logs directory in the Mask_RCNN folder."
},
{
"code": null,
"e": 5305,
"s": 5255,
"text": "This is how the loss looks after our final epoch."
},
{
"code": null,
"e": 5398,
"s": 5305,
"text": "You can take advantage of tensorboard to visualise how your network is performing. Just run:"
},
{
"code": null,
"e": 5469,
"s": 5398,
"text": "tensorboard --logdir ~/objectDetection/Mask_RCNN/logs/gns20191010T1234"
},
{
"code": null,
"e": 5500,
"s": 5469,
"text": "You can get the tensorboard at"
},
{
"code": null,
"e": 5523,
"s": 5500,
"text": "https://localhost:6006"
},
{
"code": null,
"e": 5561,
"s": 5523,
"text": "Here is how our mask loss looks like:"
},
{
"code": null,
"e": 5699,
"s": 5561,
"text": "We can see that the validation loss is performing pretty abruptly. This is expected as we only have kept 20 images in the validation set."
},
{
"code": null,
"e": 5868,
"s": 5699,
"text": "Predicting a new image is also pretty easy. Just follow the prediction.ipynb notebook for a minimal example using our trained model. Below is the main part of the code."
},
{
"code": null,
"e": 5936,
"s": 5868,
"text": "This is how the result looks for some images in the validation set:"
},
{
"code": null,
"e": 6173,
"s": 5936,
"text": "The results don’t look very promising and leave a lot to be desired, but that is to be expected because of very less training data(60 images). One can try to do the below things to improve the model performance for this weapon detector."
},
{
"code": null,
"e": 6591,
"s": 6173,
"text": "We just trained on 60 images due to time constraints. While we used transfer learning the data is still too less — Annotate more data.Train for more epochs and longer time. See how validation loss and training loss looks like.Change hyperparameters in the mrcnn/config file in the Mask_RCNN directory. For information on what these hyperparameters mean, take a look at my previous post. The main ones you can look at:"
},
{
"code": null,
"e": 6726,
"s": 6591,
"text": "We just trained on 60 images due to time constraints. While we used transfer learning the data is still too less — Annotate more data."
},
{
"code": null,
"e": 6819,
"s": 6726,
"text": "Train for more epochs and longer time. See how validation loss and training loss looks like."
},
{
"code": null,
"e": 7011,
"s": 6819,
"text": "Change hyperparameters in the mrcnn/config file in the Mask_RCNN directory. For information on what these hyperparameters mean, take a look at my previous post. The main ones you can look at:"
},
{
"code": null,
"e": 7434,
"s": 7011,
"text": "# if you want to provide different weights to different lossesLOSS_WEIGHTS ={'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}# Length of square anchor side in pixelsRPN_ANCHOR_SCALES = (32, 64, 128, 256, 512)# Ratios of anchors at each cell (width/height)# A value of 1 represents a square anchor, and 0.5 is a wide anchorRPN_ANCHOR_RATIOS = [0.5, 1, 2]"
},
{
"code": null,
"e": 7540,
"s": 7434,
"text": "In this post, I talked about how to implement Instance segmentation using Mask-RCNN for a custom dataset."
},
{
"code": null,
"e": 7717,
"s": 7540,
"text": "I tried to make the coding part as simple as possible and hope you find the code useful. In the next part of this post, I will deploy this model using a web app. So stay tuned."
},
{
"code": null,
"e": 7792,
"s": 7717,
"text": "You can download the annotated weapons data as well as the code at Github."
},
{
"code": null,
"e": 7992,
"s": 7792,
"text": "If you want to know more about various Object Detection techniques, motion estimation, object tracking in video etc., I would like to recommend this awesome course on Deep Learning in Computer Vision"
},
{
"code": null,
"e": 8256,
"s": 7992,
"text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz."
}
] |
CSS | border-collapse Property - GeeksforGeeks
|
03 Nov, 2021
The border-collapse property in CSS is used to set the borders of the cell present inside the table and tells whether these cells will share a common border or not.Syntax:
border-collapse: separate|collapse|initial|inherit;
Default Value : Its default value is separate.
Property Values:
separate: This property is used to set separate border of a cell.
collapse: It is used to collapse adjacent cells and make common border.
initial: It is used to set border-collapse property to its default value.
inherit: It is used when border-collapse property inherit from its parent elements.
Example 1:
html
<!DOCTYPE html><html> <head> <title> CSS border-collapse Property </title> <!-- border-collapse CSS property --> <style> table, td, th { border: 1px solid black; } #separateTable { border-collapse: separate; } #collapseTable { border-collapse: collapse; } </style> </head> <body> <h2> border-collapse: separate </h2> <table id = "separateTable"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: collapse </h2> <table id = "collapseTable"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> </body></html>
Output:
Example 2:
html
<!DOCTYPE html><html> <head> <title> CSS border-collapse Property </title> <style> table, td, th { border: 1px solid black; } /* border spacing is used to specify the width between border and adjacent cells */ #separateTable { border-collapse: separate; border-spacing: 10px; } #collapseTable { border-collapse: collapse; border-spacing: 10px; } #initialTable { border-collapse: initial; } </style> </head> <body> <h2> border-collapse: separate </h2> <table id = "separateTable"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: collapse </h2> <!-- border spacing property has no effect on border-collapse property--> <table id="collapseTable"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: initial </h2> <table id="initialTable"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> </body></html>
Output:
Supported Browsers: The browser supported by border-collapse property are listed below:
Google Chrome 1.0
Internet Explore/Edge 5.0
Firefox 1.0
Opera 4.0
Apple Safari 1.2
ManasChhabra2
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 23596,
"s": 23568,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 23770,
"s": 23596,
"text": "The border-collapse property in CSS is used to set the borders of the cell present inside the table and tells whether these cells will share a common border or not.Syntax: "
},
{
"code": null,
"e": 23822,
"s": 23770,
"text": "border-collapse: separate|collapse|initial|inherit;"
},
{
"code": null,
"e": 23870,
"s": 23822,
"text": "Default Value : Its default value is separate. "
},
{
"code": null,
"e": 23889,
"s": 23870,
"text": "Property Values: "
},
{
"code": null,
"e": 23955,
"s": 23889,
"text": "separate: This property is used to set separate border of a cell."
},
{
"code": null,
"e": 24027,
"s": 23955,
"text": "collapse: It is used to collapse adjacent cells and make common border."
},
{
"code": null,
"e": 24101,
"s": 24027,
"text": "initial: It is used to set border-collapse property to its default value."
},
{
"code": null,
"e": 24185,
"s": 24101,
"text": "inherit: It is used when border-collapse property inherit from its parent elements."
},
{
"code": null,
"e": 24198,
"s": 24185,
"text": "Example 1: "
},
{
"code": null,
"e": 24203,
"s": 24198,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS border-collapse Property </title> <!-- border-collapse CSS property --> <style> table, td, th { border: 1px solid black; } #separateTable { border-collapse: separate; } #collapseTable { border-collapse: collapse; } </style> </head> <body> <h2> border-collapse: separate </h2> <table id = \"separateTable\"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: collapse </h2> <table id = \"collapseTable\"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> </body></html> ",
"e": 25541,
"s": 24203,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25541,
"text": "Output: "
},
{
"code": null,
"e": 25564,
"s": 25551,
"text": "Example 2: "
},
{
"code": null,
"e": 25569,
"s": 25564,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS border-collapse Property </title> <style> table, td, th { border: 1px solid black; } /* border spacing is used to specify the width between border and adjacent cells */ #separateTable { border-collapse: separate; border-spacing: 10px; } #collapseTable { border-collapse: collapse; border-spacing: 10px; } #initialTable { border-collapse: initial; } </style> </head> <body> <h2> border-collapse: separate </h2> <table id = \"separateTable\"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: collapse </h2> <!-- border spacing property has no effect on border-collapse property--> <table id=\"collapseTable\"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> <h2> border-collapse: initial </h2> <table id=\"initialTable\"> <tr> <th>Author Name</th> <th>Contact No</th> </tr> <tr> <td>Geek</td> <td>XXXXXXXXXX</td> </tr> <tr> <td>GFG</td> <td>XXXXXXXXXX</td> </tr> </table> </body></html> ",
"e": 27667,
"s": 25569,
"text": null
},
{
"code": null,
"e": 27677,
"s": 27667,
"text": "Output: "
},
{
"code": null,
"e": 27767,
"s": 27677,
"text": "Supported Browsers: The browser supported by border-collapse property are listed below: "
},
{
"code": null,
"e": 27785,
"s": 27767,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 27811,
"s": 27785,
"text": "Internet Explore/Edge 5.0"
},
{
"code": null,
"e": 27823,
"s": 27811,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 27833,
"s": 27823,
"text": "Opera 4.0"
},
{
"code": null,
"e": 27850,
"s": 27833,
"text": "Apple Safari 1.2"
},
{
"code": null,
"e": 27866,
"s": 27852,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 27881,
"s": 27866,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27888,
"s": 27881,
"text": "Picked"
},
{
"code": null,
"e": 27892,
"s": 27888,
"text": "CSS"
},
{
"code": null,
"e": 27909,
"s": 27892,
"text": "Web Technologies"
},
{
"code": null,
"e": 28007,
"s": 27909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28057,
"s": 28007,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28119,
"s": 28057,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28177,
"s": 28119,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28225,
"s": 28177,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28275,
"s": 28225,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 28317,
"s": 28275,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28350,
"s": 28317,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28393,
"s": 28350,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28443,
"s": 28393,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to use the sleep method in C#?
|
The sleep method of the thread is used to pause the thread for a specific period.
If you want to set sleep for some seconds, then use it like the following code snippet −
int sleepfor = 2000;
Thread.Sleep(sleepfor);
You can try to run the following code to implement the sleep method of the thread −
Live Demo
using System;
using System.Threading;
namespace MyApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
int sleepfor = 2000;
Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 2 seconds
Child thread resumes
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "The sleep method of the thread is used to pause the thread for a specific period."
},
{
"code": null,
"e": 1233,
"s": 1144,
"text": "If you want to set sleep for some seconds, then use it like the following code snippet −"
},
{
"code": null,
"e": 1278,
"s": 1233,
"text": "int sleepfor = 2000;\nThread.Sleep(sleepfor);"
},
{
"code": null,
"e": 1362,
"s": 1278,
"text": "You can try to run the following code to implement the sleep method of the thread −"
},
{
"code": null,
"e": 1373,
"s": 1362,
"text": " Live Demo"
},
{
"code": null,
"e": 2079,
"s": 1373,
"text": "using System;\nusing System.Threading;\n\nnamespace MyApplication {\n class ThreadCreationProgram {\n public static void CallToChildThread() {\n Console.WriteLine(\"Child thread starts\");\n\n int sleepfor = 2000;\n\n Console.WriteLine(\"Child Thread Paused for {0} seconds\", sleepfor / 1000);\n Thread.Sleep(sleepfor);\n Console.WriteLine(\"Child thread resumes\");\n }\n\n static void Main(string[] args) {\n ThreadStart childref = new ThreadStart(CallToChildThread);\n Console.WriteLine(\"In Main: Creating the Child thread\");\n\n Thread childThread = new Thread(childref);\n childThread.Start();\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2189,
"s": 2079,
"text": "In Main: Creating the Child thread\nChild thread starts\nChild Thread Paused for 2 seconds\nChild thread resumes"
}
] |
HTML | <button> type Attribute - GeeksforGeeks
|
18 May, 2019
The <button> type attribute is used to specify the type of button. It specifies the type attribute of <button> element. The default types of <button> element can vary from browser to browser.
Syntax:
<button type="button|submit|reset">
Attribute Values:
submit: It defines a submit button. It has a default value for all browser except Internet Explorer.
button: It defines a clickable button. It has a default value for Internet Explorer.
reset: It defines a reset button which is used to change the previous data from the form.
Example:
<!DOCTYPE html> <html> <head> <title> HTML button type Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML button type Attribute</h3> <form action="#" method="get"> Username: <input type="text" name="uname"> <br><br> Password: <input type="password" name="pwd"> <br><br> <button type="submit" value="submit"> Submit </button> <button type="reset" value="reset"> Reset </button> </form> </body> </html>
Output:
Supported Browsers: The browser supported by HTML <button> type attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24565,
"s": 24537,
"text": "\n18 May, 2019"
},
{
"code": null,
"e": 24757,
"s": 24565,
"text": "The <button> type attribute is used to specify the type of button. It specifies the type attribute of <button> element. The default types of <button> element can vary from browser to browser."
},
{
"code": null,
"e": 24765,
"s": 24757,
"text": "Syntax:"
},
{
"code": null,
"e": 24801,
"s": 24765,
"text": "<button type=\"button|submit|reset\">"
},
{
"code": null,
"e": 24819,
"s": 24801,
"text": "Attribute Values:"
},
{
"code": null,
"e": 24920,
"s": 24819,
"text": "submit: It defines a submit button. It has a default value for all browser except Internet Explorer."
},
{
"code": null,
"e": 25005,
"s": 24920,
"text": "button: It defines a clickable button. It has a default value for Internet Explorer."
},
{
"code": null,
"e": 25095,
"s": 25005,
"text": "reset: It defines a reset button which is used to change the previous data from the form."
},
{
"code": null,
"e": 25104,
"s": 25095,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML button type Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML button type Attribute</h3> <form action=\"#\" method=\"get\"> Username: <input type=\"text\" name=\"uname\"> <br><br> Password: <input type=\"password\" name=\"pwd\"> <br><br> <button type=\"submit\" value=\"submit\"> Submit </button> <button type=\"reset\" value=\"reset\"> Reset </button> </form> </body> </html> ",
"e": 25850,
"s": 25104,
"text": null
},
{
"code": null,
"e": 25858,
"s": 25850,
"text": "Output:"
},
{
"code": null,
"e": 25950,
"s": 25858,
"text": "Supported Browsers: The browser supported by HTML <button> type attribute are listed below:"
},
{
"code": null,
"e": 25964,
"s": 25950,
"text": "Google Chrome"
},
{
"code": null,
"e": 25982,
"s": 25964,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25990,
"s": 25982,
"text": "Firefox"
},
{
"code": null,
"e": 25997,
"s": 25990,
"text": "Safari"
},
{
"code": null,
"e": 26003,
"s": 25997,
"text": "Opera"
},
{
"code": null,
"e": 26140,
"s": 26003,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26156,
"s": 26140,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26161,
"s": 26156,
"text": "HTML"
},
{
"code": null,
"e": 26178,
"s": 26161,
"text": "Web Technologies"
},
{
"code": null,
"e": 26183,
"s": 26178,
"text": "HTML"
},
{
"code": null,
"e": 26281,
"s": 26183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26290,
"s": 26281,
"text": "Comments"
},
{
"code": null,
"e": 26303,
"s": 26290,
"text": "Old Comments"
},
{
"code": null,
"e": 26351,
"s": 26303,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26388,
"s": 26351,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26438,
"s": 26388,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26488,
"s": 26438,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26512,
"s": 26488,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26568,
"s": 26512,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26601,
"s": 26568,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26644,
"s": 26601,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26705,
"s": 26644,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Making elements distinct in a sorted array by minimum increments
|
03 May, 2021
Given a sorted integer array. We need to make array elements distinct by increasing values and keeping array sum minimum possible. We need to print the minimum possible sum as output.
Examples:
Input : arr[] = { 2, 2, 3, 5, 6 } ;
Output : 20
Explanation : We make the array as {2,
3, 4, 5, 6}. Sum becomes 2 + 3 + 4 +
5 + 6 = 20
Input : arr[] = { 20, 20 } ;
Output : 41
Explanation : We make {20, 21}
Input : arr[] = { 3, 4, 6, 8 };
Output : 21
Explanation : All elements are unique
so result is sum of each elements.
Method 1: 1. Traverse each element of array . 2. if arr[i] == arr[i-1] then update each element of array by adding 1 from i-th(current) position to where element is either equal to its previous element or has become less than previous (because previous was increased). 3. After traversing of each element return sum .
C++
Java
Python3
C#
PHP
Javascript
// CPP program to make sorted array elements// distinct by incrementing elements and keeping// sum to minimum.#include <iostream>using namespace std; // To find minimum sum of unique elements.int minSum(int arr[], int n){ int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum;} // Driver codeint main(){ int arr[] = { 2, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n) << endl; return 0;}
// Java program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum.import java.io.*; class GFG{ // To find minimum sum // of unique elements. static int minSum(int arr[], int n) { int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code public static void main (String[] args) { int arr[] = { 2, 2, 3, 5, 6 }; int n = arr.length; System.out.println(minSum(arr, n)); }} // This code is contributed by Ansu Kumari
# Python3 program to make sorted array elements# distinct by incrementing elements and keeping# sum to minimum. # To find minimum sum of unique elements.def minSum(arr, n): sm = arr[0] for i in range(1, n): if arr[i] == arr[i - 1]: # While current element is same as # previous or has become smaller # than previous. j = i while j < n and arr[j] <= arr[j - 1]: arr[j] = arr[j] + 1 j += 1 sm = sm + arr[i] return sm # Driver codearr = [ 2, 2, 3, 5, 6 ]n = len(arr)print(minSum(arr, n)) # This code is contributed by Ansu Kumari
// C# program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum.using System; class GFG{ // To find minimum sum // of unique elements. static int minSum(int []arr, int n) { int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code public static void Main () { int []arr = { 2, 2, 3, 5, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n)); }} // This code is contributed by vt_m
<?php// PHP program to make sorted array// elements distinct by incrementing// elements and keeping sum to minimum. // To find minimum sum of unique// elements.function minSum($arr, $n){ $sum = $arr[0]; for ($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) { // While current element is // same as previous or has // become smaller than // previous. $j = $i; while ($j < $n && $arr[$j] <= $arr[$j - 1]) { $arr[$j] = $arr[$j] + 1; $j++; } } $sum = $sum + $arr[$i]; } return $sum;} // Driver code $arr = array ( 2, 2, 3, 5, 6 ); $n = sizeof($arr) ; echo minSum($arr, $n),"\n"; // This code is contributed by ajit?>
<script> // JavaScript program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum. // To find minimum sum // of unique elements. function minSum(arr, n) { let sum = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. let j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code let arr = [ 2, 2, 3, 5, 6 ]; let n = arr.length; document.write(minSum(arr, n)); </script>
Output :
20
Time Complexity : O(n^2)
Method 2: 1. Traverse each element of array . 2. If arr[i] <= prev then update prev by adding 1 and update sum by adding prev, else update prev by cur element and update sum by adding cur element(arr[i]). 3. After traversing of each element return sum .
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.#include <iostream>using namespace std; // To find minimum sum of unique elements.int minSum(int arr[], int n){ int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum;} // Drivers codeint main(){ int arr[] = { 2, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n) << endl; return 0;}
// Efficient Java program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.import java.io.*; class GFG { // To find minimum sum of unique elements. static int minSum(int arr[], int n) { int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum; } // Drivers code public static void main (String[] args) { int arr[] = { 2, 2, 3, 5, 6 }; int n = arr.length; System.out.println(minSum(arr, n)); }} // This code is contributed by Ansu Kumari.
# Efficient Python program to make sorted array# elements distinct by incrementing elements# and keeping sum to minimum. # To find minimum sum of unique elementsdef minSum(arr, n): sum = arr[0]; prev = arr[0] for i in range(1, n): # If violation happens, make current # value as 1 plus previous value and # add to sum. if arr[i] <= prev: prev = prev + 1 sum = sum + prev # No violation. else : sum = sum + arr[i] prev = arr[i] return sum # Drivers codearr = [ 2, 2, 3, 5, 6 ]n = len(arr)print(minSum(arr, n)) # This code is contributed by Ansu Kumari
// Efficient C# program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.using System; class GFG { // To find minimum sum of unique elements. static int minSum(int []arr, int n) { int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum; } // Drivers code public static void Main () { int []arr = { 2, 2, 3, 5, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n)); }} // This code is contributed by vt_m .
<?php// Efficient PHP program to// make sorted array elements// distinct by incrementing // elements and keeping sum// to minimum. // To find minimum sum// of unique elements.function minSum($arr, $n){ $sum = $arr[0]; $prev = $arr[0]; for ( $i = 1; $i < $n; $i++) { // If violation happens, // make current value as // 1 plus previous value // and add to sum. if ($arr[$i] <= $prev) { $prev = $prev + 1; $sum = $sum + $prev; } // No violation. else { $sum = $sum + $arr[$i]; $prev = $arr[$i]; } } return $sum;} // Driver code$arr = array(2, 2, 3, 5, 6);$n = count($arr);echo minSum($arr, $n); // This code is contributed by anuj_67.?>
<script> // Efficient Javascript program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum. // To find minimum sum of unique elements.function minSum(arr, n){ let sum = arr[0], prev = arr[0]; for(let i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum;} // Driver codelet arr = [ 2, 2, 3, 5, 6 ];let n = arr.length; document.write(minSum(arr, n)); // This code is contributed by decode2207 </script>
Output:
20
Time Complexity: O(n)
jit_t
vt_m
Prashant Nigam
susmitakundugoaldanga
decode2207
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 238,
"s": 54,
"text": "Given a sorted integer array. We need to make array elements distinct by increasing values and keeping array sum minimum possible. We need to print the minimum possible sum as output."
},
{
"code": null,
"e": 249,
"s": 238,
"text": "Examples: "
},
{
"code": null,
"e": 585,
"s": 249,
"text": "Input : arr[] = { 2, 2, 3, 5, 6 } ; \nOutput : 20\nExplanation : We make the array as {2, \n3, 4, 5, 6}. Sum becomes 2 + 3 + 4 + \n5 + 6 = 20\n\nInput : arr[] = { 20, 20 } ; \nOutput : 41\nExplanation : We make {20, 21}\n\nInput : arr[] = { 3, 4, 6, 8 };\nOutput : 21\nExplanation : All elements are unique \nso result is sum of each elements. \n "
},
{
"code": null,
"e": 904,
"s": 585,
"text": "Method 1: 1. Traverse each element of array . 2. if arr[i] == arr[i-1] then update each element of array by adding 1 from i-th(current) position to where element is either equal to its previous element or has become less than previous (because previous was increased). 3. After traversing of each element return sum . "
},
{
"code": null,
"e": 908,
"s": 904,
"text": "C++"
},
{
"code": null,
"e": 913,
"s": 908,
"text": "Java"
},
{
"code": null,
"e": 921,
"s": 913,
"text": "Python3"
},
{
"code": null,
"e": 924,
"s": 921,
"text": "C#"
},
{
"code": null,
"e": 928,
"s": 924,
"text": "PHP"
},
{
"code": null,
"e": 939,
"s": 928,
"text": "Javascript"
},
{
"code": "// CPP program to make sorted array elements// distinct by incrementing elements and keeping// sum to minimum.#include <iostream>using namespace std; // To find minimum sum of unique elements.int minSum(int arr[], int n){ int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum;} // Driver codeint main(){ int arr[] = { 2, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n) << endl; return 0;}",
"e": 1745,
"s": 939,
"text": null
},
{
"code": "// Java program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum.import java.io.*; class GFG{ // To find minimum sum // of unique elements. static int minSum(int arr[], int n) { int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code public static void main (String[] args) { int arr[] = { 2, 2, 3, 5, 6 }; int n = arr.length; System.out.println(minSum(arr, n)); }} // This code is contributed by Ansu Kumari",
"e": 2737,
"s": 1745,
"text": null
},
{
"code": "# Python3 program to make sorted array elements# distinct by incrementing elements and keeping# sum to minimum. # To find minimum sum of unique elements.def minSum(arr, n): sm = arr[0] for i in range(1, n): if arr[i] == arr[i - 1]: # While current element is same as # previous or has become smaller # than previous. j = i while j < n and arr[j] <= arr[j - 1]: arr[j] = arr[j] + 1 j += 1 sm = sm + arr[i] return sm # Driver codearr = [ 2, 2, 3, 5, 6 ]n = len(arr)print(minSum(arr, n)) # This code is contributed by Ansu Kumari",
"e": 3392,
"s": 2737,
"text": null
},
{
"code": "// C# program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum.using System; class GFG{ // To find minimum sum // of unique elements. static int minSum(int []arr, int n) { int sum = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. int j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code public static void Main () { int []arr = { 2, 2, 3, 5, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n)); }} // This code is contributed by vt_m",
"e": 4349,
"s": 3392,
"text": null
},
{
"code": "<?php// PHP program to make sorted array// elements distinct by incrementing// elements and keeping sum to minimum. // To find minimum sum of unique// elements.function minSum($arr, $n){ $sum = $arr[0]; for ($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) { // While current element is // same as previous or has // become smaller than // previous. $j = $i; while ($j < $n && $arr[$j] <= $arr[$j - 1]) { $arr[$j] = $arr[$j] + 1; $j++; } } $sum = $sum + $arr[$i]; } return $sum;} // Driver code $arr = array ( 2, 2, 3, 5, 6 ); $n = sizeof($arr) ; echo minSum($arr, $n),\"\\n\"; // This code is contributed by ajit?>",
"e": 5169,
"s": 4349,
"text": null
},
{
"code": "<script> // JavaScript program to make sorted// array elements distinct by// incrementing elements and// keeping sum to minimum. // To find minimum sum // of unique elements. function minSum(arr, n) { let sum = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { // While current element is same as // previous or has become smaller // than previous. let j = i; while (j < n && arr[j] <= arr[j - 1]) { arr[j] = arr[j] + 1; j++; } } sum = sum + arr[i]; } return sum; } // Driver code let arr = [ 2, 2, 3, 5, 6 ]; let n = arr.length; document.write(minSum(arr, n)); </script>",
"e": 6054,
"s": 5169,
"text": null
},
{
"code": null,
"e": 6064,
"s": 6054,
"text": "Output : "
},
{
"code": null,
"e": 6067,
"s": 6064,
"text": "20"
},
{
"code": null,
"e": 6093,
"s": 6067,
"text": "Time Complexity : O(n^2) "
},
{
"code": null,
"e": 6347,
"s": 6093,
"text": "Method 2: 1. Traverse each element of array . 2. If arr[i] <= prev then update prev by adding 1 and update sum by adding prev, else update prev by cur element and update sum by adding cur element(arr[i]). 3. After traversing of each element return sum ."
},
{
"code": null,
"e": 6351,
"s": 6347,
"text": "C++"
},
{
"code": null,
"e": 6356,
"s": 6351,
"text": "Java"
},
{
"code": null,
"e": 6364,
"s": 6356,
"text": "Python3"
},
{
"code": null,
"e": 6367,
"s": 6364,
"text": "C#"
},
{
"code": null,
"e": 6371,
"s": 6367,
"text": "PHP"
},
{
"code": null,
"e": 6382,
"s": 6371,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.#include <iostream>using namespace std; // To find minimum sum of unique elements.int minSum(int arr[], int n){ int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum;} // Drivers codeint main(){ int arr[] = { 2, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n) << endl; return 0;}",
"e": 7170,
"s": 6382,
"text": null
},
{
"code": "// Efficient Java program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.import java.io.*; class GFG { // To find minimum sum of unique elements. static int minSum(int arr[], int n) { int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum; } // Drivers code public static void main (String[] args) { int arr[] = { 2, 2, 3, 5, 6 }; int n = arr.length; System.out.println(minSum(arr, n)); }} // This code is contributed by Ansu Kumari.",
"e": 8155,
"s": 7170,
"text": null
},
{
"code": "# Efficient Python program to make sorted array# elements distinct by incrementing elements# and keeping sum to minimum. # To find minimum sum of unique elementsdef minSum(arr, n): sum = arr[0]; prev = arr[0] for i in range(1, n): # If violation happens, make current # value as 1 plus previous value and # add to sum. if arr[i] <= prev: prev = prev + 1 sum = sum + prev # No violation. else : sum = sum + arr[i] prev = arr[i] return sum # Drivers codearr = [ 2, 2, 3, 5, 6 ]n = len(arr)print(minSum(arr, n)) # This code is contributed by Ansu Kumari",
"e": 8810,
"s": 8155,
"text": null
},
{
"code": "// Efficient C# program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum.using System; class GFG { // To find minimum sum of unique elements. static int minSum(int []arr, int n) { int sum = arr[0], prev = arr[0]; for (int i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum; } // Drivers code public static void Main () { int []arr = { 2, 2, 3, 5, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n)); }} // This code is contributed by vt_m .",
"e": 9769,
"s": 8810,
"text": null
},
{
"code": "<?php// Efficient PHP program to// make sorted array elements// distinct by incrementing // elements and keeping sum// to minimum. // To find minimum sum// of unique elements.function minSum($arr, $n){ $sum = $arr[0]; $prev = $arr[0]; for ( $i = 1; $i < $n; $i++) { // If violation happens, // make current value as // 1 plus previous value // and add to sum. if ($arr[$i] <= $prev) { $prev = $prev + 1; $sum = $sum + $prev; } // No violation. else { $sum = $sum + $arr[$i]; $prev = $arr[$i]; } } return $sum;} // Driver code$arr = array(2, 2, 3, 5, 6);$n = count($arr);echo minSum($arr, $n); // This code is contributed by anuj_67.?>",
"e": 10547,
"s": 9769,
"text": null
},
{
"code": "<script> // Efficient Javascript program to make sorted array// elements distinct by incrementing elements// and keeping sum to minimum. // To find minimum sum of unique elements.function minSum(arr, n){ let sum = arr[0], prev = arr[0]; for(let i = 1; i < n; i++) { // If violation happens, make current // value as 1 plus previous value and // add to sum. if (arr[i] <= prev) { prev = prev + 1; sum = sum + prev; } // No violation. else { sum = sum + arr[i]; prev = arr[i]; } } return sum;} // Driver codelet arr = [ 2, 2, 3, 5, 6 ];let n = arr.length; document.write(minSum(arr, n)); // This code is contributed by decode2207 </script>",
"e": 11327,
"s": 10547,
"text": null
},
{
"code": null,
"e": 11337,
"s": 11327,
"text": "Output: "
},
{
"code": null,
"e": 11340,
"s": 11337,
"text": "20"
},
{
"code": null,
"e": 11364,
"s": 11340,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 11370,
"s": 11364,
"text": "jit_t"
},
{
"code": null,
"e": 11375,
"s": 11370,
"text": "vt_m"
},
{
"code": null,
"e": 11390,
"s": 11375,
"text": "Prashant Nigam"
},
{
"code": null,
"e": 11412,
"s": 11390,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 11423,
"s": 11412,
"text": "decode2207"
},
{
"code": null,
"e": 11430,
"s": 11423,
"text": "Arrays"
},
{
"code": null,
"e": 11440,
"s": 11430,
"text": "Searching"
},
{
"code": null,
"e": 11447,
"s": 11440,
"text": "Arrays"
},
{
"code": null,
"e": 11457,
"s": 11447,
"text": "Searching"
},
{
"code": null,
"e": 11555,
"s": 11457,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11623,
"s": 11555,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11667,
"s": 11623,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 11699,
"s": 11667,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11747,
"s": 11699,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 11761,
"s": 11747,
"text": "Linear Search"
},
{
"code": null,
"e": 11775,
"s": 11761,
"text": "Binary Search"
},
{
"code": null,
"e": 11843,
"s": 11775,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11857,
"s": 11843,
"text": "Linear Search"
},
{
"code": null,
"e": 11913,
"s": 11857,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Python – Common list elements and dictionary values
|
17 Jun, 2021
Given list and dictionary, extract common elements of List and Dictionary Values.
Input : test_list = [“Gfg”, “is”, “Best”, “For”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Good”, } Output : [‘Gfg’] Explanation : “Gfg” is common in both list and dictionary value.Input : test_list = [“Gfg”, “is”, “Best”, “For”, “Geeks”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Best”, } Output : [‘Gfg’, “Geeks”, “Best”] Explanation : 3 common values are extracted.
Method #1 : Using list comprehension + values()
The combination of above functionalities provide a way in which this task can be performed in a single line. In this, we extract values of dictionaries using values() and list comprehension is used to perform iteration and intersection checks.
Python3
# Python3 code to demonstrate working of# List elements and dictionary values intersection# Using list comprehension + values() # initializing listtest_list = ["Gfg", "is", "Best", "For", "Geeks"] # printing original listprint("The original list : " + str(test_list)) # initializing subs. Dictionarysubs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", } # Intersection of elements, using "in" for checking presenceres = [ele for ele in test_list if ele in subs_dict.values()] # printing resultprint("Intersection elements : " + str(res))
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
Intersection elements : ['Gfg', 'Geeks']
Method #2 : Using set() + intersection()
In this approach both list and dictionary values are converted to set() and then intersection is performed to get common elements.
Python3
# Python3 code to demonstrate working of# Common list elements and dictionary values# Using set() and intersection() # initializing listtest_list = ["Gfg", "is", "Best", "For", "Geeks"] # printing original listprint("The original list : " + str(test_list)) # initializing subs. Dictionarysubs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", } # Intersection of elements, using set() to convert# intersection() for common elementsres = list(set(test_list).intersection(list(subs_dict.values()))) # printing resultprint("Intersection elements : " + str(res))
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
Intersection elements : ['Geeks', 'Gfg']
rajeev0719singh
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "Given list and dictionary, extract common elements of List and Dictionary Values."
},
{
"code": null,
"e": 485,
"s": 110,
"text": "Input : test_list = [“Gfg”, “is”, “Best”, “For”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Good”, } Output : [‘Gfg’] Explanation : “Gfg” is common in both list and dictionary value.Input : test_list = [“Gfg”, “is”, “Best”, “For”, “Geeks”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Best”, } Output : [‘Gfg’, “Geeks”, “Best”] Explanation : 3 common values are extracted. "
},
{
"code": null,
"e": 533,
"s": 485,
"text": "Method #1 : Using list comprehension + values()"
},
{
"code": null,
"e": 779,
"s": 533,
"text": " The combination of above functionalities provide a way in which this task can be performed in a single line. In this, we extract values of dictionaries using values() and list comprehension is used to perform iteration and intersection checks."
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# List elements and dictionary values intersection# Using list comprehension + values() # initializing listtest_list = [\"Gfg\", \"is\", \"Best\", \"For\", \"Geeks\"] # printing original listprint(\"The original list : \" + str(test_list)) # initializing subs. Dictionarysubs_dict = {4 : \"Gfg\", 8 : \"Geeks\", 9 : \" Good\", } # Intersection of elements, using \"in\" for checking presenceres = [ele for ele in test_list if ele in subs_dict.values()] # printing resultprint(\"Intersection elements : \" + str(res))",
"e": 1330,
"s": 787,
"text": null
},
{
"code": null,
"e": 1429,
"s": 1330,
"text": "The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']\nIntersection elements : ['Gfg', 'Geeks']"
},
{
"code": null,
"e": 1471,
"s": 1429,
"text": "Method #2 : Using set() + intersection()"
},
{
"code": null,
"e": 1602,
"s": 1471,
"text": "In this approach both list and dictionary values are converted to set() and then intersection is performed to get common elements."
},
{
"code": null,
"e": 1610,
"s": 1602,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Common list elements and dictionary values# Using set() and intersection() # initializing listtest_list = [\"Gfg\", \"is\", \"Best\", \"For\", \"Geeks\"] # printing original listprint(\"The original list : \" + str(test_list)) # initializing subs. Dictionarysubs_dict = {4 : \"Gfg\", 8 : \"Geeks\", 9 : \" Good\", } # Intersection of elements, using set() to convert# intersection() for common elementsres = list(set(test_list).intersection(list(subs_dict.values()))) # printing resultprint(\"Intersection elements : \" + str(res))",
"e": 2172,
"s": 1610,
"text": null
},
{
"code": null,
"e": 2271,
"s": 2172,
"text": "The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']\nIntersection elements : ['Geeks', 'Gfg']"
},
{
"code": null,
"e": 2287,
"s": 2271,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2314,
"s": 2287,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2335,
"s": 2314,
"text": "Python list-programs"
},
{
"code": null,
"e": 2342,
"s": 2335,
"text": "Python"
},
{
"code": null,
"e": 2358,
"s": 2342,
"text": "Python Programs"
}
] |
Smallest number divisible by first n numbers
|
26 Mar, 2021
Given a number n find the smallest number evenly divisible by each number 1 to n.Examples:
Input : n = 4
Output : 12
Explanation : 12 is the smallest numbers divisible
by all numbers from 1 to 4
Input : n = 10
Output : 2520
Input : n = 20
Output : 232792560
If you observe carefully the ans must be the LCM of the numbers 1 to n. To find LCM of numbers from 1 to n –
Initialize ans = 1. Iterate over all the numbers from i = 1 to i = n. At the i’th iteration ans = LCM(1, 2, ........, i). This can be done easily as LCM(1, 2, ...., i) = LCM(ans, i). Thus at i’th iteration we just have to do –
Initialize ans = 1.
Iterate over all the numbers from i = 1 to i = n. At the i’th iteration ans = LCM(1, 2, ........, i). This can be done easily as LCM(1, 2, ...., i) = LCM(ans, i). Thus at i’th iteration we just have to do –
ans = LCM(ans, i)
= ans * i / gcd(ans, i) [Using the below property,
a*b = gcd(a,b) * lcm(a,b)]
Note : In C++ code, the answer quickly exceeds the integer limit, even the long long limit.Below is the implementation of the logic.
C++
Java
C#
Python3
PHP
Javascript
// C++ program to find smallest number evenly divisible by// all numbers 1 to n#include<bits/stdc++.h>using namespace std; // Function returns the lcm of first n numberslong long lcm(long long n){ long long ans = 1; for (long long i = 1; i <= n; i++) ans = (ans * i)/(__gcd(ans, i)); return ans;} // Driver program to test the above functionint main(){ long long n = 20; cout << lcm(n); return 0;}
// Java program to find the smallest number evenly divisible by// all numbers 1 to n class GFG{ static long gcd(long a, long b){ if(a%b != 0) return gcd(b,a%b); else return b;} // Function returns the lcm of first n numbersstatic long lcm(long n){ long ans = 1; for (long i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // Driver program to test the above functionpublic static void main(String []args){ long n = 20; System.out.println(lcm(n)); }}
// C# program to find smallest number// evenly divisible by// all numbers 1 to nusing System; public class GFG{ static long gcd(long a, long b){if(a%b != 0) return gcd(b,a%b);else return b;} // Function returns the lcm of first n numbersstatic long lcm(long n){ long ans = 1; for (long i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // Driver program to test the above function static public void Main (){ long n = 20; Console.WriteLine(lcm(n)); }//This code is contributed by akt_mit }
# Python program to find the smallest number evenly # divisible by all number 1 to nimport math # Returns the lcm of first n numbersdef lcm(n): ans = 1 for i in range(1, n + 1): ans = int((ans * i)/math.gcd(ans, i)) return ans # mainn = 20print (lcm(n))
<?php// Note: This code is not working on GFG-IDE// because gmp libraries are not supported // PHP program to find smallest number// evenly divisible by all numbers 1 to n // Function returns the lcm// of first n numbersfunction lcm($n){ $ans = 1; for ($i = 1; $i <= $n; $i++) $ans = ($ans * $i) / (gmp_gcd(strval(ans), strval(i))); return $ans;} // Driver Code$n = 20;echo lcm($n); // This code is contributed by mits?>
<script> // Javascript program to find the smallest number evenly divisible by// all numbers 1 to n function gcd(a, b){ if(a%b != 0) return gcd(b,a%b); else return b;} // Function returns the lcm of first n numbersfunction lcm(n){ let ans = 1; for (let i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // function call let n = 20; document.write(lcm(n)); </script>
Output :
232792560
The above solution works fine for a single input. But if we have multiple inputs, it is a good idea to use Sieve of Eratosthenes to store all prime factors. Please refer below article for Sieve based approach. LCM of First n Natural NumbersThis article is contributed by Ayush Khanduri. 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.
Mithun Kumar
ukasp
jit_t
plusplusc
susmitakundugoaldanga
divisibility
GCD-LCM
sieve
Mathematical
Mathematical
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
Modulo Operator (%) in C/C++ with Examples
Modulo 10^9+7 (1000000007)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 147,
"s": 54,
"text": "Given a number n find the smallest number evenly divisible by each number 1 to n.Examples: "
},
{
"code": null,
"e": 331,
"s": 147,
"text": "Input : n = 4\nOutput : 12\nExplanation : 12 is the smallest numbers divisible\n by all numbers from 1 to 4\n\nInput : n = 10\nOutput : 2520\n\nInput : n = 20\nOutput : 232792560"
},
{
"code": null,
"e": 444,
"s": 333,
"text": "If you observe carefully the ans must be the LCM of the numbers 1 to n. To find LCM of numbers from 1 to n – "
},
{
"code": null,
"e": 674,
"s": 444,
"text": "Initialize ans = 1. Iterate over all the numbers from i = 1 to i = n. At the i’th iteration ans = LCM(1, 2, ........, i). This can be done easily as LCM(1, 2, ...., i) = LCM(ans, i). Thus at i’th iteration we just have to do – "
},
{
"code": null,
"e": 696,
"s": 674,
"text": "Initialize ans = 1. "
},
{
"code": null,
"e": 905,
"s": 696,
"text": "Iterate over all the numbers from i = 1 to i = n. At the i’th iteration ans = LCM(1, 2, ........, i). This can be done easily as LCM(1, 2, ...., i) = LCM(ans, i). Thus at i’th iteration we just have to do – "
},
{
"code": null,
"e": 1044,
"s": 905,
"text": "ans = LCM(ans, i) \n = ans * i / gcd(ans, i) [Using the below property,\n a*b = gcd(a,b) * lcm(a,b)]"
},
{
"code": null,
"e": 1183,
"s": 1048,
"text": "Note : In C++ code, the answer quickly exceeds the integer limit, even the long long limit.Below is the implementation of the logic. "
},
{
"code": null,
"e": 1187,
"s": 1183,
"text": "C++"
},
{
"code": null,
"e": 1192,
"s": 1187,
"text": "Java"
},
{
"code": null,
"e": 1195,
"s": 1192,
"text": "C#"
},
{
"code": null,
"e": 1203,
"s": 1195,
"text": "Python3"
},
{
"code": null,
"e": 1207,
"s": 1203,
"text": "PHP"
},
{
"code": null,
"e": 1218,
"s": 1207,
"text": "Javascript"
},
{
"code": "// C++ program to find smallest number evenly divisible by// all numbers 1 to n#include<bits/stdc++.h>using namespace std; // Function returns the lcm of first n numberslong long lcm(long long n){ long long ans = 1; for (long long i = 1; i <= n; i++) ans = (ans * i)/(__gcd(ans, i)); return ans;} // Driver program to test the above functionint main(){ long long n = 20; cout << lcm(n); return 0;}",
"e": 1644,
"s": 1218,
"text": null
},
{
"code": "// Java program to find the smallest number evenly divisible by// all numbers 1 to n class GFG{ static long gcd(long a, long b){ if(a%b != 0) return gcd(b,a%b); else return b;} // Function returns the lcm of first n numbersstatic long lcm(long n){ long ans = 1; for (long i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // Driver program to test the above functionpublic static void main(String []args){ long n = 20; System.out.println(lcm(n)); }}",
"e": 2149,
"s": 1644,
"text": null
},
{
"code": "// C# program to find smallest number// evenly divisible by// all numbers 1 to nusing System; public class GFG{ static long gcd(long a, long b){if(a%b != 0) return gcd(b,a%b);else return b;} // Function returns the lcm of first n numbersstatic long lcm(long n){ long ans = 1; for (long i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // Driver program to test the above function static public void Main (){ long n = 20; Console.WriteLine(lcm(n)); }//This code is contributed by akt_mit }",
"e": 2705,
"s": 2149,
"text": null
},
{
"code": "# Python program to find the smallest number evenly # divisible by all number 1 to nimport math # Returns the lcm of first n numbersdef lcm(n): ans = 1 for i in range(1, n + 1): ans = int((ans * i)/math.gcd(ans, i)) return ans # mainn = 20print (lcm(n))",
"e": 2987,
"s": 2705,
"text": null
},
{
"code": "<?php// Note: This code is not working on GFG-IDE// because gmp libraries are not supported // PHP program to find smallest number// evenly divisible by all numbers 1 to n // Function returns the lcm// of first n numbersfunction lcm($n){ $ans = 1; for ($i = 1; $i <= $n; $i++) $ans = ($ans * $i) / (gmp_gcd(strval(ans), strval(i))); return $ans;} // Driver Code$n = 20;echo lcm($n); // This code is contributed by mits?>",
"e": 3461,
"s": 2987,
"text": null
},
{
"code": "<script> // Javascript program to find the smallest number evenly divisible by// all numbers 1 to n function gcd(a, b){ if(a%b != 0) return gcd(b,a%b); else return b;} // Function returns the lcm of first n numbersfunction lcm(n){ let ans = 1; for (let i = 1; i <= n; i++) ans = (ans * i)/(gcd(ans, i)); return ans;} // function call let n = 20; document.write(lcm(n)); </script>",
"e": 3897,
"s": 3461,
"text": null
},
{
"code": null,
"e": 3907,
"s": 3897,
"text": "Output : "
},
{
"code": null,
"e": 3917,
"s": 3907,
"text": "232792560"
},
{
"code": null,
"e": 4456,
"s": 3917,
"text": "The above solution works fine for a single input. But if we have multiple inputs, it is a good idea to use Sieve of Eratosthenes to store all prime factors. Please refer below article for Sieve based approach. LCM of First n Natural NumbersThis article is contributed by Ayush Khanduri. 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. "
},
{
"code": null,
"e": 4469,
"s": 4456,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 4475,
"s": 4469,
"text": "ukasp"
},
{
"code": null,
"e": 4481,
"s": 4475,
"text": "jit_t"
},
{
"code": null,
"e": 4491,
"s": 4481,
"text": "plusplusc"
},
{
"code": null,
"e": 4513,
"s": 4491,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 4526,
"s": 4513,
"text": "divisibility"
},
{
"code": null,
"e": 4534,
"s": 4526,
"text": "GCD-LCM"
},
{
"code": null,
"e": 4540,
"s": 4534,
"text": "sieve"
},
{
"code": null,
"e": 4553,
"s": 4540,
"text": "Mathematical"
},
{
"code": null,
"e": 4566,
"s": 4553,
"text": "Mathematical"
},
{
"code": null,
"e": 4572,
"s": 4566,
"text": "sieve"
},
{
"code": null,
"e": 4670,
"s": 4572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4694,
"s": 4670,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4715,
"s": 4694,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4729,
"s": 4715,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4782,
"s": 4729,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4814,
"s": 4782,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4851,
"s": 4814,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 4894,
"s": 4851,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 4935,
"s": 4894,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 4978,
"s": 4935,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
How to use Kali Linux in Windows with WSL 2?
|
18 Sep, 2020
The Windows Subsystem for Linux lets developers run a GNU/Linux environment including most command-line tools, etc. direct on Windows, unmodified, without the overhead of an ordinary virtual machine or dual-boot system.
Uses of WSL:
Pick your preferred GNU/Linux distributions from the Microsoft Store.
Run basic command-line tools, for example, grep, sed, awk, or other ELF-64 doubles.
Run Bash shell and GNU/Linux command-line applications like tmux, emacs, SSHD, MySQL, and also could use the language compilers.
Summon Windows applications utilizing a Unix-like command-line shell.
Summon GNU/Linux applications on Windows.
WSL 2
WSL 2 is another form of the Windows Subsystem for Linux engineering that controls the Windows Subsystem for Linux to run ELF64 Linux binaries on Windows. Its essential objectives are to build file system execution, just as including full framework call compatibility. This new design changes how these Linux binaries associate with Windows and your PC’s equipment, yet at the same time gives a similar client experience as in WSL 1 (the current broadly accessible version).
Requirements For WSL 2:
WSL 2 is only accessible in Windows 10, Version 1903, Build 18362, or higher.
On the off chance that you are on Windows 10 form 1903 or 1909 ensure your minor build number is 1049 or higher.
Running Windows 10, refreshed to version 2004 or higher, version 19041, for ARM64 systems.
WSL 2 will work with VMWare 15.5.5+ and VirtualBox 6+.
Step 1: Hold on the Windows logo key (on the keyboard) + R to open the run dialogue, and then type in the following command and select OK.
winver
Step 2: If your OS builds version is not compatible, then we have to update the Windows.
Step 3: For updating, Click on the Windows logo in the bottom left corner of your screen and then type in the following command and press enter:
check for updates
Step 4: Now, select the “Check for updates” option from the menu listed, and then a dialog box will appear.
Step 5: Click on the “Check for Updates” button on the screen, and after successful completion of the update, “restart” your machine. But, if you don’t get any information regarding the update then, after doing a restart/s you will be prompted an update.
Step 1: Click on the Windows logo in the bottom left corner of your screen and then type in the following command:
powershell
Now, when the list appears in the menu, Right-Click on the “Windows Power Shell” option and chooses “Run as administrator”.
Step 2: Now, once the Power Shell is opened and ready to use, type the following command and hit enter:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Step 3: Restart your machine.
Step 4: After the restart, again run the “Windows PowerShell” in the administrator mode, and then type in the following command:
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
Step 5: Now, type in the next command:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
Step 6: Now, again restart your machine.
Step 7: In order to update the kernel packages visit https://aka.ms/wsl2kernel, download the kernel package and install the same.
Step 8: In order to activate WSL 2 execute the following command in Windows Powershell running the same in administrator mode.
wsl --set-default-version 2
Step 1: Hit the Windows logo button on your keyboard, and then type in the following command and then, choose the “Microsoft Store” option from the menu.
microsoft store
Step 2: Once the Microsoft store opens, search for “Kali Linux” in the search bar.
Step 3: On the Kali Linux page, click on the “Get” option in order to download the Kali Linux app.
Step 4: Once the Kali Linux app is downloaded, close the Microsoft-Store.
Step 5: Click on the Windows logo in the bottom left corner of your screen and then type in the following command and press enter:
Kali Linux
Step 6: After opening the Kali Linux app, the distribution will be installed in few seconds completely.
Step 7: Then, type in the credentials that you want to set in for the login purpose. Now, you will be able to use the Kali Linux easily in the command-line prompt and also execute the basic commands without an error.
Note: The base image does not contain any tool, or a graphical interface in order to keep the image small, however, it can be downloaded and installed via “apt” commands easily.
Step 1: Open the Kali Linux app and login with your credentials.
Step 2: Type in the following command and hit enter:
sudo apt update && sudo apt upgrade -y
Step 3: After the successful completion of the above command, type the following command and hit Enter:
sudo apt upgrade && sudo apt install kali-win-kex -y
Step 4: Now, once the above command is completed installing, then type in the following:
kex
This will initiate the process to open up the GUI environment of the Kali Linux distribution installed.
Important:
1. Now, whenever we have to close the GUI opened, then we will press the “fn” key with “f8” in order to select the “exit viewer” option.
2. Then, after exiting the viewer type in the following command in order to completely close the running services:
kex stop
3. Thereafter, whenever we want to start the GUI Kali Linux environment then we will firstly open the Kali Linux app, and then type in the following commands by sequence: [or else you will get an error.]
kex stop [In any case you forgot to stop the kex services running before.]
kex
Note: The above GUI setup will work on Kali Linux versions 2020.3 or later.
Linux-Unix
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Operating System - Set 1
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 274,
"s": 54,
"text": "The Windows Subsystem for Linux lets developers run a GNU/Linux environment including most command-line tools, etc. direct on Windows, unmodified, without the overhead of an ordinary virtual machine or dual-boot system."
},
{
"code": null,
"e": 288,
"s": 274,
"text": "Uses of WSL: "
},
{
"code": null,
"e": 358,
"s": 288,
"text": "Pick your preferred GNU/Linux distributions from the Microsoft Store."
},
{
"code": null,
"e": 442,
"s": 358,
"text": "Run basic command-line tools, for example, grep, sed, awk, or other ELF-64 doubles."
},
{
"code": null,
"e": 571,
"s": 442,
"text": "Run Bash shell and GNU/Linux command-line applications like tmux, emacs, SSHD, MySQL, and also could use the language compilers."
},
{
"code": null,
"e": 641,
"s": 571,
"text": "Summon Windows applications utilizing a Unix-like command-line shell."
},
{
"code": null,
"e": 683,
"s": 641,
"text": "Summon GNU/Linux applications on Windows."
},
{
"code": null,
"e": 689,
"s": 683,
"text": "WSL 2"
},
{
"code": null,
"e": 1164,
"s": 689,
"text": "WSL 2 is another form of the Windows Subsystem for Linux engineering that controls the Windows Subsystem for Linux to run ELF64 Linux binaries on Windows. Its essential objectives are to build file system execution, just as including full framework call compatibility. This new design changes how these Linux binaries associate with Windows and your PC’s equipment, yet at the same time gives a similar client experience as in WSL 1 (the current broadly accessible version)."
},
{
"code": null,
"e": 1188,
"s": 1164,
"text": "Requirements For WSL 2:"
},
{
"code": null,
"e": 1266,
"s": 1188,
"text": "WSL 2 is only accessible in Windows 10, Version 1903, Build 18362, or higher."
},
{
"code": null,
"e": 1379,
"s": 1266,
"text": "On the off chance that you are on Windows 10 form 1903 or 1909 ensure your minor build number is 1049 or higher."
},
{
"code": null,
"e": 1470,
"s": 1379,
"text": "Running Windows 10, refreshed to version 2004 or higher, version 19041, for ARM64 systems."
},
{
"code": null,
"e": 1525,
"s": 1470,
"text": "WSL 2 will work with VMWare 15.5.5+ and VirtualBox 6+."
},
{
"code": null,
"e": 1664,
"s": 1525,
"text": "Step 1: Hold on the Windows logo key (on the keyboard) + R to open the run dialogue, and then type in the following command and select OK."
},
{
"code": null,
"e": 1672,
"s": 1664,
"text": "winver\n"
},
{
"code": null,
"e": 1761,
"s": 1672,
"text": "Step 2: If your OS builds version is not compatible, then we have to update the Windows."
},
{
"code": null,
"e": 1906,
"s": 1761,
"text": "Step 3: For updating, Click on the Windows logo in the bottom left corner of your screen and then type in the following command and press enter:"
},
{
"code": null,
"e": 1925,
"s": 1906,
"text": "check for updates\n"
},
{
"code": null,
"e": 2033,
"s": 1925,
"text": "Step 4: Now, select the “Check for updates” option from the menu listed, and then a dialog box will appear."
},
{
"code": null,
"e": 2288,
"s": 2033,
"text": "Step 5: Click on the “Check for Updates” button on the screen, and after successful completion of the update, “restart” your machine. But, if you don’t get any information regarding the update then, after doing a restart/s you will be prompted an update."
},
{
"code": null,
"e": 2403,
"s": 2288,
"text": "Step 1: Click on the Windows logo in the bottom left corner of your screen and then type in the following command:"
},
{
"code": null,
"e": 2415,
"s": 2403,
"text": "powershell\n"
},
{
"code": null,
"e": 2539,
"s": 2415,
"text": "Now, when the list appears in the menu, Right-Click on the “Windows Power Shell” option and chooses “Run as administrator”."
},
{
"code": null,
"e": 2643,
"s": 2539,
"text": "Step 2: Now, once the Power Shell is opened and ready to use, type the following command and hit enter:"
},
{
"code": null,
"e": 2729,
"s": 2643,
"text": "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux\n"
},
{
"code": null,
"e": 2759,
"s": 2729,
"text": "Step 3: Restart your machine."
},
{
"code": null,
"e": 2888,
"s": 2759,
"text": "Step 4: After the restart, again run the “Windows PowerShell” in the administrator mode, and then type in the following command:"
},
{
"code": null,
"e": 2974,
"s": 2888,
"text": "dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart\n"
},
{
"code": null,
"e": 3013,
"s": 2974,
"text": "Step 5: Now, type in the next command:"
},
{
"code": null,
"e": 3110,
"s": 3013,
"text": "dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart\n"
},
{
"code": null,
"e": 3151,
"s": 3110,
"text": "Step 6: Now, again restart your machine."
},
{
"code": null,
"e": 3281,
"s": 3151,
"text": "Step 7: In order to update the kernel packages visit https://aka.ms/wsl2kernel, download the kernel package and install the same."
},
{
"code": null,
"e": 3408,
"s": 3281,
"text": "Step 8: In order to activate WSL 2 execute the following command in Windows Powershell running the same in administrator mode."
},
{
"code": null,
"e": 3437,
"s": 3408,
"text": "wsl --set-default-version 2\n"
},
{
"code": null,
"e": 3591,
"s": 3437,
"text": "Step 1: Hit the Windows logo button on your keyboard, and then type in the following command and then, choose the “Microsoft Store” option from the menu."
},
{
"code": null,
"e": 3608,
"s": 3591,
"text": "microsoft store\n"
},
{
"code": null,
"e": 3691,
"s": 3608,
"text": "Step 2: Once the Microsoft store opens, search for “Kali Linux” in the search bar."
},
{
"code": null,
"e": 3790,
"s": 3691,
"text": "Step 3: On the Kali Linux page, click on the “Get” option in order to download the Kali Linux app."
},
{
"code": null,
"e": 3864,
"s": 3790,
"text": "Step 4: Once the Kali Linux app is downloaded, close the Microsoft-Store."
},
{
"code": null,
"e": 3995,
"s": 3864,
"text": "Step 5: Click on the Windows logo in the bottom left corner of your screen and then type in the following command and press enter:"
},
{
"code": null,
"e": 4007,
"s": 3995,
"text": "Kali Linux\n"
},
{
"code": null,
"e": 4111,
"s": 4007,
"text": "Step 6: After opening the Kali Linux app, the distribution will be installed in few seconds completely."
},
{
"code": null,
"e": 4328,
"s": 4111,
"text": "Step 7: Then, type in the credentials that you want to set in for the login purpose. Now, you will be able to use the Kali Linux easily in the command-line prompt and also execute the basic commands without an error."
},
{
"code": null,
"e": 4506,
"s": 4328,
"text": "Note: The base image does not contain any tool, or a graphical interface in order to keep the image small, however, it can be downloaded and installed via “apt” commands easily."
},
{
"code": null,
"e": 4571,
"s": 4506,
"text": "Step 1: Open the Kali Linux app and login with your credentials."
},
{
"code": null,
"e": 4624,
"s": 4571,
"text": "Step 2: Type in the following command and hit enter:"
},
{
"code": null,
"e": 4664,
"s": 4624,
"text": "sudo apt update && sudo apt upgrade -y\n"
},
{
"code": null,
"e": 4768,
"s": 4664,
"text": "Step 3: After the successful completion of the above command, type the following command and hit Enter:"
},
{
"code": null,
"e": 4822,
"s": 4768,
"text": "sudo apt upgrade && sudo apt install kali-win-kex -y\n"
},
{
"code": null,
"e": 4911,
"s": 4822,
"text": "Step 4: Now, once the above command is completed installing, then type in the following:"
},
{
"code": null,
"e": 4916,
"s": 4911,
"text": "kex\n"
},
{
"code": null,
"e": 5020,
"s": 4916,
"text": "This will initiate the process to open up the GUI environment of the Kali Linux distribution installed."
},
{
"code": null,
"e": 5032,
"s": 5020,
"text": "Important: "
},
{
"code": null,
"e": 5170,
"s": 5032,
"text": "1. Now, whenever we have to close the GUI opened, then we will press the “fn” key with “f8” in order to select the “exit viewer” option. "
},
{
"code": null,
"e": 5286,
"s": 5170,
"text": "2. Then, after exiting the viewer type in the following command in order to completely close the running services: "
},
{
"code": null,
"e": 5296,
"s": 5286,
"text": "kex stop\n"
},
{
"code": null,
"e": 5500,
"s": 5296,
"text": "3. Thereafter, whenever we want to start the GUI Kali Linux environment then we will firstly open the Kali Linux app, and then type in the following commands by sequence: [or else you will get an error.]"
},
{
"code": null,
"e": 5580,
"s": 5500,
"text": "kex stop [In any case you forgot to stop the kex services running before.]\nkex\n"
},
{
"code": null,
"e": 5656,
"s": 5580,
"text": "Note: The above GUI setup will work on Kali Linux versions 2020.3 or later."
},
{
"code": null,
"e": 5667,
"s": 5656,
"text": "Linux-Unix"
},
{
"code": null,
"e": 5685,
"s": 5667,
"text": "Operating Systems"
},
{
"code": null,
"e": 5703,
"s": 5685,
"text": "Operating Systems"
},
{
"code": null,
"e": 5801,
"s": 5703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5827,
"s": 5801,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5862,
"s": 5827,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 5899,
"s": 5862,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 5928,
"s": 5899,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 5962,
"s": 5928,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 5989,
"s": 5962,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 6028,
"s": 5989,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 6077,
"s": 6028,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 6104,
"s": 6077,
"text": "Disk Scheduling Algorithms"
}
] |
Join algorithms in Database
|
24 Dec, 2021
There are two algorithms to compute natural join and conditional join of two relations in database: Nested loop join, and Block nested loop join.
To understand these algorithms we will assume there are two relations, relation R and relation S. Relation R has TR tuples and occupies BR blocks. Relation S has TS tuples and occupies BS blocks. We will also assume relation R is the outer relation and S is the inner relation.
In the nested loop join algorithm, for each tuple in outer relation, we have to compare it with all the tuples in the inner relation then only the next tuple of outer relation is considered. All pairs of tuples which satisfy the condition are added in the result of the join.
for each tuple tR in TR do
for each tuple ts in Ts do
compare (tR, ts) if they satisfies the condition
add them in the result of the join
end
end
This algorithm is called nested join because it consists of nested for loops.
Let’s see some cases to understand the performance of this algorithm,
Case-1: Assume only two blocks of main memory are available to store blocks from R and S relation.
For each tuple in relation to R, we have to transfer all blocks of relation S and each block of relation R should be transferred only once. So, the total block transfers needed = TR * BS + BR
Case-2: Assume one relation fits entirely in the main memory and there is at least space for one extra block.
In this case, the blocks of relation S (that is, the inner relation) are only transferred once and kept in the main memory and the blocks of relation R are transferred sequentially. So, all the blocks of both the relation are transferred only once. So, the total block transfers needed = BR + BS
The relation with a lesser number of blocks should be the outer relation to minimizing the total number of blocks access required in the main memory to complete the join. That is, min(BR, BS)+1 is the minimum number of blocks in the main memory required to join two relations so that no block is transferred more than once.
In nested loop join, more access cost is required to join relations if the main memory space allocated for join is very limited.
In block nested loop join, for a block of outer relation, all the tuples in that block are compared with all the tuples of the inner relation, then only the next block of outer relation is considered. All pairs of tuples which satisfy the condition are added in the result of the join.
for each block bR in BR do
for each block bs in BS do
for each tuple tR in TR do
for each tuple ts in Ts do
compare (tR, ts) if they satisfies the condition
add them in the result of the join
end
end
end
end
Let’s look at some similar cases as nested loop join,
Case-1: Assume only two blocks of main memory are available to store blocks from R and S relation.
For each block of relation R, we have to transfer all blocks of relation S and each block of relation R should be transferred only once. So, the total block transfers needed = BR+ BR * BS
Case-2: Assume one relation fits entirely in the main memory and there is at least space for one extra block.
In this case, total block transfers needed are similar to nested loop join. Block nested loop join algorithm reduces the access cost compared to nested loop join if the main memory space allocated for join is limited.
Related GATE questions:
Gate IT 2005 | Question 84
Gate IT 2005 | Question 85
devanidarshak01
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Introduction of DBMS (Database Management System) | Set 1
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL Trigger | Student Database
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 199,
"s": 52,
"text": "There are two algorithms to compute natural join and conditional join of two relations in database: Nested loop join, and Block nested loop join. "
},
{
"code": null,
"e": 478,
"s": 199,
"text": "To understand these algorithms we will assume there are two relations, relation R and relation S. Relation R has TR tuples and occupies BR blocks. Relation S has TS tuples and occupies BS blocks. We will also assume relation R is the outer relation and S is the inner relation. "
},
{
"code": null,
"e": 755,
"s": 478,
"text": "In the nested loop join algorithm, for each tuple in outer relation, we have to compare it with all the tuples in the inner relation then only the next tuple of outer relation is considered. All pairs of tuples which satisfy the condition are added in the result of the join. "
},
{
"code": null,
"e": 908,
"s": 755,
"text": "for each tuple tR in TR do\n for each tuple ts in Ts do\n compare (tR, ts) if they satisfies the condition\n add them in the result of the join\n end \nend"
},
{
"code": null,
"e": 987,
"s": 908,
"text": "This algorithm is called nested join because it consists of nested for loops. "
},
{
"code": null,
"e": 1058,
"s": 987,
"text": "Let’s see some cases to understand the performance of this algorithm, "
},
{
"code": null,
"e": 1158,
"s": 1058,
"text": "Case-1: Assume only two blocks of main memory are available to store blocks from R and S relation. "
},
{
"code": null,
"e": 1351,
"s": 1158,
"text": "For each tuple in relation to R, we have to transfer all blocks of relation S and each block of relation R should be transferred only once. So, the total block transfers needed = TR * BS + BR "
},
{
"code": null,
"e": 1462,
"s": 1351,
"text": "Case-2: Assume one relation fits entirely in the main memory and there is at least space for one extra block. "
},
{
"code": null,
"e": 1760,
"s": 1464,
"text": "In this case, the blocks of relation S (that is, the inner relation) are only transferred once and kept in the main memory and the blocks of relation R are transferred sequentially. So, all the blocks of both the relation are transferred only once. So, the total block transfers needed = BR + BS"
},
{
"code": null,
"e": 2085,
"s": 1760,
"text": "The relation with a lesser number of blocks should be the outer relation to minimizing the total number of blocks access required in the main memory to complete the join. That is, min(BR, BS)+1 is the minimum number of blocks in the main memory required to join two relations so that no block is transferred more than once. "
},
{
"code": null,
"e": 2214,
"s": 2085,
"text": "In nested loop join, more access cost is required to join relations if the main memory space allocated for join is very limited."
},
{
"code": null,
"e": 2501,
"s": 2214,
"text": "In block nested loop join, for a block of outer relation, all the tuples in that block are compared with all the tuples of the inner relation, then only the next block of outer relation is considered. All pairs of tuples which satisfy the condition are added in the result of the join. "
},
{
"code": null,
"e": 2731,
"s": 2501,
"text": "for each block bR in BR do\n for each block bs in BS do\n for each tuple tR in TR do\n for each tuple ts in Ts do\n compare (tR, ts) if they satisfies the condition\n add them in the result of the join\n end\n end \n end\nend "
},
{
"code": null,
"e": 2786,
"s": 2731,
"text": "Let’s look at some similar cases as nested loop join, "
},
{
"code": null,
"e": 2886,
"s": 2786,
"text": "Case-1: Assume only two blocks of main memory are available to store blocks from R and S relation. "
},
{
"code": null,
"e": 3077,
"s": 2888,
"text": "For each block of relation R, we have to transfer all blocks of relation S and each block of relation R should be transferred only once. So, the total block transfers needed = BR+ BR * BS "
},
{
"code": null,
"e": 3188,
"s": 3077,
"text": "Case-2: Assume one relation fits entirely in the main memory and there is at least space for one extra block. "
},
{
"code": null,
"e": 3409,
"s": 3190,
"text": "In this case, total block transfers needed are similar to nested loop join. Block nested loop join algorithm reduces the access cost compared to nested loop join if the main memory space allocated for join is limited. "
},
{
"code": null,
"e": 3434,
"s": 3409,
"text": "Related GATE questions: "
},
{
"code": null,
"e": 3462,
"s": 3434,
"text": "Gate IT 2005 | Question 84 "
},
{
"code": null,
"e": 3490,
"s": 3462,
"text": "Gate IT 2005 | Question 85 "
},
{
"code": null,
"e": 3506,
"s": 3490,
"text": "devanidarshak01"
},
{
"code": null,
"e": 3511,
"s": 3506,
"text": "DBMS"
},
{
"code": null,
"e": 3519,
"s": 3511,
"text": "GATE CS"
},
{
"code": null,
"e": 3524,
"s": 3519,
"text": "DBMS"
},
{
"code": null,
"e": 3622,
"s": 3524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3633,
"s": 3622,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3691,
"s": 3633,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 3744,
"s": 3691,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 3767,
"s": 3744,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 3798,
"s": 3767,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 3818,
"s": 3798,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 3845,
"s": 3818,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 3858,
"s": 3845,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 3907,
"s": 3858,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Material UI Container
|
19 Feb, 2021
Material-UI is a user interface framework that provides pre-defined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Typography component in the Material-UI library.
Container:
It is the basic Material-UI component that centers the content horizontally. It manages the layout of its children.
There are two types of styling and adjusting properties that can be used with the container.
Fluid: The Fluid container wraps the content in it with maxWidth value which is provided as a prop, and this value will be the default value of the container.
maxWidth value defines the width of the screen that we are targeting.
xl: 1920px(extra large)
lg: 1280px(large)
md: 960px(medium)
sm: 600px(small)
xs: 0px(extra small)
Fixed: If you prefer to design for a fixed set of sizes instead of trying to accommodate a fully fluid viewport, you can set the fixed property. The max-width matches the min-width of the current breakpoint.
Syntax:
<Container maxwidth="lg">
<h1>This is Container</h1>
</Container>
Installing React App:
Step1: Create a React app using the following command.
npx create-react-app container-example
Step 2: Get into the project directory.
cd container-example
Installing Material-UI:
npm install @material-ui/core
// OR
yarn add @material-ui/core
Import Container:
import Container from '@material-ui/core/Container';
Example:
App.js
import Container from '@material-ui/core/Container';import React, { Component } from 'react'; export default function SimpleContainer() { return ( <> <Container maxWidth="lg"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = lg </h1> </Container> <Container maxWidth="md"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = md </h1> </Container> <Container maxWidth="sm"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = sm </h1> </Container> <Container maxWidth="xs"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = xs </h1> </Container> <Container fixed> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container with fixed prop </h1> </Container> </> );}
Output:
Material-UI
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "Material-UI is a user interface framework that provides pre-defined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Typography component in the Material-UI library."
},
{
"code": null,
"e": 337,
"s": 326,
"text": "Container:"
},
{
"code": null,
"e": 453,
"s": 337,
"text": "It is the basic Material-UI component that centers the content horizontally. It manages the layout of its children."
},
{
"code": null,
"e": 546,
"s": 453,
"text": "There are two types of styling and adjusting properties that can be used with the container."
},
{
"code": null,
"e": 705,
"s": 546,
"text": "Fluid: The Fluid container wraps the content in it with maxWidth value which is provided as a prop, and this value will be the default value of the container."
},
{
"code": null,
"e": 775,
"s": 705,
"text": "maxWidth value defines the width of the screen that we are targeting."
},
{
"code": null,
"e": 799,
"s": 775,
"text": "xl: 1920px(extra large)"
},
{
"code": null,
"e": 817,
"s": 799,
"text": "lg: 1280px(large)"
},
{
"code": null,
"e": 835,
"s": 817,
"text": "md: 960px(medium)"
},
{
"code": null,
"e": 852,
"s": 835,
"text": "sm: 600px(small)"
},
{
"code": null,
"e": 873,
"s": 852,
"text": "xs: 0px(extra small)"
},
{
"code": null,
"e": 1081,
"s": 873,
"text": "Fixed: If you prefer to design for a fixed set of sizes instead of trying to accommodate a fully fluid viewport, you can set the fixed property. The max-width matches the min-width of the current breakpoint."
},
{
"code": null,
"e": 1089,
"s": 1081,
"text": "Syntax:"
},
{
"code": null,
"e": 1158,
"s": 1089,
"text": "<Container maxwidth=\"lg\">\n <h1>This is Container</h1>\n</Container>"
},
{
"code": null,
"e": 1180,
"s": 1158,
"text": "Installing React App:"
},
{
"code": null,
"e": 1235,
"s": 1180,
"text": "Step1: Create a React app using the following command."
},
{
"code": null,
"e": 1274,
"s": 1235,
"text": "npx create-react-app container-example"
},
{
"code": null,
"e": 1314,
"s": 1274,
"text": "Step 2: Get into the project directory."
},
{
"code": null,
"e": 1335,
"s": 1314,
"text": "cd container-example"
},
{
"code": null,
"e": 1360,
"s": 1335,
"text": "Installing Material-UI: "
},
{
"code": null,
"e": 1423,
"s": 1360,
"text": "npm install @material-ui/core\n// OR\nyarn add @material-ui/core"
},
{
"code": null,
"e": 1441,
"s": 1423,
"text": "Import Container:"
},
{
"code": null,
"e": 1494,
"s": 1441,
"text": "import Container from '@material-ui/core/Container';"
},
{
"code": null,
"e": 1503,
"s": 1494,
"text": "Example:"
},
{
"code": null,
"e": 1510,
"s": 1503,
"text": "App.js"
},
{
"code": "import Container from '@material-ui/core/Container';import React, { Component } from 'react'; export default function SimpleContainer() { return ( <> <Container maxWidth=\"lg\"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = lg </h1> </Container> <Container maxWidth=\"md\"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = md </h1> </Container> <Container maxWidth=\"sm\"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = sm </h1> </Container> <Container maxWidth=\"xs\"> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container Of maxWidth = xs </h1> </Container> <Container fixed> <h1 style={{ backgroundColor: '#cfe8fc'}}> Container with fixed prop </h1> </Container> </> );}",
"e": 2422,
"s": 1510,
"text": null
},
{
"code": null,
"e": 2430,
"s": 2422,
"text": "Output:"
},
{
"code": null,
"e": 2442,
"s": 2430,
"text": "Material-UI"
},
{
"code": null,
"e": 2449,
"s": 2442,
"text": "Picked"
},
{
"code": null,
"e": 2457,
"s": 2449,
"text": "ReactJS"
},
{
"code": null,
"e": 2474,
"s": 2457,
"text": "Web Technologies"
}
] |
Make middle node head in a linked list
|
22 Jun, 2022
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples:
Input : 1 2 3 4 5
Output : 3 1 2 4 5
Input : 1 2 3 4 5 6
Output : 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
C
Java
Python3
C#
Javascript
// C++ program to make middle node as head of // linked list. #include <bits/stdc++.h>using namespace std; /* Link list node */class Node { public: int data; Node* next; }; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(Node** head) { if (*head == NULL) return; // To traverse list nodes one by one Node* one_node = (*head); // To traverse list nodes by skipping // one. Node* two_node = (*head); // To keep track of previous of middle Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node->next->next; /* move two node each time*/ one_node = one_node->next; } /* set middle node at head */ prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node; } // To insert a node at the beginning of linked // list. void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A function to print a given linked list void printList(Node* ptr) { while (ptr != NULL) { cout << ptr->data << " "; ptr = ptr->next; } cout<<endl; } /* Driver code*/int main() { // Create a list of 5 nodes Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); cout << " list before: "; printList(head); setMiddleHead(&head); cout << " list After: "; printList(head); return 0; } // This is code is contributed by rathbhupendra
// C program to make middle node as head of// linked list.#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(struct Node** head){ if (*head == NULL) return; // To traverse list nodes one by one struct Node* one_node = (*head); // To traverse list nodes by skipping // one. struct Node* two_node = (*head); // To keep track of previous of middle struct Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node->next->next; /* move two node each time*/ one_node = one_node->next; } /* set middle node at head */ prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node;} // To insert a node at the beginning of linked// list.void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // A function to print a given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf("%d ", ptr->data); ptr = ptr->next; } printf("\n");} /* Driver function*/int main(){ // Create a list of 5 nodes struct Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); printf(" list before: "); printList(head); setMiddleHead(&head); printf(" list After: "); printList(head); return 0;}
// Java program to make middle node // as head of Linked listpublic class GFG { /* Link list node */ static class Node { int data; Node next; Node(int data){ this.data = data; next = null; } } static Node head; /* Function to get the middle and set at beginning of the linked list*/ static void setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one Node one_node = head; // To traverse list nodes by // skipping one. Node two_node = head; // To keep track of previous of middle Node prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node.next.next; /* move two node each time*/ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. static void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list static void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data+" "); ptr = ptr.next; } System.out.println(); } /* Driver function*/ public static void main(String args[]) { // Create a list of 5 nodes head = null; int i; for (i = 5; i > 0; i--) push(i); System.out.print(" list before: "); printList(head); setMiddleHead(); System.out.print(" list After: "); printList(head); }}// This code is contributed by Sumit Ghosh
# Python3 program to make middle node# as head of Linked list # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to get the middle node# set it as the beginning of the # linked listdef setMiddleHead(head): if(head == None): return None # to traverse nodes # one by one one_node = head # to traverse nodes by # skipping one two_node = head # to keep track of previous middle prev = None while(two_node != None and two_node.next != None): # for previous node of middle node prev = one_node # move one node each time one_node = one_node.next # move two nodes each time two_node = two_node.next.next # set middle node at head prev.next = prev.next.next one_node.next = head head = one_node # return the modified head return head def push(head, new_data): # allocate new node new_node = Node(new_data) #link the old list to new node new_node.next = head # move the head to point the new node head = new_node # return the modified head return head # A function to print a given linked listdef printList(head): temp = head while (temp!=None): print(str(temp.data), end = " ") temp = temp.next print("") # Create a list of 5 nodeshead = Nonefor i in range(5, 0, -1): head = push(head, i) print(" list before: ", end = "")printList(head) head = setMiddleHead(head) print(" list After: ", end = "")printList(head) # This code is contributed# by Pranav Devarakonda
// C# program to make middle node // as head of Linked listusing System; public class GFG { /* Link list node */ class Node { public int data; public Node next; public Node(int data) { this.data = data; next = null; } } static Node head; /* Function to get the middle and set at beginning of the linked list*/ static void setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one Node one_node = head; // To traverse list nodes by // skipping one. Node two_node = head; // To keep track of previous of middle Node prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node.next.next; /* move two node each time*/ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. static void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list static void printList(Node ptr) { while (ptr != null) { Console.Write(ptr.data + " "); ptr = ptr.next; } Console.WriteLine(); } /* Driver code*/ public static void Main(String []args) { // Create a list of 5 nodes head = null; int i; for (i = 5; i > 0; i--) push(i); Console.Write(" list before: "); printList(head); setMiddleHead(); Console.Write(" list After: "); printList(head); }} // This code is contributed by Rajput-Ji
<script>// javascript program to make middle node // as head of Linked list /* Link list node */class Node { constructor(val) { this.data = val; this.next = null; }} var head; /* * Function to get the middle and set at beginning of the linked list */ function setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one one_node = head; // To traverse list nodes by // skipping one. two_node = head; // To keep track of previous of middle prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time */ two_node = two_node.next.next; /* move two node each time */ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. function push(new_data) { /* allocate node */ new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list function printList( ptr) { while (ptr != null) { document.write(ptr.data + " "); ptr = ptr.next; } document.write("<br/>"); } /* Driver function */ // Create a list of 5 nodes head = null; var i; for (i = 5; i > 0; i--) push(i); document.write(" list before: "); printList(head); setMiddleHead(); document.write(" list After: "); printList(head); // This code is contributed by aashish1995 </script>
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
Time Complexity : O(n) Auxiliary Space : O(1)
This article is contributed by R_Raj. 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.
Rajput-Ji
rathbhupendra
Pranav Devarakonda
aashish1995
Kirti_Mangal
polymatir3j
technophpfij
Tortoise-Hare-Approach
Linked List
Misc
Misc
Linked List
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: "
},
{
"code": null,
"e": 278,
"s": 195,
"text": "Input : 1 2 3 4 5 \nOutput : 3 1 2 4 5\n\nInput : 1 2 3 4 5 6\nOutput : 4 1 2 3 5 6 "
},
{
"code": null,
"e": 605,
"s": 282,
"text": "The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head. "
},
{
"code": null,
"e": 614,
"s": 605,
"text": "Chapters"
},
{
"code": null,
"e": 641,
"s": 614,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 691,
"s": 641,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 714,
"s": 691,
"text": "captions off, selected"
},
{
"code": null,
"e": 722,
"s": 714,
"text": "English"
},
{
"code": null,
"e": 746,
"s": 722,
"text": "This is a modal window."
},
{
"code": null,
"e": 815,
"s": 746,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 837,
"s": 815,
"text": "End of dialog window."
},
{
"code": null,
"e": 841,
"s": 837,
"text": "C++"
},
{
"code": null,
"e": 843,
"s": 841,
"text": "C"
},
{
"code": null,
"e": 848,
"s": 843,
"text": "Java"
},
{
"code": null,
"e": 856,
"s": 848,
"text": "Python3"
},
{
"code": null,
"e": 859,
"s": 856,
"text": "C#"
},
{
"code": null,
"e": 870,
"s": 859,
"text": "Javascript"
},
{
"code": "// C++ program to make middle node as head of // linked list. #include <bits/stdc++.h>using namespace std; /* Link list node */class Node { public: int data; Node* next; }; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(Node** head) { if (*head == NULL) return; // To traverse list nodes one by one Node* one_node = (*head); // To traverse list nodes by skipping // one. Node* two_node = (*head); // To keep track of previous of middle Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node->next->next; /* move two node each time*/ one_node = one_node->next; } /* set middle node at head */ prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node; } // To insert a node at the beginning of linked // list. void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A function to print a given linked list void printList(Node* ptr) { while (ptr != NULL) { cout << ptr->data << \" \"; ptr = ptr->next; } cout<<endl; } /* Driver code*/int main() { // Create a list of 5 nodes Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); cout << \" list before: \"; printList(head); setMiddleHead(&head); cout << \" list After: \"; printList(head); return 0; } // This is code is contributed by rathbhupendra",
"e": 2731,
"s": 870,
"text": null
},
{
"code": "// C program to make middle node as head of// linked list.#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(struct Node** head){ if (*head == NULL) return; // To traverse list nodes one by one struct Node* one_node = (*head); // To traverse list nodes by skipping // one. struct Node* two_node = (*head); // To keep track of previous of middle struct Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node->next->next; /* move two node each time*/ one_node = one_node->next; } /* set middle node at head */ prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node;} // To insert a node at the beginning of linked// list.void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // A function to print a given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf(\"%d \", ptr->data); ptr = ptr->next; } printf(\"\\n\");} /* Driver function*/int main(){ // Create a list of 5 nodes struct Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); printf(\" list before: \"); printList(head); setMiddleHead(&head); printf(\" list After: \"); printList(head); return 0;}",
"e": 4570,
"s": 2731,
"text": null
},
{
"code": "// Java program to make middle node // as head of Linked listpublic class GFG { /* Link list node */ static class Node { int data; Node next; Node(int data){ this.data = data; next = null; } } static Node head; /* Function to get the middle and set at beginning of the linked list*/ static void setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one Node one_node = head; // To traverse list nodes by // skipping one. Node two_node = head; // To keep track of previous of middle Node prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node.next.next; /* move two node each time*/ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. static void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list static void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data+\" \"); ptr = ptr.next; } System.out.println(); } /* Driver function*/ public static void main(String args[]) { // Create a list of 5 nodes head = null; int i; for (i = 5; i > 0; i--) push(i); System.out.print(\" list before: \"); printList(head); setMiddleHead(); System.out.print(\" list After: \"); printList(head); }}// This code is contributed by Sumit Ghosh",
"e": 6783,
"s": 4570,
"text": null
},
{
"code": "# Python3 program to make middle node# as head of Linked list # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to get the middle node# set it as the beginning of the # linked listdef setMiddleHead(head): if(head == None): return None # to traverse nodes # one by one one_node = head # to traverse nodes by # skipping one two_node = head # to keep track of previous middle prev = None while(two_node != None and two_node.next != None): # for previous node of middle node prev = one_node # move one node each time one_node = one_node.next # move two nodes each time two_node = two_node.next.next # set middle node at head prev.next = prev.next.next one_node.next = head head = one_node # return the modified head return head def push(head, new_data): # allocate new node new_node = Node(new_data) #link the old list to new node new_node.next = head # move the head to point the new node head = new_node # return the modified head return head # A function to print a given linked listdef printList(head): temp = head while (temp!=None): print(str(temp.data), end = \" \") temp = temp.next print(\"\") # Create a list of 5 nodeshead = Nonefor i in range(5, 0, -1): head = push(head, i) print(\" list before: \", end = \"\")printList(head) head = setMiddleHead(head) print(\" list After: \", end = \"\")printList(head) # This code is contributed# by Pranav Devarakonda",
"e": 8407,
"s": 6783,
"text": null
},
{
"code": "// C# program to make middle node // as head of Linked listusing System; public class GFG { /* Link list node */ class Node { public int data; public Node next; public Node(int data) { this.data = data; next = null; } } static Node head; /* Function to get the middle and set at beginning of the linked list*/ static void setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one Node one_node = head; // To traverse list nodes by // skipping one. Node two_node = head; // To keep track of previous of middle Node prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time*/ two_node = two_node.next.next; /* move two node each time*/ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. static void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list static void printList(Node ptr) { while (ptr != null) { Console.Write(ptr.data + \" \"); ptr = ptr.next; } Console.WriteLine(); } /* Driver code*/ public static void Main(String []args) { // Create a list of 5 nodes head = null; int i; for (i = 5; i > 0; i--) push(i); Console.Write(\" list before: \"); printList(head); setMiddleHead(); Console.Write(\" list After: \"); printList(head); }} // This code is contributed by Rajput-Ji",
"e": 10630,
"s": 8407,
"text": null
},
{
"code": "<script>// javascript program to make middle node // as head of Linked list /* Link list node */class Node { constructor(val) { this.data = val; this.next = null; }} var head; /* * Function to get the middle and set at beginning of the linked list */ function setMiddleHead() { if (head == null) return; // To traverse list nodes one // by one one_node = head; // To traverse list nodes by // skipping one. two_node = head; // To keep track of previous of middle prev = null; while (two_node != null && two_node.next != null) { /* for previous node of middle node */ prev = one_node; /* move one node each time */ two_node = two_node.next.next; /* move two node each time */ one_node = one_node.next; } /* set middle node at head */ prev.next = prev.next.next; one_node.next = head; head = one_node; } // To insert a node at the beginning of // linked list. function push(new_data) { /* allocate node */ new_node = new Node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // A function to print a given linked list function printList( ptr) { while (ptr != null) { document.write(ptr.data + \" \"); ptr = ptr.next; } document.write(\"<br/>\"); } /* Driver function */ // Create a list of 5 nodes head = null; var i; for (i = 5; i > 0; i--) push(i); document.write(\" list before: \"); printList(head); setMiddleHead(); document.write(\" list After: \"); printList(head); // This code is contributed by aashish1995 </script>",
"e": 12600,
"s": 10630,
"text": null
},
{
"code": null,
"e": 12610,
"s": 12600,
"text": "Output: "
},
{
"code": null,
"e": 12657,
"s": 12610,
"text": "list before: 1 2 3 4 5\nlist After : 3 1 2 4 5 "
},
{
"code": null,
"e": 12704,
"s": 12657,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 13118,
"s": 12704,
"text": "This article is contributed by R_Raj. 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. "
},
{
"code": null,
"e": 13128,
"s": 13118,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13142,
"s": 13128,
"text": "rathbhupendra"
},
{
"code": null,
"e": 13161,
"s": 13142,
"text": "Pranav Devarakonda"
},
{
"code": null,
"e": 13173,
"s": 13161,
"text": "aashish1995"
},
{
"code": null,
"e": 13186,
"s": 13173,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 13198,
"s": 13186,
"text": "polymatir3j"
},
{
"code": null,
"e": 13211,
"s": 13198,
"text": "technophpfij"
},
{
"code": null,
"e": 13234,
"s": 13211,
"text": "Tortoise-Hare-Approach"
},
{
"code": null,
"e": 13246,
"s": 13234,
"text": "Linked List"
},
{
"code": null,
"e": 13251,
"s": 13246,
"text": "Misc"
},
{
"code": null,
"e": 13256,
"s": 13251,
"text": "Misc"
},
{
"code": null,
"e": 13268,
"s": 13256,
"text": "Linked List"
},
{
"code": null,
"e": 13273,
"s": 13268,
"text": "Misc"
}
] |
How set default timezone in Node.js for Windows ?
|
21 Dec, 2021
NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It’s used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind.
In this article we will see how to set default timezone in Node.js for windows. You can learn how to install Nodejs from here.
Installing module: Install the express module using the following command.
npm install express
Project structure: Our project structure will look like this.
There are many methods we can try to set default timezone in Nodejs for Windows.
1. Set in code using process.env.tz sample below –
process.env.TZ = "Asia/Calcutta";
console.log(new Date().toString());
2. Set the variable using newDate.
const nDate = new Date().toLocaleString('en-US', {
timeZone: 'Asia/Calcutta'
});
3. We can config global timezone with the library tzdata in our code:
npm install tzdata -yN
Now in app.js set the value of TZ.
TZ = 'Asia/Calcutta'
console.log(new Date().toString());
Example 1:
app.js
var express = require('express'),app = express(); // Method 1const nDate = new Date().toLocaleString('en-US', { timeZone: 'Asia/Calcutta'}); console.log(nDate); app.listen(3000,function(){ console.log("Express Started on Port 3000");});
Run app.js file using below command:
node app.js
Output:
Example 2:
app.js
var express = require('express'),app = express(); // Method 2process.env.TZ = "Asia/Calcutta";console.log(new Date().toString()); app.listen(3000,function(){ console.log("Express Started on Port 3000");});
Run app.js file using below command:
node app.js
Output:
Example 3:
app.js
var express = require('express'), app = express(); // Method 3TZ = 'Asia/Calcutta'console.log(new Date().toString()); app.listen(3000,function(){ console.log("Express Started on Port 3000");});
Run app.js file using below command:
node app.js
Output:
prachisoda1234
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 280,
"s": 52,
"text": "NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It’s used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind."
},
{
"code": null,
"e": 407,
"s": 280,
"text": "In this article we will see how to set default timezone in Node.js for windows. You can learn how to install Nodejs from here."
},
{
"code": null,
"e": 482,
"s": 407,
"text": "Installing module: Install the express module using the following command."
},
{
"code": null,
"e": 502,
"s": 482,
"text": "npm install express"
},
{
"code": null,
"e": 564,
"s": 502,
"text": "Project structure: Our project structure will look like this."
},
{
"code": null,
"e": 645,
"s": 564,
"text": "There are many methods we can try to set default timezone in Nodejs for Windows."
},
{
"code": null,
"e": 696,
"s": 645,
"text": "1. Set in code using process.env.tz sample below –"
},
{
"code": null,
"e": 766,
"s": 696,
"text": "process.env.TZ = \"Asia/Calcutta\";\nconsole.log(new Date().toString());"
},
{
"code": null,
"e": 801,
"s": 766,
"text": "2. Set the variable using newDate."
},
{
"code": null,
"e": 882,
"s": 801,
"text": "const nDate = new Date().toLocaleString('en-US', {\ntimeZone: 'Asia/Calcutta'\n});"
},
{
"code": null,
"e": 952,
"s": 882,
"text": "3. We can config global timezone with the library tzdata in our code:"
},
{
"code": null,
"e": 975,
"s": 952,
"text": "npm install tzdata -yN"
},
{
"code": null,
"e": 1010,
"s": 975,
"text": "Now in app.js set the value of TZ."
},
{
"code": null,
"e": 1067,
"s": 1010,
"text": "TZ = 'Asia/Calcutta'\nconsole.log(new Date().toString());"
},
{
"code": null,
"e": 1078,
"s": 1067,
"text": "Example 1:"
},
{
"code": null,
"e": 1085,
"s": 1078,
"text": "app.js"
},
{
"code": "var express = require('express'),app = express(); // Method 1const nDate = new Date().toLocaleString('en-US', { timeZone: 'Asia/Calcutta'}); console.log(nDate); app.listen(3000,function(){ console.log(\"Express Started on Port 3000\");});",
"e": 1329,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1331,
"text": "Run app.js file using below command:"
},
{
"code": null,
"e": 1380,
"s": 1368,
"text": "node app.js"
},
{
"code": null,
"e": 1388,
"s": 1380,
"text": "Output:"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": "Example 2:"
},
{
"code": null,
"e": 1406,
"s": 1399,
"text": "app.js"
},
{
"code": "var express = require('express'),app = express(); // Method 2process.env.TZ = \"Asia/Calcutta\";console.log(new Date().toString()); app.listen(3000,function(){ console.log(\"Express Started on Port 3000\");});",
"e": 1619,
"s": 1406,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1619,
"text": "Run app.js file using below command:"
},
{
"code": null,
"e": 1668,
"s": 1656,
"text": "node app.js"
},
{
"code": null,
"e": 1676,
"s": 1668,
"text": "Output:"
},
{
"code": null,
"e": 1687,
"s": 1676,
"text": "Example 3:"
},
{
"code": null,
"e": 1694,
"s": 1687,
"text": "app.js"
},
{
"code": "var express = require('express'), app = express(); // Method 3TZ = 'Asia/Calcutta'console.log(new Date().toString()); app.listen(3000,function(){ console.log(\"Express Started on Port 3000\");});",
"e": 1894,
"s": 1694,
"text": null
},
{
"code": null,
"e": 1931,
"s": 1894,
"text": "Run app.js file using below command:"
},
{
"code": null,
"e": 1943,
"s": 1931,
"text": "node app.js"
},
{
"code": null,
"e": 1951,
"s": 1943,
"text": "Output:"
},
{
"code": null,
"e": 1966,
"s": 1951,
"text": "prachisoda1234"
},
{
"code": null,
"e": 1977,
"s": 1966,
"text": "Express.js"
},
{
"code": null,
"e": 1994,
"s": 1977,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 2001,
"s": 1994,
"text": "Picked"
},
{
"code": null,
"e": 2009,
"s": 2001,
"text": "Node.js"
},
{
"code": null,
"e": 2026,
"s": 2009,
"text": "Web Technologies"
},
{
"code": null,
"e": 2124,
"s": 2026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2159,
"s": 2124,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2191,
"s": 2159,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2261,
"s": 2191,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 2288,
"s": 2261,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2313,
"s": 2288,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 2375,
"s": 2313,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2436,
"s": 2375,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2486,
"s": 2436,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2529,
"s": 2486,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
R | Simple Linear Regression
|
14 Sep, 2021
Linear Regression: It is a commonly used type of predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables.
There are two types of linear regression.
Simple Linear Regression
Multiple Linear Regression
Let’s discuss Simple Linear regression using R.
It is a statistical method that allows us to summarize and study relationships between two continuous (quantitative) variables. One variable denoted x is regarded as an independent variable and the other one denoted y is regarded as a dependent variable. It is assumed that the two variables are linearly related. Hence, we try to find a linear function that predicts the response value(y) as accurately as possible as a function of the feature or independent variable(x).
For understanding the concept let’s consider a salary dataset where it is given the value of the dependent variable(salary) for every independent variable(years experienced).
Salary dataset:
Years experienced Salary
1.1 39343.00
1.3 46205.00
1.5 37731.00
2.0 43525.00
2.2 39891.00
2.9 56642.00
3.0 60150.00
3.2 54445.00
3.2 64445.00
3.7 57189.00
For general purpose, we define:
x as a feature vector, i.e x = [x_1, x_2, ...., x_n],
y as a response vector, i.e y = [y_1, y_2, ...., y_n]
for n observations (in above example, n=10).
Scatter plot of given dataset:
Now, we have to find a line that fits the above scatter plot through which we can predict any value of y or response for any value of x The line which best fits is called the Regression line.
The equation of regression line is given by:
y = a + bx
Where y is the predicted response value, a is the y-intercept, x is the feature value and b is a slope.To create the model, let’s evaluate the values of regression coefficient a and b. And as soon as the estimation of these coefficients is done, the response model can be predicted. Here we are going to use Least Square Technique.
The principle of least squares is one of the popular methods for finding a curve fitting a given data. Say (x1, y1), (x2, y2)....(xn, yn) be n observations from an experiment. We are interested in finding a curve Closely fitting the given data of size ‘n’. Now at x=x1 while the observed value of y is y1 the expected value of y from curve (1) is f(x1). Then the residual can be defined by... Similarly residual for x2, x3...xn are given by ...While evaluating the residual we will find that some residuals are positives and some are negatives. We are looking forward to finding the curve fitting the given data such that residual at any xi is minimum. Since some of the residuals are positive and others are negative and as we would like to give equal importance to all the residuals it is desirable to consider the sum of the squares of these residuals. Thus we consider:and find the best representative curve.
Least Square Fit of a Straight Line
Suppose, given a dataset (x1, y1), (x2, y2), (x3, y3).....(xn, yn) of n observation from an experiment. And we are interested in fitting a straight line. to the given data.Now consider: Now consider the sum of the squares of ei
Note: E is a function of parameters a and b and we need to find a and b such that E is minimum and the necessary condition for E to be minimum is as follows:
This condition yields: The above two equations are called normal equations which are solved to get the value of a and b.The Expression for E can be rewritten as: The basic syntax for a regression analysis in R is
lm(Y ~ model)
where Y is the object containing the dependent variable to be predicted and model is the formula for the chosen mathematical model.The command lm( ) provides the model’s coefficients but no further statistical information.
Following R code is used to implement SIMPLE LINEAR REGRESSION:
Python3
# Simple Linear Regression# Importing the datasetdataset = read.csv('salary.csv') # Splitting the dataset into the# Training set and Test setinstall.packages('caTools')library(caTools)split = sample.split(dataset$Salary, SplitRatio = 0.7)trainingset = subset(dataset, split == TRUE)testset = subset(dataset, split == FALSE) # Fitting Simple Linear Regression to the Training setlm.r= lm(formula = Salary ~ YearsExperience, data = trainingset)coef(lm.r) # Predicting the Test set resultsypred = predict(lm.r, newdata = testset) install.packages("ggplot2")library(ggplot2) # Visualising the Training set resultsggplot() + geom_point(aes(x = trainingset$YearsExperience, y = trainingset$Salary), colour = 'red') +geom_line(aes(x = trainingset$YearsExperience,y = predict(lm.r, newdata = trainingset)), colour = 'blue') + ggtitle('Salary vs Experience (Training set)') +xlab('Years of experience') +ylab('Salary') # Visualising the Test set results ggplot() + geom_point(aes(x = testset$YearsExperience, y = testset$Salary), colour = 'red') + geom_line(aes(x = trainingset$YearsExperience, y = predict(lm.r, newdata = trainingset)), colour = 'blue') + ggtitle('Salary vs Experience (Test set)') + xlab('Years of experience') + ylab('Salary')
Output of coef(lm.r): Visualizing the Training set results:
Visualizing the Testing set results:
vaibhavsinghtanwar
Advanced Computer Subject
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
Getting started with Machine Learning
How to Run a Python Script using Docker?
ML | Monte Carlo Tree Search (MCTS)
Agents in Artificial Intelligence
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 254,
"s": 52,
"text": "Linear Regression: It is a commonly used type of predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables. "
},
{
"code": null,
"e": 297,
"s": 254,
"text": "There are two types of linear regression. "
},
{
"code": null,
"e": 322,
"s": 297,
"text": "Simple Linear Regression"
},
{
"code": null,
"e": 349,
"s": 322,
"text": "Multiple Linear Regression"
},
{
"code": null,
"e": 398,
"s": 349,
"text": "Let’s discuss Simple Linear regression using R. "
},
{
"code": null,
"e": 871,
"s": 398,
"text": "It is a statistical method that allows us to summarize and study relationships between two continuous (quantitative) variables. One variable denoted x is regarded as an independent variable and the other one denoted y is regarded as a dependent variable. It is assumed that the two variables are linearly related. Hence, we try to find a linear function that predicts the response value(y) as accurately as possible as a function of the feature or independent variable(x)."
},
{
"code": null,
"e": 1047,
"s": 871,
"text": "For understanding the concept let’s consider a salary dataset where it is given the value of the dependent variable(salary) for every independent variable(years experienced). "
},
{
"code": null,
"e": 1063,
"s": 1047,
"text": "Salary dataset:"
},
{
"code": null,
"e": 1525,
"s": 1063,
"text": "Years experienced Salary\n\n 1.1 39343.00\n 1.3 46205.00\n 1.5 37731.00\n 2.0 43525.00\n 2.2 39891.00\n 2.9 56642.00\n 3.0 60150.00\n 3.2 54445.00\n 3.2 64445.00\n 3.7 57189.00"
},
{
"code": null,
"e": 1558,
"s": 1525,
"text": "For general purpose, we define: "
},
{
"code": null,
"e": 1613,
"s": 1558,
"text": "x as a feature vector, i.e x = [x_1, x_2, ...., x_n], "
},
{
"code": null,
"e": 1668,
"s": 1613,
"text": "y as a response vector, i.e y = [y_1, y_2, ...., y_n] "
},
{
"code": null,
"e": 1714,
"s": 1668,
"text": "for n observations (in above example, n=10). "
},
{
"code": null,
"e": 1748,
"s": 1716,
"text": "Scatter plot of given dataset: "
},
{
"code": null,
"e": 1941,
"s": 1748,
"text": "Now, we have to find a line that fits the above scatter plot through which we can predict any value of y or response for any value of x The line which best fits is called the Regression line. "
},
{
"code": null,
"e": 1987,
"s": 1941,
"text": "The equation of regression line is given by: "
},
{
"code": null,
"e": 2001,
"s": 1987,
"text": "y = a + bx "
},
{
"code": null,
"e": 2333,
"s": 2001,
"text": "Where y is the predicted response value, a is the y-intercept, x is the feature value and b is a slope.To create the model, let’s evaluate the values of regression coefficient a and b. And as soon as the estimation of these coefficients is done, the response model can be predicted. Here we are going to use Least Square Technique."
},
{
"code": null,
"e": 3247,
"s": 2333,
"text": "The principle of least squares is one of the popular methods for finding a curve fitting a given data. Say (x1, y1), (x2, y2)....(xn, yn) be n observations from an experiment. We are interested in finding a curve Closely fitting the given data of size ‘n’. Now at x=x1 while the observed value of y is y1 the expected value of y from curve (1) is f(x1). Then the residual can be defined by... Similarly residual for x2, x3...xn are given by ...While evaluating the residual we will find that some residuals are positives and some are negatives. We are looking forward to finding the curve fitting the given data such that residual at any xi is minimum. Since some of the residuals are positive and others are negative and as we would like to give equal importance to all the residuals it is desirable to consider the sum of the squares of these residuals. Thus we consider:and find the best representative curve. "
},
{
"code": null,
"e": 3284,
"s": 3247,
"text": "Least Square Fit of a Straight Line "
},
{
"code": null,
"e": 3514,
"s": 3284,
"text": "Suppose, given a dataset (x1, y1), (x2, y2), (x3, y3).....(xn, yn) of n observation from an experiment. And we are interested in fitting a straight line. to the given data.Now consider: Now consider the sum of the squares of ei "
},
{
"code": null,
"e": 3672,
"s": 3514,
"text": "Note: E is a function of parameters a and b and we need to find a and b such that E is minimum and the necessary condition for E to be minimum is as follows:"
},
{
"code": null,
"e": 3886,
"s": 3672,
"text": "This condition yields: The above two equations are called normal equations which are solved to get the value of a and b.The Expression for E can be rewritten as: The basic syntax for a regression analysis in R is "
},
{
"code": null,
"e": 3901,
"s": 3886,
"text": "lm(Y ~ model) "
},
{
"code": null,
"e": 4124,
"s": 3901,
"text": "where Y is the object containing the dependent variable to be predicted and model is the formula for the chosen mathematical model.The command lm( ) provides the model’s coefficients but no further statistical information."
},
{
"code": null,
"e": 4189,
"s": 4124,
"text": "Following R code is used to implement SIMPLE LINEAR REGRESSION: "
},
{
"code": null,
"e": 4197,
"s": 4189,
"text": "Python3"
},
{
"code": "# Simple Linear Regression# Importing the datasetdataset = read.csv('salary.csv') # Splitting the dataset into the# Training set and Test setinstall.packages('caTools')library(caTools)split = sample.split(dataset$Salary, SplitRatio = 0.7)trainingset = subset(dataset, split == TRUE)testset = subset(dataset, split == FALSE) # Fitting Simple Linear Regression to the Training setlm.r= lm(formula = Salary ~ YearsExperience, data = trainingset)coef(lm.r) # Predicting the Test set resultsypred = predict(lm.r, newdata = testset) install.packages(\"ggplot2\")library(ggplot2) # Visualising the Training set resultsggplot() + geom_point(aes(x = trainingset$YearsExperience, y = trainingset$Salary), colour = 'red') +geom_line(aes(x = trainingset$YearsExperience,y = predict(lm.r, newdata = trainingset)), colour = 'blue') + ggtitle('Salary vs Experience (Training set)') +xlab('Years of experience') +ylab('Salary') # Visualising the Test set results ggplot() + geom_point(aes(x = testset$YearsExperience, y = testset$Salary), colour = 'red') + geom_line(aes(x = trainingset$YearsExperience, y = predict(lm.r, newdata = trainingset)), colour = 'blue') + ggtitle('Salary vs Experience (Test set)') + xlab('Years of experience') + ylab('Salary')",
"e": 5529,
"s": 4197,
"text": null
},
{
"code": null,
"e": 5591,
"s": 5529,
"text": "Output of coef(lm.r): Visualizing the Training set results: "
},
{
"code": null,
"e": 5630,
"s": 5591,
"text": "Visualizing the Testing set results: "
},
{
"code": null,
"e": 5649,
"s": 5630,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 5675,
"s": 5649,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 5692,
"s": 5675,
"text": "Machine Learning"
},
{
"code": null,
"e": 5703,
"s": 5692,
"text": "R Language"
},
{
"code": null,
"e": 5720,
"s": 5703,
"text": "Machine Learning"
},
{
"code": null,
"e": 5818,
"s": 5720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5841,
"s": 5818,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 5867,
"s": 5841,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5905,
"s": 5867,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 5946,
"s": 5905,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 5982,
"s": 5946,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6016,
"s": 5982,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 6040,
"s": 6016,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 6078,
"s": 6040,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 6119,
"s": 6078,
"text": "Introduction to Recurrent Neural Network"
}
] |
Indus Valley Partners Interview Experience for Associate Software Developer | On-Campus 2021
|
24 Aug, 2021
Eligibility Criteria: Throughout 65% (10th,12th, UG, and PG individually)
Round 1: The first round comprised of 65 MCQ questions (Test Duration: 65 minutes):
This round consisted of objective Single choice questions on 4 sections – SQL, OOPS, C#, JavaScript in the Mettl Test platform.
You can shift to any section.
There was no negative marking.
The test was not procured.
Round 2(Technical Interview Round-1): The interview started with Tell me about yourself.
Explain OOPs Concept.
Why are abstract classes needed over interface? (Explained with real-life example)
I was asked to share my screen and write a code of merge sort on online ide.
A is Base class and B is Derived Class Then which are valid Statements? A a1=new A(); //Valid
A a2=new B(); //Valid
B b1=new B(); //Valid
B b2=new A(); //Invalid
A a1=new A(); //Valid
A a2=new B(); //Valid
B b1=new B(); //Valid
B b2=new A(); //Invalid
How to get a third-last element of the linked list? ( You are not given the size of the linked list.)
Every element appears thrice except one element. Solve it in 0(N) Time complexity with no restriction on space complexity. Input: [2,2,2,1,3,3,3]
Output:1
Input: [2,2,2,1,3,3,3]
Output:1
How will you fetch your name using the MongoDB query? (I have mentioned MongoDb in my resume.)
What is left join on these two tables? Table A Table B
1 1
2 2
3 3
3 4
Ans:
1 1
2 2
3 3
3 3
Table A Table B
1 1
2 2
3 3
3 4
Ans:
1 1
2 2
3 3
3 3
You have to distribute 17 horses to three persons where A gets 1/2 horses B gets 1/3 and C gets 1/9.A=ceil(17/2)=9 horses
B=ceil(17/3)=6 horses
C=ceil(17/9)=2 horses
9+6+2=17
A=ceil(17/2)=9 horses
B=ceil(17/3)=6 horses
C=ceil(17/9)=2 horses
9+6+2=17
The interview Duration was 35-40 minutes.
Round-3 (Technical Interview Round-2)
I was asked which programming language I am comfortable with. ( I told Java)
Why do you need a protected modifier and explain with real-life examples?
Why do you need interfaces in java?
Can you create an object of the parent class with reference to the child class? (Ans: No)
What is function overloading?
Can we overload the function with the same name and signature but a different return type? (Ans: No) int fun(int a);
String fun(int a);
int fun(int a);
String fun(int a);
Sir shared his screen and I need to tell the output of the Program. (Question was on Dynamic polymorphism).
Difference between centralized and noncentralized Databases?
I was asked to write a join query. Sir has shared his screen to show me tables which I need to join.
The interview Duration was 20-25 minutes.
Round 4(HR Round): I was asked to read my resume for her.
I was asked do I know what will be my job responsibilities.
She asked me do I know the names of my interviews in Round 1 and Round 2.
Explain Academics projects.
Explain Internships.
Have you ever worked in a team? Then what do you do in case of conflict?
I was asked if I have any questions for her. (I asked one).
The interview Duration was 10-15 minutes.
Tips: Read your resume before the interview. Be calm & answer politely.
Verdict: Selected
Indus Valley Partners
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
Write It Up: Share Your Interview Experiences
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE-1
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Nagarro Interview Experience
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
Nagarro Interview Experience | On-Campus 2021
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "Eligibility Criteria: Throughout 65% (10th,12th, UG, and PG individually)"
},
{
"code": null,
"e": 186,
"s": 102,
"text": "Round 1: The first round comprised of 65 MCQ questions (Test Duration: 65 minutes):"
},
{
"code": null,
"e": 314,
"s": 186,
"text": "This round consisted of objective Single choice questions on 4 sections – SQL, OOPS, C#, JavaScript in the Mettl Test platform."
},
{
"code": null,
"e": 344,
"s": 314,
"text": "You can shift to any section."
},
{
"code": null,
"e": 375,
"s": 344,
"text": "There was no negative marking."
},
{
"code": null,
"e": 402,
"s": 375,
"text": "The test was not procured."
},
{
"code": null,
"e": 491,
"s": 402,
"text": "Round 2(Technical Interview Round-1): The interview started with Tell me about yourself."
},
{
"code": null,
"e": 513,
"s": 491,
"text": "Explain OOPs Concept."
},
{
"code": null,
"e": 596,
"s": 513,
"text": "Why are abstract classes needed over interface? (Explained with real-life example)"
},
{
"code": null,
"e": 673,
"s": 596,
"text": "I was asked to share my screen and write a code of merge sort on online ide."
},
{
"code": null,
"e": 863,
"s": 673,
"text": "A is Base class and B is Derived Class Then which are valid Statements? A a1=new A(); //Valid\n\n A a2=new B(); //Valid\n\n B b1=new B(); //Valid\n\n B b2=new A(); //Invalid "
},
{
"code": null,
"e": 982,
"s": 863,
"text": " A a1=new A(); //Valid\n\n A a2=new B(); //Valid\n\n B b1=new B(); //Valid\n\n B b2=new A(); //Invalid "
},
{
"code": null,
"e": 1084,
"s": 982,
"text": "How to get a third-last element of the linked list? ( You are not given the size of the linked list.)"
},
{
"code": null,
"e": 1247,
"s": 1084,
"text": "Every element appears thrice except one element. Solve it in 0(N) Time complexity with no restriction on space complexity. Input: [2,2,2,1,3,3,3]\n\n Output:1"
},
{
"code": null,
"e": 1288,
"s": 1247,
"text": " Input: [2,2,2,1,3,3,3]\n\n Output:1"
},
{
"code": null,
"e": 1383,
"s": 1288,
"text": "How will you fetch your name using the MongoDB query? (I have mentioned MongoDb in my resume.)"
},
{
"code": null,
"e": 1696,
"s": 1383,
"text": "What is left join on these two tables? Table A Table B\n\n 1 1\n\n 2 2\n\n 3 3\n\n 3 4\n\n Ans:\n\n 1 1\n\n 2 2\n\n 3 3\n\n 3 3"
},
{
"code": null,
"e": 1971,
"s": 1696,
"text": " Table A Table B\n\n 1 1\n\n 2 2\n\n 3 3\n\n 3 4\n\n Ans:\n\n 1 1\n\n 2 2\n\n 3 3\n\n 3 3"
},
{
"code": null,
"e": 2146,
"s": 1971,
"text": "You have to distribute 17 horses to three persons where A gets 1/2 horses B gets 1/3 and C gets 1/9.A=ceil(17/2)=9 horses\nB=ceil(17/3)=6 horses\nC=ceil(17/9)=2 horses\n9+6+2=17"
},
{
"code": null,
"e": 2221,
"s": 2146,
"text": "A=ceil(17/2)=9 horses\nB=ceil(17/3)=6 horses\nC=ceil(17/9)=2 horses\n9+6+2=17"
},
{
"code": null,
"e": 2263,
"s": 2221,
"text": "The interview Duration was 35-40 minutes."
},
{
"code": null,
"e": 2301,
"s": 2263,
"text": "Round-3 (Technical Interview Round-2)"
},
{
"code": null,
"e": 2378,
"s": 2301,
"text": "I was asked which programming language I am comfortable with. ( I told Java)"
},
{
"code": null,
"e": 2452,
"s": 2378,
"text": "Why do you need a protected modifier and explain with real-life examples?"
},
{
"code": null,
"e": 2488,
"s": 2452,
"text": "Why do you need interfaces in java?"
},
{
"code": null,
"e": 2578,
"s": 2488,
"text": "Can you create an object of the parent class with reference to the child class? (Ans: No)"
},
{
"code": null,
"e": 2608,
"s": 2578,
"text": "What is function overloading?"
},
{
"code": null,
"e": 2752,
"s": 2608,
"text": "Can we overload the function with the same name and signature but a different return type? (Ans: No) int fun(int a);\n\n String fun(int a);"
},
{
"code": null,
"e": 2796,
"s": 2752,
"text": " int fun(int a);\n\n String fun(int a);"
},
{
"code": null,
"e": 2904,
"s": 2796,
"text": "Sir shared his screen and I need to tell the output of the Program. (Question was on Dynamic polymorphism)."
},
{
"code": null,
"e": 2965,
"s": 2904,
"text": "Difference between centralized and noncentralized Databases?"
},
{
"code": null,
"e": 3066,
"s": 2965,
"text": "I was asked to write a join query. Sir has shared his screen to show me tables which I need to join."
},
{
"code": null,
"e": 3108,
"s": 3066,
"text": "The interview Duration was 20-25 minutes."
},
{
"code": null,
"e": 3166,
"s": 3108,
"text": "Round 4(HR Round): I was asked to read my resume for her."
},
{
"code": null,
"e": 3226,
"s": 3166,
"text": "I was asked do I know what will be my job responsibilities."
},
{
"code": null,
"e": 3300,
"s": 3226,
"text": "She asked me do I know the names of my interviews in Round 1 and Round 2."
},
{
"code": null,
"e": 3328,
"s": 3300,
"text": "Explain Academics projects."
},
{
"code": null,
"e": 3349,
"s": 3328,
"text": "Explain Internships."
},
{
"code": null,
"e": 3422,
"s": 3349,
"text": "Have you ever worked in a team? Then what do you do in case of conflict?"
},
{
"code": null,
"e": 3482,
"s": 3422,
"text": "I was asked if I have any questions for her. (I asked one)."
},
{
"code": null,
"e": 3524,
"s": 3482,
"text": "The interview Duration was 10-15 minutes."
},
{
"code": null,
"e": 3596,
"s": 3524,
"text": "Tips: Read your resume before the interview. Be calm & answer politely."
},
{
"code": null,
"e": 3614,
"s": 3596,
"text": "Verdict: Selected"
},
{
"code": null,
"e": 3636,
"s": 3614,
"text": "Indus Valley Partners"
},
{
"code": null,
"e": 3646,
"s": 3636,
"text": "Marketing"
},
{
"code": null,
"e": 3656,
"s": 3646,
"text": "On-Campus"
},
{
"code": null,
"e": 3678,
"s": 3656,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3776,
"s": 3678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3814,
"s": 3776,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 3870,
"s": 3814,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 3916,
"s": 3870,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 3989,
"s": 3916,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 4027,
"s": 3989,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 4097,
"s": 4027,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 4126,
"s": 4097,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 4192,
"s": 4126,
"text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)"
},
{
"code": null,
"e": 4264,
"s": 4192,
"text": "Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22"
}
] |
Square Free Number
|
07 Apr, 2021
Given a number, check if it is square free or not. A number is said to be square free if no prime factor divides it more than once, i.e., largest power of a prime factor that divides n is one. First few square free numbers are 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, ...Examples:
Input : n = 10
Output : Yes
10 can be factorized as 2*5. Since
no prime factor appears more than
once, it is a square free number.
Input : n = 20
Output : No
20 can be factorized as 2 * 2 * 5.
Since prime factor appears more than
once, it is not a square free number.
The idea is simple, we one by one find all prime factors. For every prime factor, we check if its square also divides n. If yes, then we return false. Finally if we do not find a prime factor which is divisible more than once, we return false.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to print// all prime factors# include <bits/stdc++.h>using namespace std; // Returns true if n is a square free// number, else returns false.bool isSquareFree(int n){ if (n % 2 == 0) n = n/2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // Check if i is a prime factor if (n % i == 0) { n = n/i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true;} /* Driver program to test above function */int main(){ int n = 10; if (isSquareFree(n)) cout << "Yes"; else cout << "No"; return 0;}
// Java Program to print// all prime factors class GFG { // Returns true if n is a square free // number, else returns false. static boolean isSquareFree(int n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; if (isSquareFree(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by prerna saini.
# Python3 Program to print# all prime factorsfrom math import sqrt # Returns true if n is# a square free number,# else returns false.def isSquareFree(n): if n % 2 == 0: n = n / 2 # If 2 again divides n, # then n is not a square # free number. if n % 2 == 0: return False # n must be odd at this # point. So we can skip # one element # (Note i = i + 2) for i in range(3, int(sqrt(n) + 1)): # Check if i is a prime # factor if n % i == 0: n = n / i # If i again divides, then # n is not square free if n % i == 0: return False return True # Driver programn = 10 if isSquareFree(n): print ("Yes")else: print ("No") # This code is contributed by Shreyanshi Arun.
// C# Program to print// all prime factorsusing System; class GFG { // Returns true if n is a square free // number, else returns false. static bool isSquareFree(int n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } // Driver program public static void Main() { int n = 10; if (isSquareFree(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP Program to print// all prime factors // Returns true if n is a square free// number, else returns false.function isSquareFree($n){ if ($n % 2 == 0) $n = $n / 2; // If 2 again divides n, then n is // not a square free number. if ($n % 2 == 0) return false; // n must be odd at this // point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // Check if i is a prime factor if ($n % $i == 0) { $n = $n / $i; // If i again divides, then // n is not square free if ($n % $i == 0) return false; } } return true;} // Driver Code$n = 10;if (isSquareFree($n)) echo("Yes");else echo("No"); // This code is contributed by Ajit.?>
<script> // JavaScript Program to print// all prime factors // Returns true if n is a square free // number, else returns false. function isSquareFree(n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } // Driver code let n = 10; if (isSquareFree(n)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity : O(sqrt(N)) In the worst case when the number is a perfect square, then there will be sqrt(n)/2 iterations .
jit_t
imdhruvgupta
code_hunt
divisors
prime-factor
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Find minimum number of coins that make a given value
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 394,
"s": 54,
"text": "Given a number, check if it is square free or not. A number is said to be square free if no prime factor divides it more than once, i.e., largest power of a prime factor that divides n is one. First few square free numbers are 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, ...Examples: "
},
{
"code": null,
"e": 664,
"s": 394,
"text": "Input : n = 10\nOutput : Yes\n10 can be factorized as 2*5. Since\nno prime factor appears more than\nonce, it is a square free number.\n\nInput : n = 20\nOutput : No\n20 can be factorized as 2 * 2 * 5.\nSince prime factor appears more than\nonce, it is not a square free number."
},
{
"code": null,
"e": 911,
"s": 666,
"text": "The idea is simple, we one by one find all prime factors. For every prime factor, we check if its square also divides n. If yes, then we return false. Finally if we do not find a prime factor which is divisible more than once, we return false. "
},
{
"code": null,
"e": 915,
"s": 911,
"text": "C++"
},
{
"code": null,
"e": 920,
"s": 915,
"text": "Java"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": null,
"e": 931,
"s": 928,
"text": "C#"
},
{
"code": null,
"e": 935,
"s": 931,
"text": "PHP"
},
{
"code": null,
"e": 946,
"s": 935,
"text": "Javascript"
},
{
"code": "// C++ Program to print// all prime factors# include <bits/stdc++.h>using namespace std; // Returns true if n is a square free// number, else returns false.bool isSquareFree(int n){ if (n % 2 == 0) n = n/2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // Check if i is a prime factor if (n % i == 0) { n = n/i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true;} /* Driver program to test above function */int main(){ int n = 10; if (isSquareFree(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 1815,
"s": 946,
"text": null
},
{
"code": "// Java Program to print// all prime factors class GFG { // Returns true if n is a square free // number, else returns false. static boolean isSquareFree(int n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; if (isSquareFree(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by prerna saini.",
"e": 2922,
"s": 1815,
"text": null
},
{
"code": "# Python3 Program to print# all prime factorsfrom math import sqrt # Returns true if n is# a square free number,# else returns false.def isSquareFree(n): if n % 2 == 0: n = n / 2 # If 2 again divides n, # then n is not a square # free number. if n % 2 == 0: return False # n must be odd at this # point. So we can skip # one element # (Note i = i + 2) for i in range(3, int(sqrt(n) + 1)): # Check if i is a prime # factor if n % i == 0: n = n / i # If i again divides, then # n is not square free if n % i == 0: return False return True # Driver programn = 10 if isSquareFree(n): print (\"Yes\")else: print (\"No\") # This code is contributed by Shreyanshi Arun.",
"e": 3719,
"s": 2922,
"text": null
},
{
"code": "// C# Program to print// all prime factorsusing System; class GFG { // Returns true if n is a square free // number, else returns false. static bool isSquareFree(int n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } // Driver program public static void Main() { int n = 10; if (isSquareFree(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 4781,
"s": 3719,
"text": null
},
{
"code": "<?php// PHP Program to print// all prime factors // Returns true if n is a square free// number, else returns false.function isSquareFree($n){ if ($n % 2 == 0) $n = $n / 2; // If 2 again divides n, then n is // not a square free number. if ($n % 2 == 0) return false; // n must be odd at this // point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { // Check if i is a prime factor if ($n % $i == 0) { $n = $n / $i; // If i again divides, then // n is not square free if ($n % $i == 0) return false; } } return true;} // Driver Code$n = 10;if (isSquareFree($n)) echo(\"Yes\");else echo(\"No\"); // This code is contributed by Ajit.?>",
"e": 5630,
"s": 4781,
"text": null
},
{
"code": "<script> // JavaScript Program to print// all prime factors // Returns true if n is a square free // number, else returns false. function isSquareFree(n) { if (n % 2 == 0) n = n / 2; // If 2 again divides n, then n is // not a square free number. if (n % 2 == 0) return false; // n must be odd at this point. So we can // skip one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // Check if i is a prime factor if (n % i == 0) { n = n / i; // If i again divides, then // n is not square free if (n % i == 0) return false; } } return true; } // Driver code let n = 10; if (isSquareFree(n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 6616,
"s": 5630,
"text": null
},
{
"code": null,
"e": 6620,
"s": 6616,
"text": "Yes"
},
{
"code": null,
"e": 6749,
"s": 6622,
"text": "Time Complexity : O(sqrt(N)) In the worst case when the number is a perfect square, then there will be sqrt(n)/2 iterations . "
},
{
"code": null,
"e": 6755,
"s": 6749,
"text": "jit_t"
},
{
"code": null,
"e": 6768,
"s": 6755,
"text": "imdhruvgupta"
},
{
"code": null,
"e": 6778,
"s": 6768,
"text": "code_hunt"
},
{
"code": null,
"e": 6787,
"s": 6778,
"text": "divisors"
},
{
"code": null,
"e": 6800,
"s": 6787,
"text": "prime-factor"
},
{
"code": null,
"e": 6813,
"s": 6800,
"text": "Mathematical"
},
{
"code": null,
"e": 6826,
"s": 6813,
"text": "Mathematical"
},
{
"code": null,
"e": 6924,
"s": 6826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6948,
"s": 6924,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 6969,
"s": 6948,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 6991,
"s": 6969,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 7005,
"s": 6991,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7047,
"s": 7005,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 7084,
"s": 7047,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7127,
"s": 7084,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 7159,
"s": 7127,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7212,
"s": 7159,
"text": "Find minimum number of coins that make a given value"
}
] |
Last Minute Notes Computer Organization
|
29 Jun, 2022
Control Unit –A control unit (CU) handles all processor control signals. It directs all input and output flow, fetches the code for instructions and controlling how data moves around the system.
A control unit (CU) handles all processor control signals. It directs all input and output flow, fetches the code for instructions and controlling how data moves around the system.
Arithmetic and Logic Unit (ALU) –The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation.Figure – Basic CPU structure, illustrating ALU
The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation.
Main Memory Unit (Registers) –Accumulator: Stores the results of calculations made by ALU.Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR.
Accumulator: Stores the results of calculations made by ALU.Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR.
Accumulator: Stores the results of calculations made by ALU.
Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).
Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.
Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.
Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.
Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR.
Input/Output Devices – Program or data is read into main memory from the input device or secondary storage under the control of CPU input instruction. Output devices are used to output the information from a computer.
Buses – Data is transmitted from one part of a computer to another, connecting all major internal components to the CPU and memory, by the means of Buses. Types:Data Bus: It carries data among the memory unit, the I/O devices, and the processor.Address Bus: It carries the address of data (not the actual data) between memory and processor.Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer.
Data Bus: It carries data among the memory unit, the I/O devices, and the processor.Address Bus: It carries the address of data (not the actual data) between memory and processor.Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer.
Data Bus: It carries data among the memory unit, the I/O devices, and the processor.
Address Bus: It carries the address of data (not the actual data) between memory and processor.
Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer.
A instruction is of various length depending upon the number of addresses it contain. Generally CPU organization are of three types on the basis of number of address fields:
Single Accumulator organizationGeneral register organizationStack organization
Single Accumulator organization
General register organization
Stack organization
Zero Address Instructions –Address is stored in the opcode, in the zero address instruction. A stack based organization uses zero address instruction.One Address Instructions –This use a implied ACCUMULATOR register for data manipulation. One operand is in accumulator and other is in register or memory location. Implied means that the CPU already know that one operand is in accumulator so there is no need to specify it. i.e there will be one opcode field and one address field.Two Address Instructions –Here two address can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in accumulator here result can be stored at a different location rather than just accumulator, but require the number more of the bit to represent address.Three Address Instructions –This has three address field to specify a register or a memory location. The program created is much short in size but the number of bits per instruction increase.
Zero Address Instructions –Address is stored in the opcode, in the zero address instruction. A stack based organization uses zero address instruction.
One Address Instructions –This use a implied ACCUMULATOR register for data manipulation. One operand is in accumulator and other is in register or memory location. Implied means that the CPU already know that one operand is in accumulator so there is no need to specify it. i.e there will be one opcode field and one address field.
Two Address Instructions –Here two address can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in accumulator here result can be stored at a different location rather than just accumulator, but require the number more of the bit to represent address.
Three Address Instructions –This has three address field to specify a register or a memory location. The program created is much short in size but the number of bits per instruction increase.
The term addressing modes refers to the way in which the operand of an instruction is specified. The addressing mode specifies a rule for interpreting or modifying the address field of the instruction before the operand is actually executed.
An assembly language program instruction consists of two parts
IMPORTANT TERMS
Starting address of memory segment.
Effective address or Offset: An offset is determined by adding any combination of three address elements: displacement, base and index.Displacement: It is an 8 bit or 16 bit immediate value given in the instruction.Base: Contents of base register, BX or BP.Index: Content of index register SI or DI.
Displacement: It is an 8 bit or 16 bit immediate value given in the instruction.
Base: Contents of base register, BX or BP.
Index: Content of index register SI or DI.
Implied mode:: In implied addressing the operand is specified in the instruction itself. In this mode the data is 8 bits or 16 bits long and data is the part of instruction.Zero address instruction are designed with implied addressing mode.
Immediate addressing mode (symbol #):In this mode data is present in address field of instruction .Designed like one address instruction format.Note:Limitation in the immediate mode is that the range of constants are restricted by size of address field.
Register mode: In register addressing the operand is placed in one of 8 bit or 16 bit general purpose registers. The data is in the register that is specified by the instruction.Here one register reference is required to access the data.
Register Indirect mode: In this addressing the operand’s offset is placed in any one of the registers BX, BP, SI, DI as specified in the instruction. The effective address of the data is in the base register or an index register that is specified by the instruction.Here two register reference is required to access the data.
Auto Indexed (increment mode): Effective address of the operand is the contents of a register specified in the instruction. After accessing the operand, the contents of this register are automatically incremented to point to the next consecutive memory location.(R1)+.Here one register reference, one memory reference, and one ALU operation is required to access the data.
Auto indexed ( decrement mode): Effective address of the operand is the contents of a register specified in the instruction. Before accessing the operand, the contents of this register are automatically decremented to point to the previous consecutive memory location. –(R1)Here one register reference, one memory reference and one ALU operation is required to access the data.
Auto decrement mode is the same as the auto-increment mode. Both can also be used to implement a stack as push and pop. Auto increment and Auto-decrement modes are useful for implementing “Last-In-First-Out” data structures.
Direct addressing/ Absolute addressing Mode (symbol [ ]): The operand’s offset is given in the instruction as an 8 bit or 16 bit displacement element. In this addressing mode, the 16-bit effective address of the data is part of the instruction.Here only one memory reference operation is required to access the data.
Indirect addressing Mode (symbol @ or () ):In this mode address field of instruction contains the address of effective address.Here two references are required.1st reference to get an effective address.2nd reference to access the data.
Indexed addressing mode: The operand’s offset is the sum of the content of an index register SI or DI and an 8 bit or 16-bit displacement.
Based Indexed Addressing: The operand’s offset is sum of the content of a base register BX or BP and an index register SI or DI.
Based on Transfer of control, addressing modes are:
PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value
PC= PC + Relative value.
EA= PC + Address field value
PC= PC + Relative value.
Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value.
PC= Base register + Relative value.
Note:PC relative and based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes.
EA= Base register + Address field value.
PC= Base register + Relative value.
Note:
PC relative and based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes.
PC relative and based register both addressing modes are suitable for program relocation at runtime.
Based register addressing mode is best suitable to write position independent codes.
Characteristic of RISC –Simpler instruction, hence simple instruction decoding.Instruction come under size of one word.Instruction take single clock cycle to get executed.More number of general purpose register.Simple Addressing Modes.Less Data types.Pipeling can be achieved.
Simpler instruction, hence simple instruction decoding.
Instruction come under size of one word.
Instruction take single clock cycle to get executed.
More number of general purpose register.
Simple Addressing Modes.
Less Data types.
Pipeling can be achieved.
Characteristic of CISC –Complex instruction, hence complex instruction decoding.Instruction are larger than one word size.Instruction may take more than single clock cycle to get executed.Less number of general purpose register as operation get performed in memory itself.Complex Addressing Modes.More Data types.
Complex instruction, hence complex instruction decoding.
Instruction are larger than one word size.
Instruction may take more than single clock cycle to get executed.
Less number of general purpose register as operation get performed in memory itself.
Complex Addressing Modes.
More Data types.
Hardwired Control Unit –
Fixed logic circuits that correspond directly to the Boolean expressions are used to generate the control signals.
Hardwired control is faster than micro-programmed control.
A controller that uses this approach can operate at high speed.
RISC architecture is based on hardwired control unit.
The control signals associated with operations are stored in special memory units inaccessible by the programmer as Control Words.
Control signals are generated by a program are similar to machine language programs.
Micro-programmed control unit is slower in speed because of the time it takes to fetch microinstructions from the control memory.
There are two type Micro-programmed control Unit:Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS.Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required.
There are two type Micro-programmed control Unit:Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS.Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required.
Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS.
Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required.
Registers Involved In Each Instruction Cycle:
Memory address registers(MAR) : It is connected to the address lines of the system bus. It specifies the address in memory for a read or write operation.
Memory Buffer Register(MBR) : It is connected to the data lines of the system bus. It contains the value to be stored in memory or the last value read from the memory.
Program Counter(PC) : Holds the address of the next instruction to be fetched.
Instruction Register(IR) : Holds the last instruction fetched.
The Indirect Cycle is always followed by the Execute Cycle. The Interrupt Cycle is always followed by the Fetch Cycle. For both fetch and execute cycles, the next cycle depends on the state of the system.
The Fetch Cycle –At the beginning of the fetch cycle, the address of the next instruction to be executed is in the Program Counter(PC).The Indirect Cycles –Once an instruction is fetched, the next step is to fetch source operands. Source Operand is being fetched by indirect addressing it can be fetched by any addressing mode, here its done by indirect addressing). Register-based operands need not be fetched. Once the opcode is executed, a similar process may be needed to store the result in the main memory.The Execute CycleThe other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur.The Interrupt Cycle:At the completion of the Execute Cycle, a test is made to determine whether any enabled interrupt has occurred or not. If an enabled interrupt has occurred then Interrupt Cycle occurs. The nature of this cycle varies greatly from one machine to another.
The Fetch Cycle –At the beginning of the fetch cycle, the address of the next instruction to be executed is in the Program Counter(PC).
The Indirect Cycles –Once an instruction is fetched, the next step is to fetch source operands. Source Operand is being fetched by indirect addressing it can be fetched by any addressing mode, here its done by indirect addressing). Register-based operands need not be fetched. Once the opcode is executed, a similar process may be needed to store the result in the main memory.
The Execute CycleThe other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur.
The other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur.
The Interrupt Cycle:At the completion of the Execute Cycle, a test is made to determine whether any enabled interrupt has occurred or not. If an enabled interrupt has occurred then Interrupt Cycle occurs. The nature of this cycle varies greatly from one machine to another.
Microprogram: Program stored in memory that generates all control signals required to execute the instruction set correctly, it consists micro-instructions.Micro-instruction: Contains a sequencing word and a control word. The control word is all control information required for one clock cycle.Micro-operations: Micro-operations are the atomic operations which executes a particular micro-instruction.Example of micro-operation during the fetch cycle:
t1: MAR ←(PC)
t2: MBR ←Memory
PC ←(PC) + I
t3: IR ←(MBR)
Memories are made up of registers. Each register in the memory is one storage location. The storage location is also called a memory location. Memory locations are identified using Address. The total number of bit a memory can store is its capacity.
Simultaneous access memory organization: If H1 and H2 are the Hit Ratios and T1 and T2 are the access time of L1 and L2 memory levels respectively then theAverage Memory Access Time can be calculated as:Hierarchical Access Memory Organizations: If H1 and H2 are the Hit Ratios and T1 and T2 are the access time of L1 and L2 memory levels respectively then theAverage Memory Access Time can be calculated as:
Cache Memory is a special very high-speed memory. It is used to speed up and synchronizing with high-speed CPU.Levels of memory: Level 1 or Register, Level 2 or Cache memory, Level 3 or Main Memory, Level 4 or Secondary Memory.
Hit ratio = hit / (hit + miss) = no. of hits/total accesses
Cache Mapping:
There are three different types of mapping used for the purpose of cache memory which is as follows: Direct mapping, Associative mapping, and Set-Associative mapping.Direct Mapping –Maps each block of main memory into only one possible cache line. If a line is previously taken up by a memory block and a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory.Associative Mapping –A block of main memory can map to any line of the cache that is freely available at that moment. The word offset bits are used to identify which word in the block is needed, all of the remaining bits become Tag.Set-Associative Mapping –Cache lines are grouped into sets where each set contains k number of lines and a particular block of main memory can map to only one particular set of the cache. However, within that set, the memory block can map to any freely available cache line.
Direct Mapping –Maps each block of main memory into only one possible cache line. If a line is previously taken up by a memory block and a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory.
Associative Mapping –A block of main memory can map to any line of the cache that is freely available at that moment. The word offset bits are used to identify which word in the block is needed, all of the remaining bits become Tag.
Set-Associative Mapping –Cache lines are grouped into sets where each set contains k number of lines and a particular block of main memory can map to only one particular set of the cache. However, within that set, the memory block can map to any freely available cache line.
Note: Translation Lookaside Buffer (i.e. TLB) is required only if Virtual Memory is used by a processor. In short, TLB speeds up the translation of virtual address to a physical address by storing page-table in faster memory. In fact, TLB also sits between the CPU and Main memory.
Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in the cache is decided based on the locality of reference.Types of Locality of reference
Spatial Locality of referenceSpatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future.Temporal Locality of referenceTemporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory to avoid searching again in main memory for the same data.
Spatial Locality of referenceSpatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future.
Temporal Locality of referenceTemporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory to avoid searching again in main memory for the same data.
Write PolicyWrite Through: In this technique, all write operations are made to main memory as well as to the cache, ensuring that main memory is always valid.For hierarchical access:For simultaneous access :Write Back: In write-back updates are made only in the cache. When an update occurs, a dirty bit, or use bit, associated with the line is set. Then, when a block is replaced, it is written back to main memory if and only if the dirty bit is set.For hierarchical access:For simultaneous access :
Write Through: In this technique, all write operations are made to main memory as well as to the cache, ensuring that main memory is always valid.For hierarchical access:For simultaneous access :
For simultaneous access :
Write Back: In write-back updates are made only in the cache. When an update occurs, a dirty bit, or use bit, associated with the line is set. Then, when a block is replaced, it is written back to main memory if and only if the dirty bit is set.For hierarchical access:For simultaneous access :
For simultaneous access :
Pipelining is a process of arrangement of hardware elements of the CPU such that its overall performance is increased. Simultaneous execution of more than one instruction takes place in a pipelined processor.RISC processor has 5 stage instruction pipeline to execute all the instructions in the RISC instruction set. Following are the 5 stages of RISC pipeline with their respective operations:
Stage 1 (Instruction Fetch)In this stage the CPU reads instructions from the address in the memory whose value is present in the program counter.
Stage 2 (Instruction Decode)In this stage, instruction is decoded and the register file is accessed to get the values from the registers used in the instruction.
Stage 3 (Instruction Execute)In this stage, ALU operations are performed.
Stage 4 (Memory Access)In this stage, memory operands are read and written from/to the memory that is present in the instruction.
Stage 5 (Write Back)In this stage, computed/fetched value is written back to the register present in the instructions.
Performance of a pipelined processorConsider a ‘k’ segment/stages pipeline with clock cycle time as ‘Tp’. Let there be ‘n’ tasks to be completed in the pipelined processor. So, time taken to execute ‘n’ instructions in a pipelined processor:
ETpipeline = k + n – 1 cycles
= (k + n – 1) Tp
In the same case, for a non-pipelined processor, execution time of ‘n’ instructions will be:
ETnon-pipeline = n * k * Tp
So, speedup (S) of the pipelined processor over non-pipelined processor, when ‘n’ tasks are executed on the same processor is:
S = Performance of pipelined processor /
Performance of Non-pipelined processor
As the performance of a processor is inversely proportional to the execution time, we have,
S = ETnon-pipeline / ETpipeline
=> S = [n * k * Tp] / [(k + n – 1) * Tp]
S = [n * k] / [k + n – 1]
When the number of tasks ‘n’ are significantly larger than k, that is, n >> k
S = n * k / n
S = k
where ‘k’ are the number of stages in the pipeline.
Also, Efficiency = Given speed up / Max speed up = S / SmaxWe know that, Smax = k
So, Efficiency = S / k
Throughput = Number of instructions / Total time to complete the instructions
So, Throughput = n / (k + n – 1) * Tp
Note: The cycles per instruction (CPI) value of an ideal pipelined processor is 1
Performance of pipeline with stallsSpeed Up (S) = CPInon-pipeline / (1 + Number of stalls per instruction)
Dependencies and Data Hazard
There are mainly three types of dependencies possible in a pipelined processor. These are :Structural dependency: This dependency arises due to the resource conflict in the pipeline. A resource conflict is a situation when more than one instruction tries to access the same resource in the same cycle. A resource can be a register, memory, or ALU.To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming.Control Dependency (Branch Hazards): This type of dependency occurs during the transfer of control instructions such as BRANCH, CALL, JMP, etc. On many instruction architectures, the processor will not know the target address of these instructions when it needs to insert the new instruction into the pipeline. Due to this, unwanted instructions are fed to the pipeline.Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken.For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty.Data Dependency (Data Hazard):Data hazards occur when instructions that exhibit data dependence, modify data in different stages of a pipeline. Hazard cause delays in the pipeline. There are mainly three types of data hazards:1) RAW (Read after Write) [Flow/True data dependency]2) WAR (Write after Read) [Anti-Data dependency]3) WAW (Write after Write) [Output data dependency]To minimize data dependency stalls in the pipeline, operand forwarding is used.In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly.
Structural dependency: This dependency arises due to the resource conflict in the pipeline. A resource conflict is a situation when more than one instruction tries to access the same resource in the same cycle. A resource can be a register, memory, or ALU.To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming.
To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming.
Control Dependency (Branch Hazards): This type of dependency occurs during the transfer of control instructions such as BRANCH, CALL, JMP, etc. On many instruction architectures, the processor will not know the target address of these instructions when it needs to insert the new instruction into the pipeline. Due to this, unwanted instructions are fed to the pipeline.Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken.For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty.
Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken.
For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty.
Data Dependency (Data Hazard):Data hazards occur when instructions that exhibit data dependence, modify data in different stages of a pipeline. Hazard cause delays in the pipeline. There are mainly three types of data hazards:1) RAW (Read after Write) [Flow/True data dependency]2) WAR (Write after Read) [Anti-Data dependency]3) WAW (Write after Write) [Output data dependency]To minimize data dependency stalls in the pipeline, operand forwarding is used.In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly.
To minimize data dependency stalls in the pipeline, operand forwarding is used.
In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly.
The input/output (I/O) architecture is computer system’s interface to the outside world. Each I/O module interfaces to the system bus and controls one or more peripheral devices.
There are three basic forms of input and output systems –Programmed I/O: In programmed I/O, the processor executes a program that gives its direct control of the I/O operation, including sensing device status, sending a read or write command, and transferring the data.Interrupt driven I/O: In interrupt driven I/O, the processor issues an I/O command, continues to execute other instructions, and is interrupted by the I/O module when the I/O module completes its work.Direct Memory Access(DMA): In Direct Memory Access (DMA), the I/O module and main memory exchange data directly without processor involvement.
Programmed I/O: In programmed I/O, the processor executes a program that gives its direct control of the I/O operation, including sensing device status, sending a read or write command, and transferring the data.
Interrupt driven I/O: In interrupt driven I/O, the processor issues an I/O command, continues to execute other instructions, and is interrupted by the I/O module when the I/O module completes its work.
Direct Memory Access(DMA): In Direct Memory Access (DMA), the I/O module and main memory exchange data directly without processor involvement.
There are several ways to represent floating point number but IEEE 754 is the most efficient in most cases. IEEE 754 has 3 basic components:
The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.The Normalised Mantisa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal.
The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.
The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.
The Normalised Mantisa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal.
(a) Status FlagsZero Flag (Z): When an arithmetic operation results in zero, the flip-flop called the Zero flag – which is set to one.Carry flag (CY): After an addition of two numbers, if the sum in the accumulator is larger than eight bits, then the flip-flop uses to indicate a carry called the Carry flag, which is set to one.Parity (P): If the result has an even number of 1s, the flag is set to 1; for an odd number of 1s the flag is reset.Auxiliary Carry (AC): In an arithmetic operation, when a carry is generated from lower nibble and passed on to higher nibble then this register is set to 1.Sign flag(S): It is a single bit in a system status (flag) register used to indicate whether the result of the last mathematical operation resulted in a value in which the most significant bit was set.
Zero Flag (Z): When an arithmetic operation results in zero, the flip-flop called the Zero flag – which is set to one.
Carry flag (CY): After an addition of two numbers, if the sum in the accumulator is larger than eight bits, then the flip-flop uses to indicate a carry called the Carry flag, which is set to one.
Parity (P): If the result has an even number of 1s, the flag is set to 1; for an odd number of 1s the flag is reset.
Auxiliary Carry (AC): In an arithmetic operation, when a carry is generated from lower nibble and passed on to higher nibble then this register is set to 1.
Sign flag(S): It is a single bit in a system status (flag) register used to indicate whether the result of the last mathematical operation resulted in a value in which the most significant bit was set.
(b) Control FlagsTrap Flag (TF): It sets to enable one step execution of program. This is used for debug purpose.Interrupt Flag (IF): It is used to enable or disable interrupt during execution.Direction Flag (DF): The direction flag is a flag that controls the left-to-right or right-to-left direction of string processing.
Trap Flag (TF): It sets to enable one step execution of program. This is used for debug purpose.
Interrupt Flag (IF): It is used to enable or disable interrupt during execution.
Direction Flag (DF): The direction flag is a flag that controls the left-to-right or right-to-left direction of string processing.
kk773572498
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Three address code in Compiler
Code Optimization in Compiler Design
Introduction of Process Synchronization
Structures of Directory in Operating System
Difference between DELETE, DROP and TRUNCATE
Mutual exclusion in distributed system
Phases of a Compiler
States of a Process in Operating Systems
Difference between Clustered and Non-clustered index
Directed Acyclic graph in Compiler Design (with examples)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 249,
"s": 54,
"text": "Control Unit –A control unit (CU) handles all processor control signals. It directs all input and output flow, fetches the code for instructions and controlling how data moves around the system."
},
{
"code": null,
"e": 430,
"s": 249,
"text": "A control unit (CU) handles all processor control signals. It directs all input and output flow, fetches the code for instructions and controlling how data moves around the system."
},
{
"code": null,
"e": 735,
"s": 430,
"text": "Arithmetic and Logic Unit (ALU) –The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation.Figure – Basic CPU structure, illustrating ALU"
},
{
"code": null,
"e": 961,
"s": 735,
"text": "The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons. It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation."
},
{
"code": null,
"e": 1762,
"s": 961,
"text": "Main Memory Unit (Registers) –Accumulator: Stores the results of calculations made by ALU.Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR."
},
{
"code": null,
"e": 2533,
"s": 1762,
"text": "Accumulator: Stores the results of calculations made by ALU.Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR."
},
{
"code": null,
"e": 2594,
"s": 2533,
"text": "Accumulator: Stores the results of calculations made by ALU."
},
{
"code": null,
"e": 2765,
"s": 2594,
"text": "Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR)."
},
{
"code": null,
"e": 2902,
"s": 2765,
"text": "Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory."
},
{
"code": null,
"e": 3038,
"s": 2902,
"text": "Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory."
},
{
"code": null,
"e": 3169,
"s": 3038,
"text": "Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed."
},
{
"code": null,
"e": 3309,
"s": 3169,
"text": "Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR."
},
{
"code": null,
"e": 3527,
"s": 3309,
"text": "Input/Output Devices – Program or data is read into main memory from the input device or secondary storage under the control of CPU input instruction. Output devices are used to output the information from a computer."
},
{
"code": null,
"e": 4036,
"s": 3527,
"text": "Buses – Data is transmitted from one part of a computer to another, connecting all major internal components to the CPU and memory, by the means of Buses. Types:Data Bus: It carries data among the memory unit, the I/O devices, and the processor.Address Bus: It carries the address of data (not the actual data) between memory and processor.Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer."
},
{
"code": null,
"e": 4384,
"s": 4036,
"text": "Data Bus: It carries data among the memory unit, the I/O devices, and the processor.Address Bus: It carries the address of data (not the actual data) between memory and processor.Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer."
},
{
"code": null,
"e": 4469,
"s": 4384,
"text": "Data Bus: It carries data among the memory unit, the I/O devices, and the processor."
},
{
"code": null,
"e": 4565,
"s": 4469,
"text": "Address Bus: It carries the address of data (not the actual data) between memory and processor."
},
{
"code": null,
"e": 4734,
"s": 4565,
"text": "Control Bus: It carries control commands from the CPU (and status signals from other devices) in order to control and coordinate all the activities within the computer."
},
{
"code": null,
"e": 4908,
"s": 4734,
"text": "A instruction is of various length depending upon the number of addresses it contain. Generally CPU organization are of three types on the basis of number of address fields:"
},
{
"code": null,
"e": 4987,
"s": 4908,
"text": "Single Accumulator organizationGeneral register organizationStack organization"
},
{
"code": null,
"e": 5019,
"s": 4987,
"text": "Single Accumulator organization"
},
{
"code": null,
"e": 5049,
"s": 5019,
"text": "General register organization"
},
{
"code": null,
"e": 5068,
"s": 5049,
"text": "Stack organization"
},
{
"code": null,
"e": 6041,
"s": 5068,
"text": "Zero Address Instructions –Address is stored in the opcode, in the zero address instruction. A stack based organization uses zero address instruction.One Address Instructions –This use a implied ACCUMULATOR register for data manipulation. One operand is in accumulator and other is in register or memory location. Implied means that the CPU already know that one operand is in accumulator so there is no need to specify it. i.e there will be one opcode field and one address field.Two Address Instructions –Here two address can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in accumulator here result can be stored at a different location rather than just accumulator, but require the number more of the bit to represent address.Three Address Instructions –This has three address field to specify a register or a memory location. The program created is much short in size but the number of bits per instruction increase."
},
{
"code": null,
"e": 6192,
"s": 6041,
"text": "Zero Address Instructions –Address is stored in the opcode, in the zero address instruction. A stack based organization uses zero address instruction."
},
{
"code": null,
"e": 6524,
"s": 6192,
"text": "One Address Instructions –This use a implied ACCUMULATOR register for data manipulation. One operand is in accumulator and other is in register or memory location. Implied means that the CPU already know that one operand is in accumulator so there is no need to specify it. i.e there will be one opcode field and one address field."
},
{
"code": null,
"e": 6825,
"s": 6524,
"text": "Two Address Instructions –Here two address can be specified in the instruction. Unlike earlier in one address instruction, the result was stored in accumulator here result can be stored at a different location rather than just accumulator, but require the number more of the bit to represent address."
},
{
"code": null,
"e": 7017,
"s": 6825,
"text": "Three Address Instructions –This has three address field to specify a register or a memory location. The program created is much short in size but the number of bits per instruction increase."
},
{
"code": null,
"e": 7259,
"s": 7017,
"text": "The term addressing modes refers to the way in which the operand of an instruction is specified. The addressing mode specifies a rule for interpreting or modifying the address field of the instruction before the operand is actually executed."
},
{
"code": null,
"e": 7322,
"s": 7259,
"text": "An assembly language program instruction consists of two parts"
},
{
"code": null,
"e": 7338,
"s": 7322,
"text": "IMPORTANT TERMS"
},
{
"code": null,
"e": 7374,
"s": 7338,
"text": "Starting address of memory segment."
},
{
"code": null,
"e": 7674,
"s": 7374,
"text": "Effective address or Offset: An offset is determined by adding any combination of three address elements: displacement, base and index.Displacement: It is an 8 bit or 16 bit immediate value given in the instruction.Base: Contents of base register, BX or BP.Index: Content of index register SI or DI."
},
{
"code": null,
"e": 7755,
"s": 7674,
"text": "Displacement: It is an 8 bit or 16 bit immediate value given in the instruction."
},
{
"code": null,
"e": 7798,
"s": 7755,
"text": "Base: Contents of base register, BX or BP."
},
{
"code": null,
"e": 7841,
"s": 7798,
"text": "Index: Content of index register SI or DI."
},
{
"code": null,
"e": 8082,
"s": 7841,
"text": "Implied mode:: In implied addressing the operand is specified in the instruction itself. In this mode the data is 8 bits or 16 bits long and data is the part of instruction.Zero address instruction are designed with implied addressing mode."
},
{
"code": null,
"e": 8336,
"s": 8082,
"text": "Immediate addressing mode (symbol #):In this mode data is present in address field of instruction .Designed like one address instruction format.Note:Limitation in the immediate mode is that the range of constants are restricted by size of address field."
},
{
"code": null,
"e": 8574,
"s": 8336,
"text": "Register mode: In register addressing the operand is placed in one of 8 bit or 16 bit general purpose registers. The data is in the register that is specified by the instruction.Here one register reference is required to access the data."
},
{
"code": null,
"e": 8900,
"s": 8574,
"text": "Register Indirect mode: In this addressing the operand’s offset is placed in any one of the registers BX, BP, SI, DI as specified in the instruction. The effective address of the data is in the base register or an index register that is specified by the instruction.Here two register reference is required to access the data."
},
{
"code": null,
"e": 9273,
"s": 8900,
"text": "Auto Indexed (increment mode): Effective address of the operand is the contents of a register specified in the instruction. After accessing the operand, the contents of this register are automatically incremented to point to the next consecutive memory location.(R1)+.Here one register reference, one memory reference, and one ALU operation is required to access the data."
},
{
"code": null,
"e": 9651,
"s": 9273,
"text": "Auto indexed ( decrement mode): Effective address of the operand is the contents of a register specified in the instruction. Before accessing the operand, the contents of this register are automatically decremented to point to the previous consecutive memory location. –(R1)Here one register reference, one memory reference and one ALU operation is required to access the data."
},
{
"code": null,
"e": 9876,
"s": 9651,
"text": "Auto decrement mode is the same as the auto-increment mode. Both can also be used to implement a stack as push and pop. Auto increment and Auto-decrement modes are useful for implementing “Last-In-First-Out” data structures."
},
{
"code": null,
"e": 10193,
"s": 9876,
"text": "Direct addressing/ Absolute addressing Mode (symbol [ ]): The operand’s offset is given in the instruction as an 8 bit or 16 bit displacement element. In this addressing mode, the 16-bit effective address of the data is part of the instruction.Here only one memory reference operation is required to access the data."
},
{
"code": null,
"e": 10429,
"s": 10193,
"text": "Indirect addressing Mode (symbol @ or () ):In this mode address field of instruction contains the address of effective address.Here two references are required.1st reference to get an effective address.2nd reference to access the data."
},
{
"code": null,
"e": 10568,
"s": 10429,
"text": "Indexed addressing mode: The operand’s offset is the sum of the content of an index register SI or DI and an 8 bit or 16-bit displacement."
},
{
"code": null,
"e": 10697,
"s": 10568,
"text": "Based Indexed Addressing: The operand’s offset is sum of the content of a base register BX or BP and an index register SI or DI."
},
{
"code": null,
"e": 10749,
"s": 10697,
"text": "Based on Transfer of control, addressing modes are:"
},
{
"code": null,
"e": 10988,
"s": 10749,
"text": "PC relative addressing mode: PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.EA= PC + Address field value\nPC= PC + Relative value."
},
{
"code": null,
"e": 11042,
"s": 10988,
"text": "EA= PC + Address field value\nPC= PC + Relative value."
},
{
"code": null,
"e": 11520,
"s": 11042,
"text": "Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control.In this mode effective address is obtained by adding base register value to address field value.EA= Base register + Address field value.\nPC= Base register + Relative value.\nNote:PC relative and based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes."
},
{
"code": null,
"e": 11598,
"s": 11520,
"text": "EA= Base register + Address field value.\nPC= Base register + Relative value.\n"
},
{
"code": null,
"e": 11604,
"s": 11598,
"text": "Note:"
},
{
"code": null,
"e": 11789,
"s": 11604,
"text": "PC relative and based register both addressing modes are suitable for program relocation at runtime.Based register addressing mode is best suitable to write position independent codes."
},
{
"code": null,
"e": 11890,
"s": 11789,
"text": "PC relative and based register both addressing modes are suitable for program relocation at runtime."
},
{
"code": null,
"e": 11975,
"s": 11890,
"text": "Based register addressing mode is best suitable to write position independent codes."
},
{
"code": null,
"e": 12252,
"s": 11975,
"text": "Characteristic of RISC –Simpler instruction, hence simple instruction decoding.Instruction come under size of one word.Instruction take single clock cycle to get executed.More number of general purpose register.Simple Addressing Modes.Less Data types.Pipeling can be achieved."
},
{
"code": null,
"e": 12308,
"s": 12252,
"text": "Simpler instruction, hence simple instruction decoding."
},
{
"code": null,
"e": 12349,
"s": 12308,
"text": "Instruction come under size of one word."
},
{
"code": null,
"e": 12402,
"s": 12349,
"text": "Instruction take single clock cycle to get executed."
},
{
"code": null,
"e": 12443,
"s": 12402,
"text": "More number of general purpose register."
},
{
"code": null,
"e": 12468,
"s": 12443,
"text": "Simple Addressing Modes."
},
{
"code": null,
"e": 12485,
"s": 12468,
"text": "Less Data types."
},
{
"code": null,
"e": 12511,
"s": 12485,
"text": "Pipeling can be achieved."
},
{
"code": null,
"e": 12825,
"s": 12511,
"text": "Characteristic of CISC –Complex instruction, hence complex instruction decoding.Instruction are larger than one word size.Instruction may take more than single clock cycle to get executed.Less number of general purpose register as operation get performed in memory itself.Complex Addressing Modes.More Data types."
},
{
"code": null,
"e": 12882,
"s": 12825,
"text": "Complex instruction, hence complex instruction decoding."
},
{
"code": null,
"e": 12925,
"s": 12882,
"text": "Instruction are larger than one word size."
},
{
"code": null,
"e": 12992,
"s": 12925,
"text": "Instruction may take more than single clock cycle to get executed."
},
{
"code": null,
"e": 13077,
"s": 12992,
"text": "Less number of general purpose register as operation get performed in memory itself."
},
{
"code": null,
"e": 13103,
"s": 13077,
"text": "Complex Addressing Modes."
},
{
"code": null,
"e": 13120,
"s": 13103,
"text": "More Data types."
},
{
"code": null,
"e": 13145,
"s": 13120,
"text": "Hardwired Control Unit –"
},
{
"code": null,
"e": 13260,
"s": 13145,
"text": "Fixed logic circuits that correspond directly to the Boolean expressions are used to generate the control signals."
},
{
"code": null,
"e": 13319,
"s": 13260,
"text": "Hardwired control is faster than micro-programmed control."
},
{
"code": null,
"e": 13383,
"s": 13319,
"text": "A controller that uses this approach can operate at high speed."
},
{
"code": null,
"e": 13437,
"s": 13383,
"text": "RISC architecture is based on hardwired control unit."
},
{
"code": null,
"e": 13568,
"s": 13437,
"text": "The control signals associated with operations are stored in special memory units inaccessible by the programmer as Control Words."
},
{
"code": null,
"e": 13653,
"s": 13568,
"text": "Control signals are generated by a program are similar to machine language programs."
},
{
"code": null,
"e": 13783,
"s": 13653,
"text": "Micro-programmed control unit is slower in speed because of the time it takes to fetch microinstructions from the control memory."
},
{
"code": null,
"e": 14112,
"s": 13783,
"text": "There are two type Micro-programmed control Unit:Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS.Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required."
},
{
"code": null,
"e": 14441,
"s": 14112,
"text": "There are two type Micro-programmed control Unit:Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS.Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required."
},
{
"code": null,
"e": 14566,
"s": 14441,
"text": "Horizontal Micro-programmed control Unit- The control signals are represented in the decoded binary format that is 1 bit/CS."
},
{
"code": null,
"e": 14722,
"s": 14566,
"text": "Vertical Micro-programmed control Unit – The control signals re represented in the encoded binary format. For N control signals- Logn(N) bits are required."
},
{
"code": null,
"e": 14768,
"s": 14722,
"text": "Registers Involved In Each Instruction Cycle:"
},
{
"code": null,
"e": 14922,
"s": 14768,
"text": "Memory address registers(MAR) : It is connected to the address lines of the system bus. It specifies the address in memory for a read or write operation."
},
{
"code": null,
"e": 15090,
"s": 14922,
"text": "Memory Buffer Register(MBR) : It is connected to the data lines of the system bus. It contains the value to be stored in memory or the last value read from the memory."
},
{
"code": null,
"e": 15169,
"s": 15090,
"text": "Program Counter(PC) : Holds the address of the next instruction to be fetched."
},
{
"code": null,
"e": 15232,
"s": 15169,
"text": "Instruction Register(IR) : Holds the last instruction fetched."
},
{
"code": null,
"e": 15437,
"s": 15232,
"text": "The Indirect Cycle is always followed by the Execute Cycle. The Interrupt Cycle is always followed by the Fetch Cycle. For both fetch and execute cycles, the next cycle depends on the state of the system."
},
{
"code": null,
"e": 16619,
"s": 15437,
"text": "The Fetch Cycle –At the beginning of the fetch cycle, the address of the next instruction to be executed is in the Program Counter(PC).The Indirect Cycles –Once an instruction is fetched, the next step is to fetch source operands. Source Operand is being fetched by indirect addressing it can be fetched by any addressing mode, here its done by indirect addressing). Register-based operands need not be fetched. Once the opcode is executed, a similar process may be needed to store the result in the main memory.The Execute CycleThe other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur.The Interrupt Cycle:At the completion of the Execute Cycle, a test is made to determine whether any enabled interrupt has occurred or not. If an enabled interrupt has occurred then Interrupt Cycle occurs. The nature of this cycle varies greatly from one machine to another."
},
{
"code": null,
"e": 16755,
"s": 16619,
"text": "The Fetch Cycle –At the beginning of the fetch cycle, the address of the next instruction to be executed is in the Program Counter(PC)."
},
{
"code": null,
"e": 17133,
"s": 16755,
"text": "The Indirect Cycles –Once an instruction is fetched, the next step is to fetch source operands. Source Operand is being fetched by indirect addressing it can be fetched by any addressing mode, here its done by indirect addressing). Register-based operands need not be fetched. Once the opcode is executed, a similar process may be needed to store the result in the main memory."
},
{
"code": null,
"e": 17530,
"s": 17133,
"text": "The Execute CycleThe other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur."
},
{
"code": null,
"e": 17910,
"s": 17530,
"text": "The other three cycles(Fetch, Indirect and Interrupt) are simple and predictable. Each of them requires a simple, small and fixed sequence of micro-operations. In each case, the same micro-operation is repeated each time around. Execute Cycle is different from them. Like, for a machine with N different opcodes there are N different sequences of micro-operations that can occur."
},
{
"code": null,
"e": 18184,
"s": 17910,
"text": "The Interrupt Cycle:At the completion of the Execute Cycle, a test is made to determine whether any enabled interrupt has occurred or not. If an enabled interrupt has occurred then Interrupt Cycle occurs. The nature of this cycle varies greatly from one machine to another."
},
{
"code": null,
"e": 18637,
"s": 18184,
"text": "Microprogram: Program stored in memory that generates all control signals required to execute the instruction set correctly, it consists micro-instructions.Micro-instruction: Contains a sequencing word and a control word. The control word is all control information required for one clock cycle.Micro-operations: Micro-operations are the atomic operations which executes a particular micro-instruction.Example of micro-operation during the fetch cycle:"
},
{
"code": null,
"e": 18699,
"s": 18637,
"text": "t1: MAR ←(PC)\nt2: MBR ←Memory\n PC ←(PC) + I\nt3: IR ←(MBR)\n"
},
{
"code": null,
"e": 18949,
"s": 18699,
"text": "Memories are made up of registers. Each register in the memory is one storage location. The storage location is also called a memory location. Memory locations are identified using Address. The total number of bit a memory can store is its capacity."
},
{
"code": null,
"e": 19357,
"s": 18949,
"text": "Simultaneous access memory organization: If H1 and H2 are the Hit Ratios and T1 and T2 are the access time of L1 and L2 memory levels respectively then theAverage Memory Access Time can be calculated as:Hierarchical Access Memory Organizations: If H1 and H2 are the Hit Ratios and T1 and T2 are the access time of L1 and L2 memory levels respectively then theAverage Memory Access Time can be calculated as:"
},
{
"code": null,
"e": 19585,
"s": 19357,
"text": "Cache Memory is a special very high-speed memory. It is used to speed up and synchronizing with high-speed CPU.Levels of memory: Level 1 or Register, Level 2 or Cache memory, Level 3 or Main Memory, Level 4 or Secondary Memory."
},
{
"code": null,
"e": 19646,
"s": 19585,
"text": "Hit ratio = hit / (hit + miss) = no. of hits/total accesses"
},
{
"code": null,
"e": 19661,
"s": 19646,
"text": "Cache Mapping:"
},
{
"code": null,
"e": 20686,
"s": 19661,
"text": "There are three different types of mapping used for the purpose of cache memory which is as follows: Direct mapping, Associative mapping, and Set-Associative mapping.Direct Mapping –Maps each block of main memory into only one possible cache line. If a line is previously taken up by a memory block and a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory.Associative Mapping –A block of main memory can map to any line of the cache that is freely available at that moment. The word offset bits are used to identify which word in the block is needed, all of the remaining bits become Tag.Set-Associative Mapping –Cache lines are grouped into sets where each set contains k number of lines and a particular block of main memory can map to only one particular set of the cache. However, within that set, the memory block can map to any freely available cache line."
},
{
"code": null,
"e": 21039,
"s": 20686,
"text": "Direct Mapping –Maps each block of main memory into only one possible cache line. If a line is previously taken up by a memory block and a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory."
},
{
"code": null,
"e": 21272,
"s": 21039,
"text": "Associative Mapping –A block of main memory can map to any line of the cache that is freely available at that moment. The word offset bits are used to identify which word in the block is needed, all of the remaining bits become Tag."
},
{
"code": null,
"e": 21547,
"s": 21272,
"text": "Set-Associative Mapping –Cache lines are grouped into sets where each set contains k number of lines and a particular block of main memory can map to only one particular set of the cache. However, within that set, the memory block can map to any freely available cache line."
},
{
"code": null,
"e": 21829,
"s": 21547,
"text": "Note: Translation Lookaside Buffer (i.e. TLB) is required only if Virtual Memory is used by a processor. In short, TLB speeds up the translation of virtual address to a physical address by storing page-table in faster memory. In fact, TLB also sits between the CPU and Main memory."
},
{
"code": null,
"e": 22079,
"s": 21829,
"text": "Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in the cache is decided based on the locality of reference.Types of Locality of reference"
},
{
"code": null,
"e": 22495,
"s": 22079,
"text": "Spatial Locality of referenceSpatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future.Temporal Locality of referenceTemporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory to avoid searching again in main memory for the same data."
},
{
"code": null,
"e": 22665,
"s": 22495,
"text": "Spatial Locality of referenceSpatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future."
},
{
"code": null,
"e": 22912,
"s": 22665,
"text": "Temporal Locality of referenceTemporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory to avoid searching again in main memory for the same data."
},
{
"code": null,
"e": 23414,
"s": 22912,
"text": "Write PolicyWrite Through: In this technique, all write operations are made to main memory as well as to the cache, ensuring that main memory is always valid.For hierarchical access:For simultaneous access :Write Back: In write-back updates are made only in the cache. When an update occurs, a dirty bit, or use bit, associated with the line is set. Then, when a block is replaced, it is written back to main memory if and only if the dirty bit is set.For hierarchical access:For simultaneous access :"
},
{
"code": null,
"e": 23610,
"s": 23414,
"text": "Write Through: In this technique, all write operations are made to main memory as well as to the cache, ensuring that main memory is always valid.For hierarchical access:For simultaneous access :"
},
{
"code": null,
"e": 23636,
"s": 23610,
"text": "For simultaneous access :"
},
{
"code": null,
"e": 23931,
"s": 23636,
"text": "Write Back: In write-back updates are made only in the cache. When an update occurs, a dirty bit, or use bit, associated with the line is set. Then, when a block is replaced, it is written back to main memory if and only if the dirty bit is set.For hierarchical access:For simultaneous access :"
},
{
"code": null,
"e": 23957,
"s": 23931,
"text": "For simultaneous access :"
},
{
"code": null,
"e": 24352,
"s": 23957,
"text": "Pipelining is a process of arrangement of hardware elements of the CPU such that its overall performance is increased. Simultaneous execution of more than one instruction takes place in a pipelined processor.RISC processor has 5 stage instruction pipeline to execute all the instructions in the RISC instruction set. Following are the 5 stages of RISC pipeline with their respective operations:"
},
{
"code": null,
"e": 24498,
"s": 24352,
"text": "Stage 1 (Instruction Fetch)In this stage the CPU reads instructions from the address in the memory whose value is present in the program counter."
},
{
"code": null,
"e": 24660,
"s": 24498,
"text": "Stage 2 (Instruction Decode)In this stage, instruction is decoded and the register file is accessed to get the values from the registers used in the instruction."
},
{
"code": null,
"e": 24734,
"s": 24660,
"text": "Stage 3 (Instruction Execute)In this stage, ALU operations are performed."
},
{
"code": null,
"e": 24864,
"s": 24734,
"text": "Stage 4 (Memory Access)In this stage, memory operands are read and written from/to the memory that is present in the instruction."
},
{
"code": null,
"e": 24983,
"s": 24864,
"text": "Stage 5 (Write Back)In this stage, computed/fetched value is written back to the register present in the instructions."
},
{
"code": null,
"e": 25225,
"s": 24983,
"text": "Performance of a pipelined processorConsider a ‘k’ segment/stages pipeline with clock cycle time as ‘Tp’. Let there be ‘n’ tasks to be completed in the pipelined processor. So, time taken to execute ‘n’ instructions in a pipelined processor:"
},
{
"code": null,
"e": 25324,
"s": 25225,
"text": " ETpipeline = k + n – 1 cycles\n = (k + n – 1) Tp\n"
},
{
"code": null,
"e": 25417,
"s": 25324,
"text": "In the same case, for a non-pipelined processor, execution time of ‘n’ instructions will be:"
},
{
"code": null,
"e": 25466,
"s": 25417,
"text": " ETnon-pipeline = n * k * Tp\n"
},
{
"code": null,
"e": 25593,
"s": 25466,
"text": "So, speedup (S) of the pipelined processor over non-pipelined processor, when ‘n’ tasks are executed on the same processor is:"
},
{
"code": null,
"e": 25686,
"s": 25593,
"text": " S = Performance of pipelined processor /\n Performance of Non-pipelined processor\n"
},
{
"code": null,
"e": 25778,
"s": 25686,
"text": "As the performance of a processor is inversely proportional to the execution time, we have,"
},
{
"code": null,
"e": 25893,
"s": 25778,
"text": " S = ETnon-pipeline / ETpipeline\n => S = [n * k * Tp] / [(k + n – 1) * Tp]\n S = [n * k] / [k + n – 1]\n"
},
{
"code": null,
"e": 25971,
"s": 25893,
"text": "When the number of tasks ‘n’ are significantly larger than k, that is, n >> k"
},
{
"code": null,
"e": 26000,
"s": 25971,
"text": " S = n * k / n\n S = k\n"
},
{
"code": null,
"e": 26052,
"s": 26000,
"text": "where ‘k’ are the number of stages in the pipeline."
},
{
"code": null,
"e": 26134,
"s": 26052,
"text": "Also, Efficiency = Given speed up / Max speed up = S / SmaxWe know that, Smax = k"
},
{
"code": null,
"e": 26157,
"s": 26134,
"text": "So, Efficiency = S / k"
},
{
"code": null,
"e": 26235,
"s": 26157,
"text": "Throughput = Number of instructions / Total time to complete the instructions"
},
{
"code": null,
"e": 26273,
"s": 26235,
"text": "So, Throughput = n / (k + n – 1) * Tp"
},
{
"code": null,
"e": 26355,
"s": 26273,
"text": "Note: The cycles per instruction (CPI) value of an ideal pipelined processor is 1"
},
{
"code": null,
"e": 26462,
"s": 26355,
"text": "Performance of pipeline with stallsSpeed Up (S) = CPInon-pipeline / (1 + Number of stalls per instruction)"
},
{
"code": null,
"e": 26491,
"s": 26462,
"text": "Dependencies and Data Hazard"
},
{
"code": null,
"e": 28297,
"s": 26491,
"text": "There are mainly three types of dependencies possible in a pipelined processor. These are :Structural dependency: This dependency arises due to the resource conflict in the pipeline. A resource conflict is a situation when more than one instruction tries to access the same resource in the same cycle. A resource can be a register, memory, or ALU.To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming.Control Dependency (Branch Hazards): This type of dependency occurs during the transfer of control instructions such as BRANCH, CALL, JMP, etc. On many instruction architectures, the processor will not know the target address of these instructions when it needs to insert the new instruction into the pipeline. Due to this, unwanted instructions are fed to the pipeline.Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken.For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty.Data Dependency (Data Hazard):Data hazards occur when instructions that exhibit data dependence, modify data in different stages of a pipeline. Hazard cause delays in the pipeline. There are mainly three types of data hazards:1) RAW (Read after Write) [Flow/True data dependency]2) WAR (Write after Read) [Anti-Data dependency]3) WAW (Write after Write) [Output data dependency]To minimize data dependency stalls in the pipeline, operand forwarding is used.In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly."
},
{
"code": null,
"e": 28656,
"s": 28297,
"text": "Structural dependency: This dependency arises due to the resource conflict in the pipeline. A resource conflict is a situation when more than one instruction tries to access the same resource in the same cycle. A resource can be a register, memory, or ALU.To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming."
},
{
"code": null,
"e": 28759,
"s": 28656,
"text": "To minimize structural dependency stalls in the pipeline, we use a hardware mechanism called Renaming."
},
{
"code": null,
"e": 29462,
"s": 28759,
"text": "Control Dependency (Branch Hazards): This type of dependency occurs during the transfer of control instructions such as BRANCH, CALL, JMP, etc. On many instruction architectures, the processor will not know the target address of these instructions when it needs to insert the new instruction into the pipeline. Due to this, unwanted instructions are fed to the pipeline.Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken.For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty."
},
{
"code": null,
"e": 29634,
"s": 29462,
"text": "Branch Prediction is the method through which stalls due to control dependency can be eliminated. In this at 1st stage prediction is done about which branch will be taken."
},
{
"code": null,
"e": 29796,
"s": 29634,
"text": "For branch prediction Branch penalty is zero. The number of stalls introduced during the branch operations in the pipelined processor is known as branch penalty."
},
{
"code": null,
"e": 30451,
"s": 29796,
"text": "Data Dependency (Data Hazard):Data hazards occur when instructions that exhibit data dependence, modify data in different stages of a pipeline. Hazard cause delays in the pipeline. There are mainly three types of data hazards:1) RAW (Read after Write) [Flow/True data dependency]2) WAR (Write after Read) [Anti-Data dependency]3) WAW (Write after Write) [Output data dependency]To minimize data dependency stalls in the pipeline, operand forwarding is used.In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly."
},
{
"code": null,
"e": 30531,
"s": 30451,
"text": "To minimize data dependency stalls in the pipeline, operand forwarding is used."
},
{
"code": null,
"e": 30729,
"s": 30531,
"text": "In operand forwarding, we use the interface registers present between the stages to hold intermediate output so that dependent instruction can access new value from the interface register directly."
},
{
"code": null,
"e": 30908,
"s": 30729,
"text": "The input/output (I/O) architecture is computer system’s interface to the outside world. Each I/O module interfaces to the system bus and controls one or more peripheral devices."
},
{
"code": null,
"e": 31521,
"s": 30908,
"text": "There are three basic forms of input and output systems –Programmed I/O: In programmed I/O, the processor executes a program that gives its direct control of the I/O operation, including sensing device status, sending a read or write command, and transferring the data.Interrupt driven I/O: In interrupt driven I/O, the processor issues an I/O command, continues to execute other instructions, and is interrupted by the I/O module when the I/O module completes its work.Direct Memory Access(DMA): In Direct Memory Access (DMA), the I/O module and main memory exchange data directly without processor involvement."
},
{
"code": null,
"e": 31734,
"s": 31521,
"text": "Programmed I/O: In programmed I/O, the processor executes a program that gives its direct control of the I/O operation, including sensing device status, sending a read or write command, and transferring the data."
},
{
"code": null,
"e": 31936,
"s": 31734,
"text": "Interrupt driven I/O: In interrupt driven I/O, the processor issues an I/O command, continues to execute other instructions, and is interrupted by the I/O module when the I/O module completes its work."
},
{
"code": null,
"e": 32079,
"s": 31936,
"text": "Direct Memory Access(DMA): In Direct Memory Access (DMA), the I/O module and main memory exchange data directly without processor involvement."
},
{
"code": null,
"e": 32220,
"s": 32079,
"text": "There are several ways to represent floating point number but IEEE 754 is the most efficient in most cases. IEEE 754 has 3 basic components:"
},
{
"code": null,
"e": 32777,
"s": 32220,
"text": "The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.The Normalised Mantisa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal."
},
{
"code": null,
"e": 32899,
"s": 32777,
"text": "The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number."
},
{
"code": null,
"e": 33072,
"s": 32899,
"text": "The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent."
},
{
"code": null,
"e": 33336,
"s": 33072,
"text": "The Normalised Mantisa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal."
},
{
"code": null,
"e": 34139,
"s": 33336,
"text": "(a) Status FlagsZero Flag (Z): When an arithmetic operation results in zero, the flip-flop called the Zero flag – which is set to one.Carry flag (CY): After an addition of two numbers, if the sum in the accumulator is larger than eight bits, then the flip-flop uses to indicate a carry called the Carry flag, which is set to one.Parity (P): If the result has an even number of 1s, the flag is set to 1; for an odd number of 1s the flag is reset.Auxiliary Carry (AC): In an arithmetic operation, when a carry is generated from lower nibble and passed on to higher nibble then this register is set to 1.Sign flag(S): It is a single bit in a system status (flag) register used to indicate whether the result of the last mathematical operation resulted in a value in which the most significant bit was set."
},
{
"code": null,
"e": 34258,
"s": 34139,
"text": "Zero Flag (Z): When an arithmetic operation results in zero, the flip-flop called the Zero flag – which is set to one."
},
{
"code": null,
"e": 34454,
"s": 34258,
"text": "Carry flag (CY): After an addition of two numbers, if the sum in the accumulator is larger than eight bits, then the flip-flop uses to indicate a carry called the Carry flag, which is set to one."
},
{
"code": null,
"e": 34571,
"s": 34454,
"text": "Parity (P): If the result has an even number of 1s, the flag is set to 1; for an odd number of 1s the flag is reset."
},
{
"code": null,
"e": 34728,
"s": 34571,
"text": "Auxiliary Carry (AC): In an arithmetic operation, when a carry is generated from lower nibble and passed on to higher nibble then this register is set to 1."
},
{
"code": null,
"e": 34930,
"s": 34728,
"text": "Sign flag(S): It is a single bit in a system status (flag) register used to indicate whether the result of the last mathematical operation resulted in a value in which the most significant bit was set."
},
{
"code": null,
"e": 35254,
"s": 34930,
"text": "(b) Control FlagsTrap Flag (TF): It sets to enable one step execution of program. This is used for debug purpose.Interrupt Flag (IF): It is used to enable or disable interrupt during execution.Direction Flag (DF): The direction flag is a flag that controls the left-to-right or right-to-left direction of string processing."
},
{
"code": null,
"e": 35351,
"s": 35254,
"text": "Trap Flag (TF): It sets to enable one step execution of program. This is used for debug purpose."
},
{
"code": null,
"e": 35432,
"s": 35351,
"text": "Interrupt Flag (IF): It is used to enable or disable interrupt during execution."
},
{
"code": null,
"e": 35563,
"s": 35432,
"text": "Direction Flag (DF): The direction flag is a flag that controls the left-to-right or right-to-left direction of string processing."
},
{
"code": null,
"e": 35575,
"s": 35563,
"text": "kk773572498"
},
{
"code": null,
"e": 35583,
"s": 35575,
"text": "GATE CS"
},
{
"code": null,
"e": 35681,
"s": 35583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35712,
"s": 35681,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 35749,
"s": 35712,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 35789,
"s": 35749,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 35833,
"s": 35789,
"text": "Structures of Directory in Operating System"
},
{
"code": null,
"e": 35878,
"s": 35833,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 35917,
"s": 35878,
"text": "Mutual exclusion in distributed system"
},
{
"code": null,
"e": 35938,
"s": 35917,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 35979,
"s": 35938,
"text": "States of a Process in Operating Systems"
},
{
"code": null,
"e": 36032,
"s": 35979,
"text": "Difference between Clustered and Non-clustered index"
}
] |
Newton’s Divided Difference Interpolation Formula
|
28 Jan, 2022
Interpolation is an estimation of a value within two known values in a sequence of values.
Newton’s divided difference interpolation formula is a interpolation technique used when the interval difference is not same for all sequence of values.
Suppose f(x0), f(x1), f(x2).........f(xn) be the (n+1) values of the function y=f(x) corresponding to the arguments x=x0, x1, x2...xn, where interval differences are not sameThen the first divided difference is given by
The second divided difference is given by
and so on...Divided differences are symmetric with respect to the arguments i.e independent of the order of arguments.so, f[x0, x1]=f[x1, x0]f[x0, x1, x2]=f[x2, x1, x0]=f[x1, x2, x0]By using first divided difference, second divided difference as so on .A table is formed which is called the divided difference table.
Divided difference table:
Advantages of NEWTON’S DIVIDED DIFFERENCE INTERPOLATION FORMULA
These are useful for interpolation.
Through difference table, we can find out the differences in higher order.
Differences at each stage in each of the columns are easily measured by subtracting the previous value from its immediately succeeding value.
The differences are found out successively between the two adjacent values of the y variable till the ultimate difference vanishes or become a constant.
NEWTON’S DIVIDED DIFFERENCE INTERPOLATION FORMULA
Input : Value at 7
Output :
Value at 7 is 13.47
Below is the implementation for Newton’s divided difference interpolation method.
C++
Java
Python3
C#
PHP
// CPP program for implementing// Newton divided difference formula#include <bits/stdc++.h>using namespace std; // Function to find the product termfloat proterm(int i, float value, float x[]){ float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro;} // Function for calculating// divided difference tablevoid dividedDiffTable(float x[], float y[][10], int n){ for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j][i] = (y[j][i - 1] - y[j + 1] [i - 1]) / (x[j] - x[i + j]); } }} // Function for applying Newton's// divided difference formulafloat applyFormula(float value, float x[], float y[][10], int n){ float sum = y[0][0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0][i]); } return sum;} // Function for displaying // divided difference tablevoid printDiffTable(float y[][10],int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { cout << setprecision(4) << y[i][j] << "\t "; } cout << "\n"; }} // Driver Functionint main(){ // number of inputs given int n = 4; float value, sum, y[10][10]; float x[] = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value cout << "\nValue at " << value << " is " << applyFormula(value, x, y, n) << endl; return 0;}
// Java program for implementing// Newton divided difference formulaimport java.text.*;import java.math.*; class GFG{// Function to find the product termstatic float proterm(int i, float value, float x[]){ float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro;} // Function for calculating// divided difference tablestatic void dividedDiffTable(float x[], float y[][], int n){ for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j][i] = (y[j][i - 1] - y[j + 1] [i - 1]) / (x[j] - x[i + j]); } }} // Function for applying Newton's// divided difference formulastatic float applyFormula(float value, float x[], float y[][], int n){ float sum = y[0][0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0][i]); } return sum;} // Function for displaying // divided difference tablestatic void printDiffTable(float y[][],int n){ DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.HALF_UP); for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { String str1 = df.format(y[i][j]); System.out.print(str1+"\t "); } System.out.println(""); }} // Driver Functionpublic static void main(String[] args){ // number of inputs given int n = 4; float value, sum; float y[][]=new float[10][10]; float x[] = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.HALF_UP); System.out.println("\nValue at "+df.format(value)+" is " +df.format(applyFormula(value, x, y, n)));}}// This code is contributed by mits
# Python3 program for implementing # Newton divided difference formula # Function to find the product term def proterm(i, value, x): pro = 1; for j in range(i): pro = pro * (value - x[j]); return pro; # Function for calculating # divided difference table def dividedDiffTable(x, y, n): for i in range(1, n): for j in range(n - i): y[j][i] = ((y[j][i - 1] - y[j + 1][i - 1]) / (x[j] - x[i + j])); return y; # Function for applying Newton's # divided difference formula def applyFormula(value, x, y, n): sum = y[0][0]; for i in range(1, n): sum = sum + (proterm(i, value, x) * y[0][i]); return sum; # Function for displaying divided # difference table def printDiffTable(y, n): for i in range(n): for j in range(n - i): print(round(y[i][j], 4), "\t", end = " "); print(""); # Driver Code # number of inputs given n = 4; y = [[0 for i in range(10)] for j in range(10)]; x = [ 5, 6, 9, 11 ]; # y[][] is used for divided difference # table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; # calculating divided difference table y=dividedDiffTable(x, y, n); # displaying divided difference table printDiffTable(y, n); # value to be interpolated value = 7; # printing the value print("\nValue at", value, "is", round(applyFormula(value, x, y, n), 2)) # This code is contributed by mits
// C# program for implementing // Newton divided difference formula using System; class GFG{ // Function to find the product term static float proterm(int i, float value, float[] x) { float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro; } // Function for calculating // divided difference table static void dividedDiffTable(float[] x, float[,] y, int n) { for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j,i] = (y[j,i - 1] - y[j + 1,i - 1]) / (x[j] - x[i + j]); } } } // Function for applying Newton's // divided difference formula static float applyFormula(float value, float[] x, float[,] y, int n) { float sum = y[0,0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0,i]); } return sum; } // Function for displaying // divided difference table static void printDiffTable(float[,] y,int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { Console.Write(Math.Round(y[i,j],4)+"\t "); } Console.WriteLine(""); } } // Driver Function public static void Main() { // number of inputs given int n = 4; float value; float[,] y=new float[10,10]; float[] x = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0,0] = 12; y[1,0] = 13; y[2,0] = 14; y[3,0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value Console.WriteLine("\nValue at "+(value)+" is " +Math.Round(applyFormula(value, x, y, n),2)); } } // This code is contributed by mits
<?php// PHP program for implementing // Newton divided difference formula // Function to find the product term function proterm($i, $value, $x) { $pro = 1; for ($j = 0; $j < $i; $j++) { $pro = $pro * ($value - $x[$j]); } return $pro; } // Function for calculating // divided difference table function dividedDiffTable($x, &$y, $n) { for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $n - $i; $j++) { $y[$j][$i] = ($y[$j][$i - 1] - $y[$j + 1][$i - 1]) / ($x[$j] - $x[$i + $j]); } } } // Function for applying Newton's // divided difference formula function applyFormula($value, $x, $y,$n) { $sum = $y[0][0]; for ($i = 1; $i < $n; $i++) { $sum = $sum + (proterm($i, $value, $x) * $y[0][$i]); } return $sum; } // Function for displaying // divided difference table function printDiffTable($y, $n) { for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n - $i; $j++) { echo round($y[$i][$j], 4) . "\t "; } echo "\n"; } } // Driver Code // number of inputs given $n = 4; $y = array_fill(0, 10, array_fill(0, 10, 0)); $x = array( 5, 6, 9, 11 ); // y[][] is used for divided difference // table where y[][0] is used for input $y[0][0] = 12; $y[1][0] = 13; $y[2][0] = 14; $y[3][0] = 16; // calculating divided difference table dividedDiffTable($x, $y, $n); // displaying divided difference table printDiffTable($y, $n); // value to be interpolated $value = 7; // printing the value echo "\nValue at " . $value . " is " . round(applyFormula($value, $x, $y, $n), 2) . "\n" // This code is contributed by mits?>
12 1 -0.1667 0.05
13 0.3333 0.1333
14 1
16
Value at 7 is 13.47
Mithun Kumar
akashagg
itskawal2000
Algebra
Engineering Mathematics
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Difference between Propositional Logic and Predicate Logic
Mathematics | Introduction to Propositional Logic | Set 1
Arrow Symbols in LaTeX
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 145,
"s": 54,
"text": "Interpolation is an estimation of a value within two known values in a sequence of values."
},
{
"code": null,
"e": 298,
"s": 145,
"text": "Newton’s divided difference interpolation formula is a interpolation technique used when the interval difference is not same for all sequence of values."
},
{
"code": null,
"e": 518,
"s": 298,
"text": "Suppose f(x0), f(x1), f(x2).........f(xn) be the (n+1) values of the function y=f(x) corresponding to the arguments x=x0, x1, x2...xn, where interval differences are not sameThen the first divided difference is given by"
},
{
"code": null,
"e": 562,
"s": 520,
"text": "The second divided difference is given by"
},
{
"code": null,
"e": 881,
"s": 564,
"text": "and so on...Divided differences are symmetric with respect to the arguments i.e independent of the order of arguments.so, f[x0, x1]=f[x1, x0]f[x0, x1, x2]=f[x2, x1, x0]=f[x1, x2, x0]By using first divided difference, second divided difference as so on .A table is formed which is called the divided difference table."
},
{
"code": null,
"e": 907,
"s": 881,
"text": "Divided difference table:"
},
{
"code": null,
"e": 971,
"s": 907,
"text": "Advantages of NEWTON’S DIVIDED DIFFERENCE INTERPOLATION FORMULA"
},
{
"code": null,
"e": 1007,
"s": 971,
"text": "These are useful for interpolation."
},
{
"code": null,
"e": 1082,
"s": 1007,
"text": "Through difference table, we can find out the differences in higher order."
},
{
"code": null,
"e": 1224,
"s": 1082,
"text": "Differences at each stage in each of the columns are easily measured by subtracting the previous value from its immediately succeeding value."
},
{
"code": null,
"e": 1377,
"s": 1224,
"text": "The differences are found out successively between the two adjacent values of the y variable till the ultimate difference vanishes or become a constant."
},
{
"code": null,
"e": 1427,
"s": 1377,
"text": "NEWTON’S DIVIDED DIFFERENCE INTERPOLATION FORMULA"
},
{
"code": null,
"e": 1497,
"s": 1427,
"text": "Input : Value at 7\n \nOutput :\n \n Value at 7 is 13.47\n"
},
{
"code": null,
"e": 1579,
"s": 1497,
"text": "Below is the implementation for Newton’s divided difference interpolation method."
},
{
"code": null,
"e": 1583,
"s": 1579,
"text": "C++"
},
{
"code": null,
"e": 1588,
"s": 1583,
"text": "Java"
},
{
"code": null,
"e": 1596,
"s": 1588,
"text": "Python3"
},
{
"code": null,
"e": 1599,
"s": 1596,
"text": "C#"
},
{
"code": null,
"e": 1603,
"s": 1599,
"text": "PHP"
},
{
"code": "// CPP program for implementing// Newton divided difference formula#include <bits/stdc++.h>using namespace std; // Function to find the product termfloat proterm(int i, float value, float x[]){ float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro;} // Function for calculating// divided difference tablevoid dividedDiffTable(float x[], float y[][10], int n){ for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j][i] = (y[j][i - 1] - y[j + 1] [i - 1]) / (x[j] - x[i + j]); } }} // Function for applying Newton's// divided difference formulafloat applyFormula(float value, float x[], float y[][10], int n){ float sum = y[0][0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0][i]); } return sum;} // Function for displaying // divided difference tablevoid printDiffTable(float y[][10],int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { cout << setprecision(4) << y[i][j] << \"\\t \"; } cout << \"\\n\"; }} // Driver Functionint main(){ // number of inputs given int n = 4; float value, sum, y[10][10]; float x[] = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value cout << \"\\nValue at \" << value << \" is \" << applyFormula(value, x, y, n) << endl; return 0;}",
"e": 3402,
"s": 1603,
"text": null
},
{
"code": "// Java program for implementing// Newton divided difference formulaimport java.text.*;import java.math.*; class GFG{// Function to find the product termstatic float proterm(int i, float value, float x[]){ float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro;} // Function for calculating// divided difference tablestatic void dividedDiffTable(float x[], float y[][], int n){ for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j][i] = (y[j][i - 1] - y[j + 1] [i - 1]) / (x[j] - x[i + j]); } }} // Function for applying Newton's// divided difference formulastatic float applyFormula(float value, float x[], float y[][], int n){ float sum = y[0][0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0][i]); } return sum;} // Function for displaying // divided difference tablestatic void printDiffTable(float y[][],int n){ DecimalFormat df = new DecimalFormat(\"#.####\"); df.setRoundingMode(RoundingMode.HALF_UP); for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { String str1 = df.format(y[i][j]); System.out.print(str1+\"\\t \"); } System.out.println(\"\"); }} // Driver Functionpublic static void main(String[] args){ // number of inputs given int n = 4; float value, sum; float y[][]=new float[10][10]; float x[] = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value DecimalFormat df = new DecimalFormat(\"#.##\"); df.setRoundingMode(RoundingMode.HALF_UP); System.out.println(\"\\nValue at \"+df.format(value)+\" is \" +df.format(applyFormula(value, x, y, n)));}}// This code is contributed by mits",
"e": 5520,
"s": 3402,
"text": null
},
{
"code": "# Python3 program for implementing # Newton divided difference formula # Function to find the product term def proterm(i, value, x): pro = 1; for j in range(i): pro = pro * (value - x[j]); return pro; # Function for calculating # divided difference table def dividedDiffTable(x, y, n): for i in range(1, n): for j in range(n - i): y[j][i] = ((y[j][i - 1] - y[j + 1][i - 1]) / (x[j] - x[i + j])); return y; # Function for applying Newton's # divided difference formula def applyFormula(value, x, y, n): sum = y[0][0]; for i in range(1, n): sum = sum + (proterm(i, value, x) * y[0][i]); return sum; # Function for displaying divided # difference table def printDiffTable(y, n): for i in range(n): for j in range(n - i): print(round(y[i][j], 4), \"\\t\", end = \" \"); print(\"\"); # Driver Code # number of inputs given n = 4; y = [[0 for i in range(10)] for j in range(10)]; x = [ 5, 6, 9, 11 ]; # y[][] is used for divided difference # table where y[][0] is used for input y[0][0] = 12; y[1][0] = 13; y[2][0] = 14; y[3][0] = 16; # calculating divided difference table y=dividedDiffTable(x, y, n); # displaying divided difference table printDiffTable(y, n); # value to be interpolated value = 7; # printing the value print(\"\\nValue at\", value, \"is\", round(applyFormula(value, x, y, n), 2)) # This code is contributed by mits",
"e": 7053,
"s": 5520,
"text": null
},
{
"code": "// C# program for implementing // Newton divided difference formula using System; class GFG{ // Function to find the product term static float proterm(int i, float value, float[] x) { float pro = 1; for (int j = 0; j < i; j++) { pro = pro * (value - x[j]); } return pro; } // Function for calculating // divided difference table static void dividedDiffTable(float[] x, float[,] y, int n) { for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { y[j,i] = (y[j,i - 1] - y[j + 1,i - 1]) / (x[j] - x[i + j]); } } } // Function for applying Newton's // divided difference formula static float applyFormula(float value, float[] x, float[,] y, int n) { float sum = y[0,0]; for (int i = 1; i < n; i++) { sum = sum + (proterm(i, value, x) * y[0,i]); } return sum; } // Function for displaying // divided difference table static void printDiffTable(float[,] y,int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { Console.Write(Math.Round(y[i,j],4)+\"\\t \"); } Console.WriteLine(\"\"); } } // Driver Function public static void Main() { // number of inputs given int n = 4; float value; float[,] y=new float[10,10]; float[] x = { 5, 6, 9, 11 }; // y[][] is used for divided difference // table where y[][0] is used for input y[0,0] = 12; y[1,0] = 13; y[2,0] = 14; y[3,0] = 16; // calculating divided difference table dividedDiffTable(x, y, n); // displaying divided difference table printDiffTable(y,n); // value to be interpolated value = 7; // printing the value Console.WriteLine(\"\\nValue at \"+(value)+\" is \" +Math.Round(applyFormula(value, x, y, n),2)); } } // This code is contributed by mits ",
"e": 8920,
"s": 7053,
"text": null
},
{
"code": "<?php// PHP program for implementing // Newton divided difference formula // Function to find the product term function proterm($i, $value, $x) { $pro = 1; for ($j = 0; $j < $i; $j++) { $pro = $pro * ($value - $x[$j]); } return $pro; } // Function for calculating // divided difference table function dividedDiffTable($x, &$y, $n) { for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $n - $i; $j++) { $y[$j][$i] = ($y[$j][$i - 1] - $y[$j + 1][$i - 1]) / ($x[$j] - $x[$i + $j]); } } } // Function for applying Newton's // divided difference formula function applyFormula($value, $x, $y,$n) { $sum = $y[0][0]; for ($i = 1; $i < $n; $i++) { $sum = $sum + (proterm($i, $value, $x) * $y[0][$i]); } return $sum; } // Function for displaying // divided difference table function printDiffTable($y, $n) { for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n - $i; $j++) { echo round($y[$i][$j], 4) . \"\\t \"; } echo \"\\n\"; } } // Driver Code // number of inputs given $n = 4; $y = array_fill(0, 10, array_fill(0, 10, 0)); $x = array( 5, 6, 9, 11 ); // y[][] is used for divided difference // table where y[][0] is used for input $y[0][0] = 12; $y[1][0] = 13; $y[2][0] = 14; $y[3][0] = 16; // calculating divided difference table dividedDiffTable($x, $y, $n); // displaying divided difference table printDiffTable($y, $n); // value to be interpolated $value = 7; // printing the value echo \"\\nValue at \" . $value . \" is \" . round(applyFormula($value, $x, $y, $n), 2) . \"\\n\" // This code is contributed by mits?>",
"e": 10716,
"s": 8920,
"text": null
},
{
"code": null,
"e": 10825,
"s": 10716,
"text": "12 1 -0.1667 0.05 \n13 0.3333 0.1333 \n14 1 \n16 \n\nValue at 7 is 13.47\n"
},
{
"code": null,
"e": 10838,
"s": 10825,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10847,
"s": 10838,
"text": "akashagg"
},
{
"code": null,
"e": 10860,
"s": 10847,
"text": "itskawal2000"
},
{
"code": null,
"e": 10868,
"s": 10860,
"text": "Algebra"
},
{
"code": null,
"e": 10892,
"s": 10868,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 10905,
"s": 10892,
"text": "Mathematical"
},
{
"code": null,
"e": 10918,
"s": 10905,
"text": "Mathematical"
},
{
"code": null,
"e": 11016,
"s": 10918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11079,
"s": 11016,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 11101,
"s": 11079,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 11160,
"s": 11101,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 11218,
"s": 11160,
"text": "Mathematics | Introduction to Propositional Logic | Set 1"
},
{
"code": null,
"e": 11241,
"s": 11218,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 11271,
"s": 11241,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11314,
"s": 11271,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11374,
"s": 11314,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 11389,
"s": 11374,
"text": "C++ Data Types"
}
] |
Fligner-Killeen Test in R Programming
|
12 Oct, 2020
The Fligner-Killeen test is a non-parametric test for homogeneity of group variances based on ranks. It is useful when the data are non-normally distributed or when problems related to outliers in the dataset cannot be resolved. It is also one of the many tests for homogeneity of variances which is most robust against departures from normality. There are several solutions to test for the equality (homogeneity) of variance across groups, including:
F-test
Bartlett’s test
Levene’s test
Fligner-Killeen test
It is very much easy to perform these tests in R programming. In this article let’s perform the Fligner-Killeen test in R.
A hypothesis is a statement about the given problem. Hypothesis testing is a statistical method that is used in making a statistical decision using experimental data. Hypothesis testing is basically an assumption that we make about a population parameter. It evaluates two mutually exclusive statements about a population to determine which statement is best supported by the sample data. To know more about the statistical hypothesis please refer to Understanding Hypothesis Testing. For Fligner-Killeen test the statistical hypotheses are:
Null Hypothesis: All populations variances are equal
Alternative Hypothesis: At least two of them differ
The R provides a function fligner.test() which is available in stats package that can be used to compute the Fligner-Killeen test. The syntax for this function is given below:
Syntax:
fligner.test(formula, dataset)
Parameters:
formula: a formula of the form values ~ groups
dataset: a matrix or data frame
Fligner-Killeen test with one independent variable:
Consider the R’s inbuilt PlantGrowth dataset that gives the dried weight of three groups of ten batches of plants, wherever every group of ten batches got a different treatment. The weight variable gives the weight of the batch and the group variable gives the treatment received either ctrl, trt1 or trt2. To view the data set please type below command:
R
print(PlantGrowth)
Output:
weight group
1 4.17 ctrl
2 5.58 ctrl
3 5.18 ctrl
4 6.11 ctrl
5 4.50 ctrl
6 4.61 ctrl
7 5.17 ctrl
8 4.53 ctrl
9 5.33 ctrl
10 5.14 ctrl
11 4.81 trt1
12 4.17 trt1
13 4.41 trt1
14 3.59 trt1
15 5.87 trt1
16 3.83 trt1
17 6.03 trt1
18 4.89 trt1
19 4.32 trt1
20 4.69 trt1
21 6.31 trt2
22 5.12 trt2
23 5.54 trt2
24 5.50 trt2
25 5.37 trt2
26 5.29 trt2
27 4.92 trt2
28 6.15 trt2
29 5.80 trt2
30 5.26 trt2
As mentioned above, the Fligner-Killeen test is useful when the data are non-normally distributed or when problems related to outliers in the dataset cannot be resolved. Here let’s consider only one independent variable. To perform the test, use the below command:
R
# R program to illustrate# Fligner-Killeen test # Import required packagelibrary(stats) # Using fligner.test()result = fligner.test(weight ~ group, PlantGrowth) # print the resultprint(result)
Output:
Fligner-Killeen test of homogeneity of variances
data: weight by group
Fligner-Killeen:med chi-squared = 2.3499, df = 2, p-value = 0.3088
Fligner-Killeen test with multiple independent variables:
If one wants to do the test with multiple independent variables then the interaction() function must be used to collapse multiple factors into a single variable containing all combinations of the factors. Here let’s take the R’s inbuilt ToothGrowth data set.
R
# R program to illustrate# Fligner-Killeen test # Import required packagelibrary(stats) # Using fligner.test()result = fligner.test(len ~ interaction(supp, dose), data = ToothGrowth) # print the resultprint(result)
Output:
Fligner-Killeen test of homogeneity of variances
data: len by interaction(supp, dose)
Fligner-Killeen:med chi-squared = 7.7488, df = 5, p-value = 0.1706
R Data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2020"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "The Fligner-Killeen test is a non-parametric test for homogeneity of group variances based on ranks. It is useful when the data are non-normally distributed or when problems related to outliers in the dataset cannot be resolved. It is also one of the many tests for homogeneity of variances which is most robust against departures from normality. There are several solutions to test for the equality (homogeneity) of variance across groups, including:"
},
{
"code": null,
"e": 487,
"s": 480,
"text": "F-test"
},
{
"code": null,
"e": 503,
"s": 487,
"text": "Bartlett’s test"
},
{
"code": null,
"e": 517,
"s": 503,
"text": "Levene’s test"
},
{
"code": null,
"e": 538,
"s": 517,
"text": "Fligner-Killeen test"
},
{
"code": null,
"e": 661,
"s": 538,
"text": "It is very much easy to perform these tests in R programming. In this article let’s perform the Fligner-Killeen test in R."
},
{
"code": null,
"e": 1203,
"s": 661,
"text": "A hypothesis is a statement about the given problem. Hypothesis testing is a statistical method that is used in making a statistical decision using experimental data. Hypothesis testing is basically an assumption that we make about a population parameter. It evaluates two mutually exclusive statements about a population to determine which statement is best supported by the sample data. To know more about the statistical hypothesis please refer to Understanding Hypothesis Testing. For Fligner-Killeen test the statistical hypotheses are:"
},
{
"code": null,
"e": 1256,
"s": 1203,
"text": "Null Hypothesis: All populations variances are equal"
},
{
"code": null,
"e": 1308,
"s": 1256,
"text": "Alternative Hypothesis: At least two of them differ"
},
{
"code": null,
"e": 1484,
"s": 1308,
"text": "The R provides a function fligner.test() which is available in stats package that can be used to compute the Fligner-Killeen test. The syntax for this function is given below:"
},
{
"code": null,
"e": 1492,
"s": 1484,
"text": "Syntax:"
},
{
"code": null,
"e": 1523,
"s": 1492,
"text": "fligner.test(formula, dataset)"
},
{
"code": null,
"e": 1537,
"s": 1525,
"text": "Parameters:"
},
{
"code": null,
"e": 1584,
"s": 1537,
"text": "formula: a formula of the form values ~ groups"
},
{
"code": null,
"e": 1616,
"s": 1584,
"text": "dataset: a matrix or data frame"
},
{
"code": null,
"e": 1668,
"s": 1616,
"text": "Fligner-Killeen test with one independent variable:"
},
{
"code": null,
"e": 2023,
"s": 1668,
"text": "Consider the R’s inbuilt PlantGrowth dataset that gives the dried weight of three groups of ten batches of plants, wherever every group of ten batches got a different treatment. The weight variable gives the weight of the batch and the group variable gives the treatment received either ctrl, trt1 or trt2. To view the data set please type below command:"
},
{
"code": null,
"e": 2025,
"s": 2023,
"text": "R"
},
{
"code": "print(PlantGrowth)",
"e": 2044,
"s": 2025,
"text": null
},
{
"code": null,
"e": 2052,
"s": 2044,
"text": "Output:"
},
{
"code": null,
"e": 2550,
"s": 2052,
"text": " weight group\n1 4.17 ctrl\n2 5.58 ctrl\n3 5.18 ctrl\n4 6.11 ctrl\n5 4.50 ctrl\n6 4.61 ctrl\n7 5.17 ctrl\n8 4.53 ctrl\n9 5.33 ctrl\n10 5.14 ctrl\n11 4.81 trt1\n12 4.17 trt1\n13 4.41 trt1\n14 3.59 trt1\n15 5.87 trt1\n16 3.83 trt1\n17 6.03 trt1\n18 4.89 trt1\n19 4.32 trt1\n20 4.69 trt1\n21 6.31 trt2\n22 5.12 trt2\n23 5.54 trt2\n24 5.50 trt2\n25 5.37 trt2\n26 5.29 trt2\n27 4.92 trt2\n28 6.15 trt2\n29 5.80 trt2\n30 5.26 trt2\n"
},
{
"code": null,
"e": 2815,
"s": 2550,
"text": "As mentioned above, the Fligner-Killeen test is useful when the data are non-normally distributed or when problems related to outliers in the dataset cannot be resolved. Here let’s consider only one independent variable. To perform the test, use the below command:"
},
{
"code": null,
"e": 2817,
"s": 2815,
"text": "R"
},
{
"code": "# R program to illustrate# Fligner-Killeen test # Import required packagelibrary(stats) # Using fligner.test()result = fligner.test(weight ~ group, PlantGrowth) # print the resultprint(result)",
"e": 3013,
"s": 2817,
"text": null
},
{
"code": null,
"e": 3021,
"s": 3013,
"text": "Output:"
},
{
"code": null,
"e": 3162,
"s": 3021,
"text": "Fligner-Killeen test of homogeneity of variances\n\ndata: weight by group\nFligner-Killeen:med chi-squared = 2.3499, df = 2, p-value = 0.3088\n"
},
{
"code": null,
"e": 3220,
"s": 3162,
"text": "Fligner-Killeen test with multiple independent variables:"
},
{
"code": null,
"e": 3479,
"s": 3220,
"text": "If one wants to do the test with multiple independent variables then the interaction() function must be used to collapse multiple factors into a single variable containing all combinations of the factors. Here let’s take the R’s inbuilt ToothGrowth data set."
},
{
"code": null,
"e": 3481,
"s": 3479,
"text": "R"
},
{
"code": "# R program to illustrate# Fligner-Killeen test # Import required packagelibrary(stats) # Using fligner.test()result = fligner.test(len ~ interaction(supp, dose), data = ToothGrowth) # print the resultprint(result)",
"e": 3721,
"s": 3481,
"text": null
},
{
"code": null,
"e": 3729,
"s": 3721,
"text": "Output:"
},
{
"code": null,
"e": 3885,
"s": 3729,
"text": "Fligner-Killeen test of homogeneity of variances\n\ndata: len by interaction(supp, dose)\nFligner-Killeen:med chi-squared = 7.7488, df = 5, p-value = 0.1706\n"
},
{
"code": null,
"e": 3900,
"s": 3885,
"text": "R Data-science"
},
{
"code": null,
"e": 3911,
"s": 3900,
"text": "R Language"
},
{
"code": null,
"e": 4009,
"s": 3911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4061,
"s": 4009,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4119,
"s": 4061,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4154,
"s": 4119,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4192,
"s": 4154,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4241,
"s": 4192,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4258,
"s": 4241,
"text": "R - if statement"
},
{
"code": null,
"e": 4295,
"s": 4258,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4338,
"s": 4295,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4375,
"s": 4338,
"text": "How to import an Excel File into R ?"
}
] |
Polymorphism in R Programming
|
10 Aug, 2021
R language is evolving and it implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets you define a generic method or function for types of objects you haven’t yet defined and may never do. This means that one can use the same name for several functions with different sets of arguments and from various classes. R’s method call mechanism is generics which allows registering certain names to be treated as methods in R, and they act as dispatchers.
Polymorphism in R can be obtained by the generics. It allows certain names to be treated as methods and they act as dispatchers. Let’s understand with the help of plot() function and summary function. In R programming the plot() and summary() functions return different results depending on the objects being passed to them and that’s why they are generic functions that implement polymorphism.
plot() is one of the generic functions that implement polymorphism in R. It produces a different graph if it is given a vector, a factor, a data frame, etc. But have you ever wondered how does the class of vectors or factors determine the method used for plotting? Let’s see the code for the plot function.
Example: Code of plot function
R
plot
Output:
function (x, y, ...)
UseMethod("plot")
We can see that the body of the plot function contains only one expression and that is UseMethod(“plot”). Let’s see the definition of UseMethod with the help of help() function.
Example: Definition of the help() method.
R
help(UseMethod)
Output:
From the above output, we can see that UseMethod takes two parameters generic and object.
The generic is the string name which is the name of the function (plot in this case).
This is an object whose class will determine the method that will be “dispatched,” It means the object for which the generic method will be called.
The UseMethod then searches for the suitable plot function that is needed to be called by creating a string of the type plot.object. We can also see all the available methods for the plot function.
Example:
R
methods(plot)
Output:
Let’s see how plot() function taking arguments and displaying different outputs
In this example let’s take a single numeric vector inside plot() function as a parameter.
R
# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 15, height = 13) # The runif() function generates# random deviates of the uniform distributionx <- 3 * runif(40) + (1:30)par(mar = c(20, 20, 1, 1)) # type='l' is used to connect the points# of the scatter plots with lines.plot(x, type = 'l', col = '#343deb') # We can do mouse click or enter pressedz <- locator(1)
Output:
We need to pass two vector parameters and it produces a scatter plot accordingly.
R
# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 5, height = 3) # The runif() function generates random# deviates of the uniform distributionx <- runif(20)y <- runif(20) * xpar(mar = c(2, 2, 0.3, 0.3)) # type = 'p' means as points, the output comes as scattered# pch stands for plot character. pch = 16 we get . characterplot(x, y, type = 'p', pch = 16, col = '#ab1ab0') #Either mouse press or enter key press waitz <- locator(1)
Output:
If we passed factor as arguments then we get a bar chart pattern.
R
# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 5, height = 8) # here fruits names are passed and barchart is produced as outputf <- factor(c('apple', 'orange', 'apple', 'pear', 'orange', 'apple', 'apple', 'orange'))par(mar = c(2, 2, 0.6, 0.6)) # Using plot()plot(f, col = '#8f4c91')z <- locator(1)
Output:
The Plot function takes the data frame as an argument and each variable of the data frame is plotted against each other.
R
# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 6, height = 6) set.seed(280870)x <- c(4, 3, 1, 2, 2, 4, 6, 4, 5, 5, 4, 4, 5, 4, 4, 8, 4, 1, 2, 7)y <- x * rnorm(20, 1, 0.3)z <- x * y # Takina a data framedf <- data.frame(x, y, z)par(mar = c(0.1, 0.1, 0.1, 0.1)) # Using plot()plot(df, col = '#a832a6', pch = 16, cex = 1.5)z <- locator(1)
Output:
It is also a generic function that implements polymorphism in R. It is used to produce result summaries of the results of various model fitting functions.
Example 1:
R
# R program to illustrate# polymorphosim # Rainbow colors and let us see summary of itcolors <- c("violet", "indigo", "blue", "green", "yellow", "orange", "red")summary(colors)
Output:
Length Class Mode
7 character character
Example 2:
Let us check for summarized results for state.region. In R it usually displays what are the regions available under “Northeast”, “South”, “North Central”, and “West”. Using summary() function either one can pass state.region as 1st parameter and as a second step, (optionally) pass “maxsum” argument. “maxsum” indicates how many levels should be shown for factors in output.
R
# R program to illustrate# polymorphosim state.region # Provides summarised results under each regionsummary(state.region) # As maxsum is given as 3, totally we should have 3 regions# But here we have 4 regions and hence highest count region,# next highest count region is displayed and the other# regions are clubbed under Othersummary(state.region, maxsum = 3)
Output:
> state.region
[1] South West West South West West
[7] Northeast South South South West West
[13] North Central North Central North Central North Central South South
[19] Northeast South Northeast North Central North Central South
[25] North Central West North Central West Northeast Northeast
[31] West Northeast South North Central North Central South
[37] West Northeast Northeast South North Central South
[43] South West Northeast South West South
[49] North Central West
Levels: Northeast South North Central West
> summary(state.region)
Northeast South North Central West
9 16 12 13
> summary(state.region, maxsum = 3)
South West (Other)
16 13 21
Example 3:
If the data set is very large then let’s have a look at how the summary() function works.
R
# R program to illustrate# polymorphosim # 10 different data sets are taken using stats::rnormx <- stats::rnorm(10)x # Let us cut the dataset to lie between -3 and 3 and# in this case, it will be# (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]c <- cut(x, breaks = -3:3)c # Summarized the available dataset under the given levelssummary(c)
Output:
> x
[1] 0.66647846 -0.29140286 -0.29596477 -0.23432541 -0.02144178 1.56640107 0.64575227
[8] -0.23759734 0.73304657 -0.04201218
> c
[1] (0,1] (-1,0] (-1,0] (-1,0] (-1,0] (1,2] (0,1] (-1,0] (0,1] (-1,0]
Levels: (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]
> summary(c)
(-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]
0 0 6 3 1 0
Till now, we have described the plot() and summary() function which is a polymorphic function. By means of different inputs, plot() function behavior is changing and producing outputs. Here we can see the polymorphism concept. Similarly, in summary(), function, by means of varying parameters, the same method is applicable to provide different statistical outputs. Now let’s create our own generic methods.
Let’s create a class bank and let’s try to create our own display() method that will use the print() method and will display the content of the class in the format specified by us.
For doing this we first have to create a generic display() function that will use the UseMethod function.
R
display <- function(obj){ UseMethod("print")}
After creating the generic display function let’s create the display function for our class bank.
R
print.bank<-function(obj){ cat("Name is ", obj$name, "\n") cat(obj$account_no, " is the Acc no of the holder\n ") cat(obj$saving, " is the amount of saving in the account \n ") cat(obj$withdrawn, " is the withdrawn amount\n")}
Now, let’s see the output given by this function
R
x <- list(name ="Arjun", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-"bank" display <- function(obj){ UseMethod("print")} print.bank<-function(obj){ cat("Name is ", obj$name, "\n") cat(obj$account_no, " is the Acc no of the holder\n ") cat(obj$saving, " is the amount of saving in the account \n ") cat(obj$withdrawn, " is the withdrawn amount\n")} display(x)
Output:
Name is Arjun
1234 is the Acc no of the holder
1500 is the amount of saving in the account
234 is the withdrawn amount
gulshankumarar231
nikhilaggarwal3
Picked
R-OOPs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
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)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 586,
"s": 54,
"text": "R language is evolving and it implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets you define a generic method or function for types of objects you haven’t yet defined and may never do. This means that one can use the same name for several functions with different sets of arguments and from various classes. R’s method call mechanism is generics which allows registering certain names to be treated as methods in R, and they act as dispatchers. "
},
{
"code": null,
"e": 982,
"s": 586,
"text": "Polymorphism in R can be obtained by the generics. It allows certain names to be treated as methods and they act as dispatchers. Let’s understand with the help of plot() function and summary function. In R programming the plot() and summary() functions return different results depending on the objects being passed to them and that’s why they are generic functions that implement polymorphism. "
},
{
"code": null,
"e": 1291,
"s": 982,
"text": "plot() is one of the generic functions that implement polymorphism in R. It produces a different graph if it is given a vector, a factor, a data frame, etc. But have you ever wondered how does the class of vectors or factors determine the method used for plotting? Let’s see the code for the plot function. "
},
{
"code": null,
"e": 1322,
"s": 1291,
"text": "Example: Code of plot function"
},
{
"code": null,
"e": 1324,
"s": 1322,
"text": "R"
},
{
"code": "plot",
"e": 1329,
"s": 1324,
"text": null
},
{
"code": null,
"e": 1337,
"s": 1329,
"text": "Output:"
},
{
"code": null,
"e": 1376,
"s": 1337,
"text": "function (x, y, ...)\nUseMethod(\"plot\")"
},
{
"code": null,
"e": 1554,
"s": 1376,
"text": "We can see that the body of the plot function contains only one expression and that is UseMethod(“plot”). Let’s see the definition of UseMethod with the help of help() function."
},
{
"code": null,
"e": 1596,
"s": 1554,
"text": "Example: Definition of the help() method."
},
{
"code": null,
"e": 1598,
"s": 1596,
"text": "R"
},
{
"code": "help(UseMethod)",
"e": 1614,
"s": 1598,
"text": null
},
{
"code": null,
"e": 1622,
"s": 1614,
"text": "Output:"
},
{
"code": null,
"e": 1713,
"s": 1622,
"text": "From the above output, we can see that UseMethod takes two parameters generic and object. "
},
{
"code": null,
"e": 1800,
"s": 1713,
"text": "The generic is the string name which is the name of the function (plot in this case). "
},
{
"code": null,
"e": 1948,
"s": 1800,
"text": "This is an object whose class will determine the method that will be “dispatched,” It means the object for which the generic method will be called."
},
{
"code": null,
"e": 2146,
"s": 1948,
"text": "The UseMethod then searches for the suitable plot function that is needed to be called by creating a string of the type plot.object. We can also see all the available methods for the plot function."
},
{
"code": null,
"e": 2155,
"s": 2146,
"text": "Example:"
},
{
"code": null,
"e": 2157,
"s": 2155,
"text": "R"
},
{
"code": "methods(plot)",
"e": 2171,
"s": 2157,
"text": null
},
{
"code": null,
"e": 2179,
"s": 2171,
"text": "Output:"
},
{
"code": null,
"e": 2259,
"s": 2179,
"text": "Let’s see how plot() function taking arguments and displaying different outputs"
},
{
"code": null,
"e": 2349,
"s": 2259,
"text": "In this example let’s take a single numeric vector inside plot() function as a parameter."
},
{
"code": null,
"e": 2351,
"s": 2349,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 15, height = 13) # The runif() function generates# random deviates of the uniform distributionx <- 3 * runif(40) + (1:30)par(mar = c(20, 20, 1, 1)) # type='l' is used to connect the points# of the scatter plots with lines.plot(x, type = 'l', col = '#343deb') # We can do mouse click or enter pressedz <- locator(1)",
"e": 2753,
"s": 2351,
"text": null
},
{
"code": null,
"e": 2762,
"s": 2753,
"text": " Output:"
},
{
"code": null,
"e": 2844,
"s": 2762,
"text": "We need to pass two vector parameters and it produces a scatter plot accordingly."
},
{
"code": null,
"e": 2846,
"s": 2844,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 5, height = 3) # The runif() function generates random# deviates of the uniform distributionx <- runif(20)y <- runif(20) * xpar(mar = c(2, 2, 0.3, 0.3)) # type = 'p' means as points, the output comes as scattered# pch stands for plot character. pch = 16 we get . characterplot(x, y, type = 'p', pch = 16, col = '#ab1ab0') #Either mouse press or enter key press waitz <- locator(1)",
"e": 3312,
"s": 2846,
"text": null
},
{
"code": null,
"e": 3321,
"s": 3312,
"text": " Output:"
},
{
"code": null,
"e": 3388,
"s": 3321,
"text": "If we passed factor as arguments then we get a bar chart pattern. "
},
{
"code": null,
"e": 3390,
"s": 3388,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 5, height = 8) # here fruits names are passed and barchart is produced as outputf <- factor(c('apple', 'orange', 'apple', 'pear', 'orange', 'apple', 'apple', 'orange'))par(mar = c(2, 2, 0.6, 0.6)) # Using plot()plot(f, col = '#8f4c91')z <- locator(1)",
"e": 3739,
"s": 3390,
"text": null
},
{
"code": null,
"e": 3748,
"s": 3739,
"text": " Output:"
},
{
"code": null,
"e": 3869,
"s": 3748,
"text": "The Plot function takes the data frame as an argument and each variable of the data frame is plotted against each other."
},
{
"code": null,
"e": 3871,
"s": 3869,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # X Window System Graphics (X11)X11(width = 6, height = 6) set.seed(280870)x <- c(4, 3, 1, 2, 2, 4, 6, 4, 5, 5, 4, 4, 5, 4, 4, 8, 4, 1, 2, 7)y <- x * rnorm(20, 1, 0.3)z <- x * y # Takina a data framedf <- data.frame(x, y, z)par(mar = c(0.1, 0.1, 0.1, 0.1)) # Using plot()plot(df, col = '#a832a6', pch = 16, cex = 1.5)z <- locator(1)",
"e": 4251,
"s": 3871,
"text": null
},
{
"code": null,
"e": 4260,
"s": 4251,
"text": " Output:"
},
{
"code": null,
"e": 4415,
"s": 4260,
"text": "It is also a generic function that implements polymorphism in R. It is used to produce result summaries of the results of various model fitting functions."
},
{
"code": null,
"e": 4426,
"s": 4415,
"text": "Example 1:"
},
{
"code": null,
"e": 4428,
"s": 4426,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # Rainbow colors and let us see summary of itcolors <- c(\"violet\", \"indigo\", \"blue\", \"green\", \"yellow\", \"orange\", \"red\")summary(colors)",
"e": 4616,
"s": 4428,
"text": null
},
{
"code": null,
"e": 4625,
"s": 4616,
"text": " Output:"
},
{
"code": null,
"e": 4683,
"s": 4625,
"text": "Length Class Mode \n 7 character character "
},
{
"code": null,
"e": 4694,
"s": 4683,
"text": "Example 2:"
},
{
"code": null,
"e": 5069,
"s": 4694,
"text": "Let us check for summarized results for state.region. In R it usually displays what are the regions available under “Northeast”, “South”, “North Central”, and “West”. Using summary() function either one can pass state.region as 1st parameter and as a second step, (optionally) pass “maxsum” argument. “maxsum” indicates how many levels should be shown for factors in output."
},
{
"code": null,
"e": 5071,
"s": 5069,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim state.region # Provides summarised results under each regionsummary(state.region) # As maxsum is given as 3, totally we should have 3 regions# But here we have 4 regions and hence highest count region,# next highest count region is displayed and the other# regions are clubbed under Othersummary(state.region, maxsum = 3)",
"e": 5434,
"s": 5071,
"text": null
},
{
"code": null,
"e": 5442,
"s": 5434,
"text": "Output:"
},
{
"code": null,
"e": 6497,
"s": 5442,
"text": "> state.region\n [1] South West West South West West \n [7] Northeast South South South West West \n[13] North Central North Central North Central North Central South South \n[19] Northeast South Northeast North Central North Central South \n[25] North Central West North Central West Northeast Northeast \n[31] West Northeast South North Central North Central South \n[37] West Northeast Northeast South North Central South \n[43] South West Northeast South West South \n[49] North Central West \nLevels: Northeast South North Central West\n\n> summary(state.region) \n Northeast South North Central West \n 9 16 12 13 \n \n> summary(state.region, maxsum = 3) \n South West (Other) \n 16 13 21 "
},
{
"code": null,
"e": 6508,
"s": 6497,
"text": "Example 3:"
},
{
"code": null,
"e": 6598,
"s": 6508,
"text": "If the data set is very large then let’s have a look at how the summary() function works."
},
{
"code": null,
"e": 6600,
"s": 6598,
"text": "R"
},
{
"code": "# R program to illustrate# polymorphosim # 10 different data sets are taken using stats::rnormx <- stats::rnorm(10)x # Let us cut the dataset to lie between -3 and 3 and# in this case, it will be# (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]c <- cut(x, breaks = -3:3)c # Summarized the available dataset under the given levelssummary(c)",
"e": 6933,
"s": 6600,
"text": null
},
{
"code": null,
"e": 6942,
"s": 6933,
"text": " Output:"
},
{
"code": null,
"e": 7318,
"s": 6942,
"text": "> x\n [1] 0.66647846 -0.29140286 -0.29596477 -0.23432541 -0.02144178 1.56640107 0.64575227\n [8] -0.23759734 0.73304657 -0.04201218\n \n> c\n [1] (0,1] (-1,0] (-1,0] (-1,0] (-1,0] (1,2] (0,1] (-1,0] (0,1] (-1,0]\nLevels: (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]\n\n> summary(c)\n(-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3] \n 0 0 6 3 1 0 "
},
{
"code": null,
"e": 7726,
"s": 7318,
"text": "Till now, we have described the plot() and summary() function which is a polymorphic function. By means of different inputs, plot() function behavior is changing and producing outputs. Here we can see the polymorphism concept. Similarly, in summary(), function, by means of varying parameters, the same method is applicable to provide different statistical outputs. Now let’s create our own generic methods."
},
{
"code": null,
"e": 7907,
"s": 7726,
"text": "Let’s create a class bank and let’s try to create our own display() method that will use the print() method and will display the content of the class in the format specified by us."
},
{
"code": null,
"e": 8013,
"s": 7907,
"text": "For doing this we first have to create a generic display() function that will use the UseMethod function."
},
{
"code": null,
"e": 8015,
"s": 8013,
"text": "R"
},
{
"code": "display <- function(obj){ UseMethod(\"print\")}",
"e": 8064,
"s": 8015,
"text": null
},
{
"code": null,
"e": 8162,
"s": 8064,
"text": "After creating the generic display function let’s create the display function for our class bank."
},
{
"code": null,
"e": 8164,
"s": 8162,
"text": "R"
},
{
"code": "print.bank<-function(obj){ cat(\"Name is \", obj$name, \"\\n\") cat(obj$account_no, \" is the Acc no of the holder\\n \") cat(obj$saving, \" is the amount of saving in the account \\n \") cat(obj$withdrawn, \" is the withdrawn amount\\n\")}",
"e": 8403,
"s": 8164,
"text": null
},
{
"code": null,
"e": 8452,
"s": 8403,
"text": "Now, let’s see the output given by this function"
},
{
"code": null,
"e": 8454,
"s": 8452,
"text": "R"
},
{
"code": "x <- list(name =\"Arjun\", account_no = 1234, saving = 1500, withdrawn = 234)class(x)<-\"bank\" display <- function(obj){ UseMethod(\"print\")} print.bank<-function(obj){ cat(\"Name is \", obj$name, \"\\n\") cat(obj$account_no, \" is the Acc no of the holder\\n \") cat(obj$saving, \" is the amount of saving in the account \\n \") cat(obj$withdrawn, \" is the withdrawn amount\\n\")} display(x)",
"e": 8852,
"s": 8454,
"text": null
},
{
"code": null,
"e": 8860,
"s": 8852,
"text": "Output:"
},
{
"code": null,
"e": 8987,
"s": 8860,
"text": "Name is Arjun \n1234 is the Acc no of the holder\n 1500 is the amount of saving in the account \n 234 is the withdrawn amount"
},
{
"code": null,
"e": 9005,
"s": 8987,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 9021,
"s": 9005,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 9028,
"s": 9021,
"text": "Picked"
},
{
"code": null,
"e": 9035,
"s": 9028,
"text": "R-OOPs"
},
{
"code": null,
"e": 9046,
"s": 9035,
"text": "R Language"
},
{
"code": null,
"e": 9144,
"s": 9046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9189,
"s": 9144,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 9241,
"s": 9189,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 9299,
"s": 9241,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 9351,
"s": 9299,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 9409,
"s": 9351,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 9441,
"s": 9409,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 9504,
"s": 9441,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 9539,
"s": 9504,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 9583,
"s": 9539,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
Flutter – Row and Column Widgets
|
29 Jun, 2022
Row and Column are the two most important and powerful widgets in Flutter. These widgets let you align children horizontally and vertically as per the requirement. As we know that when we design any UI(User Interface) in a flutter, we need to arrange its content in the Row and Column manner so these Row and Column widgets are required when designing UI.
Column(
{Key key,
MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
MainAxisSize mainAxisSize: MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
TextDirection textDirection,
VerticalDirection verticalDirection: VerticalDirection.down,
TextBaseline textBaseline,
List<Widget> children: const <Widget>[]}
)
Row(
{Key key,
MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
MainAxisSize mainAxisSize: MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
TextDirection textDirection,
VerticalDirection verticalDirection: VerticalDirection.down,
TextBaseline textBaseline: TextBaseline.alphabetic,
List<Widget> children: const <Widget>[]}
)
children: This property takes in List<Widget>, that is a list of widgets to display inside the Row or the Column widget.
clipBehaviour: This property holds Clip class as the object to decide whether the content on the Row or Column should be clipped or not.
crossAxisAlignment: The crossAxisAlignment takes in CrossAxisAlignment enum as the object to how the children’s widgets should be places in crossAxisAlignment. For Row it is vertical and for Column it is horizontal.
direction: This property holds as the Axis enum object to decide the direction used in the main axis. For Row and Column, it is fixed.
mainAxisAlignment: This property takes in MainAxisAlignment enum as the object to decide how the children widgets should be place in mainAxisAlignment. For Row it is horizontal and for Column it is vertical.
mainAxisSize: This property decides the size of main-axis by taking in MainAxisSize enum as the object.
runtimeType: This property tells the run-time type of the Row or Column widget.
textBaseline: This property is responsible for the alignment of the text in the Row or Column widget with respect to a baseline.
textDirection: This property controls the text direction of the Row or Column widget, which can either be from left-to-right (by default) or right-to-left.
verticalDirection: This property takes in VerticalDirection enum as the object to determine the order in which the children should be layered.
It creates a horizontal array of children.
Alignment Properties: We can align content as per our choice by using mainAxisAlignment and crossAxisAlignment. Row’s mainAxis is horizontal and cross Axis to Row’s main Axis is vertical. We can align children horizontally using MainAxisAlignment and vertically using CrossAxisAlignment in that row.
Apart from these mainAxisAlignment and crossAxisAlignment, we also have some other properties like mainAxisSize,textDirection,verticalDirection etc. but we will focus on these two(mainAxisAlignment and crossAxisAlignment) in this article as these are mostly used and others in some other article.
Row
We can align the content by using the following properties:
start: Place the children from the starting of the row.
end: Place the children at the end of the row.
center: Place the children at the center of the row.
spaceBetween: Place the space evenly between the children.
spaceAround: Place the space evenly between the children and also half of that space before and after the first and last child.
spaceEvenly: Place the space evenly between the children and also before and after the first and last child.
We will see the difference with the help of examples. Let’s suppose we want to align content such that there is space around the children in a row :
Dart
import 'package:flutter/material.dart'; //function to trigger buildvoid main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.green, ),// ThemeData home: const MyHomePage(), debugShowCheckedModeBanner: false, );// MaterialApp }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("GeeksForGeeks"), ),// AppBar // App body consists of single Row // Row consists of three children widgets body: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "Geeks", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "For", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "Geeks", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), ); }}
Output:
It creates a vertical array of children.
In this also we have mainAxisAlignment and crossAxisAlignment. In column, children are aligned from top to bottom. Main Axis is vertical and the Cross Axis is horizontal. MainAxisAlignment aligns its children vertically and CrossAxisAlignment aligns horizontally in that Column.
Column
We can align the content by using the same properties as discussed above in Row (start, end,spaceBetween,spaceAround,spaceEvenly).
We will see the difference with the help of examples. Let’s suppose we want to align content so that we have space around the children . Assign mainAxisAlignment as spaceAround as shown below:
Example
Dart
import 'package:flutter/material.dart'; //function to trigger buildvoid main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.green, ), // ThemeData home: const MyHomePage(), debugShowCheckedModeBanner: false, ); // MaterialApp }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("GeeksForGeeks"), ), // AppBar // App body consists of single Column // Column consists of three children widgets body: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "GeeksForGeeks", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "GeeksForGeeks", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( "GeeksForGeeks", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), // Column ); }}
Output:
Some more examples are :
mainAxisAlignment.spaceEvenly
mainAxisAlignment.spaceEvenly
mainAxisAlignment.center
mainAxisAlignment.center
mainAxisAlignment.spaceBetween
mainAxisAlignment.spaceBetween
We can also align content using combination of mainAxisAlignment and crossAxisAlignment for both Row and Column. Lets take an example of Row, set mainAxisAlignment as MainAxisAlignment.spaceAround and crossAxisAlignment as CrossAxisAlignment.stretch. By doing this(crossAxisAlignment.stretch), the height of the row will be equal to the height of the body because we have only one row.
The row has no horizontal scrolling so when a large number of children are inserted in a single row that is not able to fit in the row then it will give us an Overflow message (for ex: Right overflowed by 560px).
The column has no vertical scrolling so when a large number of children are inserted in a single Column whose total children size is more than the total height of the screen then it will give us an Overflow message (for ex: Bottom overflowed by 684px).
ankit_kumar_
sagartomar9927
Flutter-widgets
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Stack Widget
Flutter - Search Bar
Operators in Dart
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter - Dialogs
Flutter - ListTile Widget
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 412,
"s": 54,
"text": "Row and Column are the two most important and powerful widgets in Flutter. These widgets let you align children horizontally and vertically as per the requirement. As we know that when we design any UI(User Interface) in a flutter, we need to arrange its content in the Row and Column manner so these Row and Column widgets are required when designing UI. "
},
{
"code": null,
"e": 763,
"s": 412,
"text": "Column(\n{Key key,\nMainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,\nMainAxisSize mainAxisSize: MainAxisSize.max,\nCrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,\nTextDirection textDirection,\nVerticalDirection verticalDirection: VerticalDirection.down,\nTextBaseline textBaseline,\nList<Widget> children: const <Widget>[]}\n)"
},
{
"code": null,
"e": 1136,
"s": 763,
"text": "Row(\n{Key key,\nMainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,\nMainAxisSize mainAxisSize: MainAxisSize.max,\nCrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,\nTextDirection textDirection,\nVerticalDirection verticalDirection: VerticalDirection.down,\nTextBaseline textBaseline: TextBaseline.alphabetic,\nList<Widget> children: const <Widget>[]}\n)"
},
{
"code": null,
"e": 1257,
"s": 1136,
"text": "children: This property takes in List<Widget>, that is a list of widgets to display inside the Row or the Column widget."
},
{
"code": null,
"e": 1394,
"s": 1257,
"text": "clipBehaviour: This property holds Clip class as the object to decide whether the content on the Row or Column should be clipped or not."
},
{
"code": null,
"e": 1610,
"s": 1394,
"text": "crossAxisAlignment: The crossAxisAlignment takes in CrossAxisAlignment enum as the object to how the children’s widgets should be places in crossAxisAlignment. For Row it is vertical and for Column it is horizontal."
},
{
"code": null,
"e": 1745,
"s": 1610,
"text": "direction: This property holds as the Axis enum object to decide the direction used in the main axis. For Row and Column, it is fixed."
},
{
"code": null,
"e": 1953,
"s": 1745,
"text": "mainAxisAlignment: This property takes in MainAxisAlignment enum as the object to decide how the children widgets should be place in mainAxisAlignment. For Row it is horizontal and for Column it is vertical."
},
{
"code": null,
"e": 2057,
"s": 1953,
"text": "mainAxisSize: This property decides the size of main-axis by taking in MainAxisSize enum as the object."
},
{
"code": null,
"e": 2137,
"s": 2057,
"text": "runtimeType: This property tells the run-time type of the Row or Column widget."
},
{
"code": null,
"e": 2266,
"s": 2137,
"text": "textBaseline: This property is responsible for the alignment of the text in the Row or Column widget with respect to a baseline."
},
{
"code": null,
"e": 2422,
"s": 2266,
"text": "textDirection: This property controls the text direction of the Row or Column widget, which can either be from left-to-right (by default) or right-to-left."
},
{
"code": null,
"e": 2565,
"s": 2422,
"text": "verticalDirection: This property takes in VerticalDirection enum as the object to determine the order in which the children should be layered."
},
{
"code": null,
"e": 2608,
"s": 2565,
"text": "It creates a horizontal array of children."
},
{
"code": null,
"e": 2909,
"s": 2608,
"text": "Alignment Properties: We can align content as per our choice by using mainAxisAlignment and crossAxisAlignment. Row’s mainAxis is horizontal and cross Axis to Row’s main Axis is vertical. We can align children horizontally using MainAxisAlignment and vertically using CrossAxisAlignment in that row."
},
{
"code": null,
"e": 3206,
"s": 2909,
"text": "Apart from these mainAxisAlignment and crossAxisAlignment, we also have some other properties like mainAxisSize,textDirection,verticalDirection etc. but we will focus on these two(mainAxisAlignment and crossAxisAlignment) in this article as these are mostly used and others in some other article."
},
{
"code": null,
"e": 3210,
"s": 3206,
"text": "Row"
},
{
"code": null,
"e": 3270,
"s": 3210,
"text": "We can align the content by using the following properties:"
},
{
"code": null,
"e": 3326,
"s": 3270,
"text": "start: Place the children from the starting of the row."
},
{
"code": null,
"e": 3373,
"s": 3326,
"text": "end: Place the children at the end of the row."
},
{
"code": null,
"e": 3426,
"s": 3373,
"text": "center: Place the children at the center of the row."
},
{
"code": null,
"e": 3485,
"s": 3426,
"text": "spaceBetween: Place the space evenly between the children."
},
{
"code": null,
"e": 3614,
"s": 3485,
"text": "spaceAround: Place the space evenly between the children and also half of that space before and after the first and last child."
},
{
"code": null,
"e": 3724,
"s": 3614,
"text": "spaceEvenly: Place the space evenly between the children and also before and after the first and last child."
},
{
"code": null,
"e": 3873,
"s": 3724,
"text": "We will see the difference with the help of examples. Let’s suppose we want to align content such that there is space around the children in a row :"
},
{
"code": null,
"e": 3878,
"s": 3873,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; //function to trigger buildvoid main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.green, ),// ThemeData home: const MyHomePage(), debugShowCheckedModeBanner: false, );// MaterialApp }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(\"GeeksForGeeks\"), ),// AppBar // App body consists of single Row // Row consists of three children widgets body: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"Geeks\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"For\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"Geeks\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), ); }}",
"e": 6078,
"s": 3878,
"text": null
},
{
"code": null,
"e": 6086,
"s": 6078,
"text": "Output:"
},
{
"code": null,
"e": 6127,
"s": 6086,
"text": "It creates a vertical array of children."
},
{
"code": null,
"e": 6406,
"s": 6127,
"text": "In this also we have mainAxisAlignment and crossAxisAlignment. In column, children are aligned from top to bottom. Main Axis is vertical and the Cross Axis is horizontal. MainAxisAlignment aligns its children vertically and CrossAxisAlignment aligns horizontally in that Column."
},
{
"code": null,
"e": 6413,
"s": 6406,
"text": "Column"
},
{
"code": null,
"e": 6544,
"s": 6413,
"text": "We can align the content by using the same properties as discussed above in Row (start, end,spaceBetween,spaceAround,spaceEvenly)."
},
{
"code": null,
"e": 6737,
"s": 6544,
"text": "We will see the difference with the help of examples. Let’s suppose we want to align content so that we have space around the children . Assign mainAxisAlignment as spaceAround as shown below:"
},
{
"code": null,
"e": 6745,
"s": 6737,
"text": "Example"
},
{
"code": null,
"e": 6750,
"s": 6745,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; //function to trigger buildvoid main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.green, ), // ThemeData home: const MyHomePage(), debugShowCheckedModeBanner: false, ); // MaterialApp }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(\"GeeksForGeeks\"), ), // AppBar // App body consists of single Column // Column consists of three children widgets body: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"GeeksForGeeks\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"GeeksForGeeks\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.green), child: const Padding( padding: EdgeInsets.all(8.0), child: Text( \"GeeksForGeeks\", style: TextStyle(color: Colors.white, fontSize: 25), ), ), ) ], ), // Column ); }}",
"e": 8998,
"s": 6750,
"text": null
},
{
"code": null,
"e": 9006,
"s": 8998,
"text": "Output:"
},
{
"code": null,
"e": 9031,
"s": 9006,
"text": "Some more examples are :"
},
{
"code": null,
"e": 9061,
"s": 9031,
"text": "mainAxisAlignment.spaceEvenly"
},
{
"code": null,
"e": 9091,
"s": 9061,
"text": "mainAxisAlignment.spaceEvenly"
},
{
"code": null,
"e": 9116,
"s": 9091,
"text": "mainAxisAlignment.center"
},
{
"code": null,
"e": 9141,
"s": 9116,
"text": "mainAxisAlignment.center"
},
{
"code": null,
"e": 9172,
"s": 9141,
"text": "mainAxisAlignment.spaceBetween"
},
{
"code": null,
"e": 9203,
"s": 9172,
"text": "mainAxisAlignment.spaceBetween"
},
{
"code": null,
"e": 9589,
"s": 9203,
"text": "We can also align content using combination of mainAxisAlignment and crossAxisAlignment for both Row and Column. Lets take an example of Row, set mainAxisAlignment as MainAxisAlignment.spaceAround and crossAxisAlignment as CrossAxisAlignment.stretch. By doing this(crossAxisAlignment.stretch), the height of the row will be equal to the height of the body because we have only one row."
},
{
"code": null,
"e": 9802,
"s": 9589,
"text": "The row has no horizontal scrolling so when a large number of children are inserted in a single row that is not able to fit in the row then it will give us an Overflow message (for ex: Right overflowed by 560px)."
},
{
"code": null,
"e": 10055,
"s": 9802,
"text": "The column has no vertical scrolling so when a large number of children are inserted in a single Column whose total children size is more than the total height of the screen then it will give us an Overflow message (for ex: Bottom overflowed by 684px)."
},
{
"code": null,
"e": 10068,
"s": 10055,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 10083,
"s": 10068,
"text": "sagartomar9927"
},
{
"code": null,
"e": 10099,
"s": 10083,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 10104,
"s": 10099,
"text": "Dart"
},
{
"code": null,
"e": 10202,
"s": 10104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10241,
"s": 10202,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 10267,
"s": 10241,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 10293,
"s": 10267,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 10316,
"s": 10293,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 10337,
"s": 10316,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 10355,
"s": 10337,
"text": "Operators in Dart"
},
{
"code": null,
"e": 10386,
"s": 10355,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 10412,
"s": 10386,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 10430,
"s": 10412,
"text": "Flutter - Dialogs"
}
] |
Quality Function Deployment (QFD) in Software Quality
|
17 Aug, 2020
Quality Function Deployment (QFD) is process or set of tools used to define the customer requirements for product and convert those requirements into engineering specifications and plans such that the customer requirements for that product are satisfied.
QFD was developed in late 1960s by Japanese Planning Specialist named Yoji Akao.
QFD aims at translating Voice of Customer into measurable and detailed design targets and then drives them from the assembly level down through sub-assembly level, component level, and production process levels.
QFD helps to achieve structured planning of product by enabling development team to clearly specify customer needs and expectations of product and then evaluate each part of product systematically.
Key steps in QFD :
Product planning :Translating what customer wants or needs into set of prioritized design requirements.Prioritized design requirements describe looks/design of product.Involves benchmarking – comparing product’s performance with competitor’s products.Setting targets for improvements and for achieving competitive edge.Part Planning :Translating product requirement specifications into part of characteristics.For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc.Process Planning :Translating part characteristics into an effective and efficient process.The ability to deliver six sigma quality should be maximized.Production Planning :Translating process into manufacturing or service delivery methods.In this step too, ability to deliver six sigma quality should be improved.
Product planning :Translating what customer wants or needs into set of prioritized design requirements.Prioritized design requirements describe looks/design of product.Involves benchmarking – comparing product’s performance with competitor’s products.Setting targets for improvements and for achieving competitive edge.
Translating what customer wants or needs into set of prioritized design requirements.
Prioritized design requirements describe looks/design of product.
Involves benchmarking – comparing product’s performance with competitor’s products.
Setting targets for improvements and for achieving competitive edge.
Part Planning :Translating product requirement specifications into part of characteristics.For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc.
Translating product requirement specifications into part of characteristics.
For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc.
Process Planning :Translating part characteristics into an effective and efficient process.The ability to deliver six sigma quality should be maximized.
Translating part characteristics into an effective and efficient process.
The ability to deliver six sigma quality should be maximized.
Production Planning :Translating process into manufacturing or service delivery methods.In this step too, ability to deliver six sigma quality should be improved.
Translating process into manufacturing or service delivery methods.
In this step too, ability to deliver six sigma quality should be improved.
Benefits of QFD :
Customer-focused –Very first step of QFD is marked by understanding and collecting all user requirements and expectations of product. The company does not focus on what they think customer wants, instead, they ask customers and focus on requirements and expectations put forward by them.Voice of Customer Competitor Analysis –House of Quality is significant tool that is used to compare voice of customer with design specifications.Structure and Documentation –Tools used in Quality Function Deployment are very well structured for capturing decisions made and lessons learned during development of product. This documentation can assist in development of future products.Low Development Cost –Since QFD focuses and pays close attention to customer requirements and expectations in initial steps itself, so the chances of late design changes or modifications are highly reduced, thereby resulting in low product development cost.Shorter Development Time –QFD process prevents wastage of time and resources as enough emphasis is made on customer needs and wants for the product. Since customer requirements are understood and developed in right way, so any development of non-value-added features or unnecessary functions is avoided, resulting in no time waste of product development team.
Customer-focused –Very first step of QFD is marked by understanding and collecting all user requirements and expectations of product. The company does not focus on what they think customer wants, instead, they ask customers and focus on requirements and expectations put forward by them.
Voice of Customer Competitor Analysis –House of Quality is significant tool that is used to compare voice of customer with design specifications.
Structure and Documentation –Tools used in Quality Function Deployment are very well structured for capturing decisions made and lessons learned during development of product. This documentation can assist in development of future products.
Low Development Cost –Since QFD focuses and pays close attention to customer requirements and expectations in initial steps itself, so the chances of late design changes or modifications are highly reduced, thereby resulting in low product development cost.
Shorter Development Time –QFD process prevents wastage of time and resources as enough emphasis is made on customer needs and wants for the product. Since customer requirements are understood and developed in right way, so any development of non-value-added features or unnecessary functions is avoided, resulting in no time waste of product development team.
A QFD Tool – House Of Quality (HOQ) :House of Quality or HOQ is conceptual map or matrix that provides an understanding of how customer requirements (WHATs) are related to various technical descriptors or design parameters (HOWs) and their priority levels. House of Quality is also known as Quality Matrix. The matrix gets its name from fact that it represents the shape of house.
A House of Quality has the following parts :
WHATs –Customer requirements and needs are listed.Importance Factor –The team rates each of customer requirements (WHATs) on scale of 1 to 5 based on their level of importance to the customer. Here, 1 denotes lowest level and 5 denotes highest level of importance to customer.HOWs or Ceiling –It comprises design features, technical descriptors and specifications of product aligned with customer requirements.Body –HOWs are ranked on basis of their correlation of satisfying each of listed WHATs. Body Ranking System used is set of symbols used to show Strong, Moderate, Weak or No correlation between HOWs and WHATs. Also, each of symbols represents numerical value.Roof –The roof indicates how design requirements(HOWs) are related to each other. Roof Ranking System uses set of symbols to represent different types of interactions – Strong Positive, Positive, None, Negative or Strong Negative.Competitor Comparison : This part focuses on comparing competitor’s product in regards to fulfilling WHATs. This is also measured on scale of 1 to 5 where 1 denotes Highly Dissatisfied and 5 denotes Highly Satisfied.Relative Importance –This part gives results by calculating total sum of each of HOWs by multiplying their Importance with value of Body Ranking symbol. This part is useful as it allows us to identify HOWs of products which require more attention and resources.Lower Level or Foundation –This part of HOQ lists more specific target values for technical specifications in relation to HOWs in order to satisfy customer requirements.
WHATs –Customer requirements and needs are listed.
Importance Factor –The team rates each of customer requirements (WHATs) on scale of 1 to 5 based on their level of importance to the customer. Here, 1 denotes lowest level and 5 denotes highest level of importance to customer.
HOWs or Ceiling –It comprises design features, technical descriptors and specifications of product aligned with customer requirements.
Body –HOWs are ranked on basis of their correlation of satisfying each of listed WHATs. Body Ranking System used is set of symbols used to show Strong, Moderate, Weak or No correlation between HOWs and WHATs. Also, each of symbols represents numerical value.
Roof –The roof indicates how design requirements(HOWs) are related to each other. Roof Ranking System uses set of symbols to represent different types of interactions – Strong Positive, Positive, None, Negative or Strong Negative.
Competitor Comparison : This part focuses on comparing competitor’s product in regards to fulfilling WHATs. This is also measured on scale of 1 to 5 where 1 denotes Highly Dissatisfied and 5 denotes Highly Satisfied.
Relative Importance –This part gives results by calculating total sum of each of HOWs by multiplying their Importance with value of Body Ranking symbol. This part is useful as it allows us to identify HOWs of products which require more attention and resources.
Lower Level or Foundation –This part of HOQ lists more specific target values for technical specifications in relation to HOWs in order to satisfy customer requirements.
Refer to the HOQ Diagram below :
The Roof Ranking System and Body Ranking System are as follows :
The formula for Computing Importance Weight and Relative Importance Weight :
Importance Weight,
= Sum of (Importance Factor * Body Ranking Symbol Value)
in column
Relative Importance Weight,
= (Importance Weight/ Total Importance Weight) * 100
For example, if column in HOWs is as follows :
Importance Weight (A)
= (2 * 9 + 3 * 3 + 3 * 1)
= 18 + 9 + 3
= 30
Similarly, Importance Weight of other technical requirements is calculated.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between Verification and Validation
Unit Testing | Software Testing
Software Testing | Basics
System Testing
Software Engineering | Classical Waterfall Model
Software Engineering | Seven Principles of software testing
Software Requirement Specification (SRS) Format
Software Engineering | Integration Testing
Difference between Spring and Spring Boot
Software Testing Life Cycle (STLC)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 307,
"s": 52,
"text": "Quality Function Deployment (QFD) is process or set of tools used to define the customer requirements for product and convert those requirements into engineering specifications and plans such that the customer requirements for that product are satisfied."
},
{
"code": null,
"e": 388,
"s": 307,
"text": "QFD was developed in late 1960s by Japanese Planning Specialist named Yoji Akao."
},
{
"code": null,
"e": 600,
"s": 388,
"text": "QFD aims at translating Voice of Customer into measurable and detailed design targets and then drives them from the assembly level down through sub-assembly level, component level, and production process levels."
},
{
"code": null,
"e": 798,
"s": 600,
"text": "QFD helps to achieve structured planning of product by enabling development team to clearly specify customer needs and expectations of product and then evaluate each part of product systematically."
},
{
"code": null,
"e": 817,
"s": 798,
"text": "Key steps in QFD :"
},
{
"code": null,
"e": 1675,
"s": 817,
"text": "Product planning :Translating what customer wants or needs into set of prioritized design requirements.Prioritized design requirements describe looks/design of product.Involves benchmarking – comparing product’s performance with competitor’s products.Setting targets for improvements and for achieving competitive edge.Part Planning :Translating product requirement specifications into part of characteristics.For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc.Process Planning :Translating part characteristics into an effective and efficient process.The ability to deliver six sigma quality should be maximized.Production Planning :Translating process into manufacturing or service delivery methods.In this step too, ability to deliver six sigma quality should be improved."
},
{
"code": null,
"e": 1995,
"s": 1675,
"text": "Product planning :Translating what customer wants or needs into set of prioritized design requirements.Prioritized design requirements describe looks/design of product.Involves benchmarking – comparing product’s performance with competitor’s products.Setting targets for improvements and for achieving competitive edge."
},
{
"code": null,
"e": 2081,
"s": 1995,
"text": "Translating what customer wants or needs into set of prioritized design requirements."
},
{
"code": null,
"e": 2147,
"s": 2081,
"text": "Prioritized design requirements describe looks/design of product."
},
{
"code": null,
"e": 2231,
"s": 2147,
"text": "Involves benchmarking – comparing product’s performance with competitor’s products."
},
{
"code": null,
"e": 2300,
"s": 2231,
"text": "Setting targets for improvements and for achieving competitive edge."
},
{
"code": null,
"e": 2525,
"s": 2300,
"text": "Part Planning :Translating product requirement specifications into part of characteristics.For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc."
},
{
"code": null,
"e": 2602,
"s": 2525,
"text": "Translating product requirement specifications into part of characteristics."
},
{
"code": null,
"e": 2736,
"s": 2602,
"text": "For example, if requirement is that product should be portable, then characteristics could be light-weight, small size, compact, etc."
},
{
"code": null,
"e": 2889,
"s": 2736,
"text": "Process Planning :Translating part characteristics into an effective and efficient process.The ability to deliver six sigma quality should be maximized."
},
{
"code": null,
"e": 2963,
"s": 2889,
"text": "Translating part characteristics into an effective and efficient process."
},
{
"code": null,
"e": 3025,
"s": 2963,
"text": "The ability to deliver six sigma quality should be maximized."
},
{
"code": null,
"e": 3188,
"s": 3025,
"text": "Production Planning :Translating process into manufacturing or service delivery methods.In this step too, ability to deliver six sigma quality should be improved."
},
{
"code": null,
"e": 3256,
"s": 3188,
"text": "Translating process into manufacturing or service delivery methods."
},
{
"code": null,
"e": 3331,
"s": 3256,
"text": "In this step too, ability to deliver six sigma quality should be improved."
},
{
"code": null,
"e": 3349,
"s": 3331,
"text": "Benefits of QFD :"
},
{
"code": null,
"e": 4638,
"s": 3349,
"text": "Customer-focused –Very first step of QFD is marked by understanding and collecting all user requirements and expectations of product. The company does not focus on what they think customer wants, instead, they ask customers and focus on requirements and expectations put forward by them.Voice of Customer Competitor Analysis –House of Quality is significant tool that is used to compare voice of customer with design specifications.Structure and Documentation –Tools used in Quality Function Deployment are very well structured for capturing decisions made and lessons learned during development of product. This documentation can assist in development of future products.Low Development Cost –Since QFD focuses and pays close attention to customer requirements and expectations in initial steps itself, so the chances of late design changes or modifications are highly reduced, thereby resulting in low product development cost.Shorter Development Time –QFD process prevents wastage of time and resources as enough emphasis is made on customer needs and wants for the product. Since customer requirements are understood and developed in right way, so any development of non-value-added features or unnecessary functions is avoided, resulting in no time waste of product development team."
},
{
"code": null,
"e": 4926,
"s": 4638,
"text": "Customer-focused –Very first step of QFD is marked by understanding and collecting all user requirements and expectations of product. The company does not focus on what they think customer wants, instead, they ask customers and focus on requirements and expectations put forward by them."
},
{
"code": null,
"e": 5072,
"s": 4926,
"text": "Voice of Customer Competitor Analysis –House of Quality is significant tool that is used to compare voice of customer with design specifications."
},
{
"code": null,
"e": 5313,
"s": 5072,
"text": "Structure and Documentation –Tools used in Quality Function Deployment are very well structured for capturing decisions made and lessons learned during development of product. This documentation can assist in development of future products."
},
{
"code": null,
"e": 5571,
"s": 5313,
"text": "Low Development Cost –Since QFD focuses and pays close attention to customer requirements and expectations in initial steps itself, so the chances of late design changes or modifications are highly reduced, thereby resulting in low product development cost."
},
{
"code": null,
"e": 5931,
"s": 5571,
"text": "Shorter Development Time –QFD process prevents wastage of time and resources as enough emphasis is made on customer needs and wants for the product. Since customer requirements are understood and developed in right way, so any development of non-value-added features or unnecessary functions is avoided, resulting in no time waste of product development team."
},
{
"code": null,
"e": 6312,
"s": 5931,
"text": "A QFD Tool – House Of Quality (HOQ) :House of Quality or HOQ is conceptual map or matrix that provides an understanding of how customer requirements (WHATs) are related to various technical descriptors or design parameters (HOWs) and their priority levels. House of Quality is also known as Quality Matrix. The matrix gets its name from fact that it represents the shape of house."
},
{
"code": null,
"e": 6357,
"s": 6312,
"text": "A House of Quality has the following parts :"
},
{
"code": null,
"e": 7902,
"s": 6357,
"text": "WHATs –Customer requirements and needs are listed.Importance Factor –The team rates each of customer requirements (WHATs) on scale of 1 to 5 based on their level of importance to the customer. Here, 1 denotes lowest level and 5 denotes highest level of importance to customer.HOWs or Ceiling –It comprises design features, technical descriptors and specifications of product aligned with customer requirements.Body –HOWs are ranked on basis of their correlation of satisfying each of listed WHATs. Body Ranking System used is set of symbols used to show Strong, Moderate, Weak or No correlation between HOWs and WHATs. Also, each of symbols represents numerical value.Roof –The roof indicates how design requirements(HOWs) are related to each other. Roof Ranking System uses set of symbols to represent different types of interactions – Strong Positive, Positive, None, Negative or Strong Negative.Competitor Comparison : This part focuses on comparing competitor’s product in regards to fulfilling WHATs. This is also measured on scale of 1 to 5 where 1 denotes Highly Dissatisfied and 5 denotes Highly Satisfied.Relative Importance –This part gives results by calculating total sum of each of HOWs by multiplying their Importance with value of Body Ranking symbol. This part is useful as it allows us to identify HOWs of products which require more attention and resources.Lower Level or Foundation –This part of HOQ lists more specific target values for technical specifications in relation to HOWs in order to satisfy customer requirements."
},
{
"code": null,
"e": 7953,
"s": 7902,
"text": "WHATs –Customer requirements and needs are listed."
},
{
"code": null,
"e": 8180,
"s": 7953,
"text": "Importance Factor –The team rates each of customer requirements (WHATs) on scale of 1 to 5 based on their level of importance to the customer. Here, 1 denotes lowest level and 5 denotes highest level of importance to customer."
},
{
"code": null,
"e": 8315,
"s": 8180,
"text": "HOWs or Ceiling –It comprises design features, technical descriptors and specifications of product aligned with customer requirements."
},
{
"code": null,
"e": 8574,
"s": 8315,
"text": "Body –HOWs are ranked on basis of their correlation of satisfying each of listed WHATs. Body Ranking System used is set of symbols used to show Strong, Moderate, Weak or No correlation between HOWs and WHATs. Also, each of symbols represents numerical value."
},
{
"code": null,
"e": 8805,
"s": 8574,
"text": "Roof –The roof indicates how design requirements(HOWs) are related to each other. Roof Ranking System uses set of symbols to represent different types of interactions – Strong Positive, Positive, None, Negative or Strong Negative."
},
{
"code": null,
"e": 9022,
"s": 8805,
"text": "Competitor Comparison : This part focuses on comparing competitor’s product in regards to fulfilling WHATs. This is also measured on scale of 1 to 5 where 1 denotes Highly Dissatisfied and 5 denotes Highly Satisfied."
},
{
"code": null,
"e": 9284,
"s": 9022,
"text": "Relative Importance –This part gives results by calculating total sum of each of HOWs by multiplying their Importance with value of Body Ranking symbol. This part is useful as it allows us to identify HOWs of products which require more attention and resources."
},
{
"code": null,
"e": 9454,
"s": 9284,
"text": "Lower Level or Foundation –This part of HOQ lists more specific target values for technical specifications in relation to HOWs in order to satisfy customer requirements."
},
{
"code": null,
"e": 9487,
"s": 9454,
"text": "Refer to the HOQ Diagram below :"
},
{
"code": null,
"e": 9552,
"s": 9487,
"text": "The Roof Ranking System and Body Ranking System are as follows :"
},
{
"code": null,
"e": 9629,
"s": 9552,
"text": "The formula for Computing Importance Weight and Relative Importance Weight :"
},
{
"code": null,
"e": 9707,
"s": 9629,
"text": "Importance Weight, \n= Sum of (Importance Factor * Body Ranking Symbol Value) "
},
{
"code": null,
"e": 9717,
"s": 9707,
"text": "in column"
},
{
"code": null,
"e": 9800,
"s": 9717,
"text": "Relative Importance Weight, \n= (Importance Weight/ Total Importance Weight) * 100 "
},
{
"code": null,
"e": 9847,
"s": 9800,
"text": "For example, if column in HOWs is as follows :"
},
{
"code": null,
"e": 9917,
"s": 9847,
"text": "Importance Weight (A) \n= (2 * 9 + 3 * 3 + 3 * 1) \n= 18 + 9 + 3 \n= 30 "
},
{
"code": null,
"e": 9993,
"s": 9917,
"text": "Similarly, Importance Weight of other technical requirements is calculated."
},
{
"code": null,
"e": 10014,
"s": 9993,
"text": "Software Engineering"
},
{
"code": null,
"e": 10112,
"s": 10014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10160,
"s": 10112,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 10192,
"s": 10160,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 10218,
"s": 10192,
"text": "Software Testing | Basics"
},
{
"code": null,
"e": 10233,
"s": 10218,
"text": "System Testing"
},
{
"code": null,
"e": 10282,
"s": 10233,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 10342,
"s": 10282,
"text": "Software Engineering | Seven Principles of software testing"
},
{
"code": null,
"e": 10390,
"s": 10342,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 10433,
"s": 10390,
"text": "Software Engineering | Integration Testing"
},
{
"code": null,
"e": 10475,
"s": 10433,
"text": "Difference between Spring and Spring Boot"
}
] |
Operational Amplifier (op-amp) in Digital Electronics
|
10 Feb, 2021
An amplifier is a device that increases the strength of the input signal. It can be Voltage amplifiers, whose input is some voltage and output is also voltage but amplified. Current amplifier, whose input is some current and output is also current but amplified.
Block diagram of an op-amp
Transconductance amplifier, whose input is some voltage and output is the current.
Transimpedance amplifier, whose input is some current and output is the voltage.
An operational amplifier (or, op-amp) is a voltage amplification, three-terminal electronic device, having two input terminals namely Inverting terminal (marked by ‘-‘ sign in diagrams) and a Non-inverting terminal(marked by ‘+’ sign in diagrams), and the third terminal is the output terminal. Gain (“A”) of the op-amp = output signal/input signal
Different configurations of op-amp:
Open Loop Configuration – In this configuration, the op-amp does not have any feedback. Ideally, it has an infinite open-loop gain(practically hundreds of thousands of times larger than the potential difference between its input terminals).
#Inverting Mode:
Inverting open loop op-amp
#Non-inverting Mode:
Non-inverting open loop op-amp
Closed Loop Configuration – In this configuration of the op-amp, negative feedback is used i.e., a portion of the output voltage is applied back to the inverting input. This feedback greatly reduces the gain of the op-amp as compared to open-loop gain. Thus, it is a kind of controlled way of amplification.
#Inverting Mode:
Inverting closed loop op-amp
#Non-inverting Mode:
Non-inverting closed loop op-amp
Characteristic of an ideal op-amp –
Open Loop gain: Ideally op-amp should have an infinite open-loop gain (practically it is hundreds of thousands of times larger than the potential difference between its input terminals).
Input impedance or resistance: Ideally op-amp should have infinite input resistance (practically it should be very high).
Output impedance or resistance: Ideally op-amp should have zero output resistance (practically it should be very low).
Bandwidth: Ideally op-amp should have infinite bandwidth (practically it is limited).
CMRR: Ideally op-amp should have infinite CMRR, Common Mode Rejection Ratio so that common noise voltage in the output becomes zero.
Slew Rate: Ideally op-amp should have infinite SR, slew rate so that any change in the input voltage simultaneously changes the output voltage.
Basic terminologies of an op-amp –
1. Slew Rate: The Slew rate (SR) of an op-amp is defined as the maximum rate of change of output voltage per unit of time. It is represented as volts per microsecond ( V/μs).
SR = (dVo / dt) |max
2. Output Offset Voltage: Output of the op-amp should be ideally zero when the voltage difference between the inputs is zero but, practically the output is non-zero, there is a voltage of very small magnitude. This unwanted voltage at the output side when no input is given is called Output Offset Voltage.
3. Input Offset Current: Magnitude of the difference of current entering inverting and non-inverting terminals, when no input voltage is given to op-amp.
Io = |Ib1-Ib2|;
Io-Input Offset Current, Ib1 &
Ib2-current at input terminals
4. Input Bias Current:
I(bias) = (Ib1+Ib2)/2
5. Input Offset Voltage: It is the voltage applied deliberately either at inverting or non-inverting terminal of an op-amp to nullify the effect of Output Offset Voltage.
V(Input Offset Voltage) = 0 (ideally)
V(Input Offset Voltage) = -V(Output Offset Voltage) (practically)
6. Common Mode Rejection Ratio (CMRR): It is the ratio between the differential mode gain (when the different signals are applied to both inputs terminals) to the common-mode gain(when the signal is applied to just one of the input terminals).
CMRR = |(differential mode gain) / (common mode gain)|
7. Supply Voltage Rejection Ratio (SVRR): It is defined as the ratio of change in input offset voltage, Vio of an op-amp to change in the supply voltage, V.
SVRR = ΔVio / ΔV
Application – It can be used as:
Inverting and Non-inverting adder,
Subtractor,
Integrator,
Differentiator,
Logarithmic amplifier etc.
sanju6890
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Feb, 2021"
},
{
"code": null,
"e": 315,
"s": 52,
"text": "An amplifier is a device that increases the strength of the input signal. It can be Voltage amplifiers, whose input is some voltage and output is also voltage but amplified. Current amplifier, whose input is some current and output is also current but amplified."
},
{
"code": null,
"e": 342,
"s": 315,
"text": "Block diagram of an op-amp"
},
{
"code": null,
"e": 425,
"s": 342,
"text": "Transconductance amplifier, whose input is some voltage and output is the current."
},
{
"code": null,
"e": 506,
"s": 425,
"text": "Transimpedance amplifier, whose input is some current and output is the voltage."
},
{
"code": null,
"e": 856,
"s": 506,
"text": "An operational amplifier (or, op-amp) is a voltage amplification, three-terminal electronic device, having two input terminals namely Inverting terminal (marked by ‘-‘ sign in diagrams) and a Non-inverting terminal(marked by ‘+’ sign in diagrams), and the third terminal is the output terminal. Gain (“A”) of the op-amp = output signal/input signal "
},
{
"code": null,
"e": 893,
"s": 856,
"text": "Different configurations of op-amp: "
},
{
"code": null,
"e": 1134,
"s": 893,
"text": "Open Loop Configuration – In this configuration, the op-amp does not have any feedback. Ideally, it has an infinite open-loop gain(practically hundreds of thousands of times larger than the potential difference between its input terminals)."
},
{
"code": null,
"e": 1152,
"s": 1134,
"text": "#Inverting Mode: "
},
{
"code": null,
"e": 1180,
"s": 1152,
"text": "Inverting open loop op-amp "
},
{
"code": null,
"e": 1203,
"s": 1180,
"text": "#Non-inverting Mode: "
},
{
"code": null,
"e": 1234,
"s": 1203,
"text": "Non-inverting open loop op-amp"
},
{
"code": null,
"e": 1543,
"s": 1234,
"text": "Closed Loop Configuration – In this configuration of the op-amp, negative feedback is used i.e., a portion of the output voltage is applied back to the inverting input. This feedback greatly reduces the gain of the op-amp as compared to open-loop gain. Thus, it is a kind of controlled way of amplification. "
},
{
"code": null,
"e": 1560,
"s": 1543,
"text": "#Inverting Mode:"
},
{
"code": null,
"e": 1589,
"s": 1560,
"text": "Inverting closed loop op-amp"
},
{
"code": null,
"e": 1611,
"s": 1589,
"text": "#Non-inverting Mode: "
},
{
"code": null,
"e": 1644,
"s": 1611,
"text": "Non-inverting closed loop op-amp"
},
{
"code": null,
"e": 1681,
"s": 1644,
"text": "Characteristic of an ideal op-amp – "
},
{
"code": null,
"e": 1868,
"s": 1681,
"text": "Open Loop gain: Ideally op-amp should have an infinite open-loop gain (practically it is hundreds of thousands of times larger than the potential difference between its input terminals)."
},
{
"code": null,
"e": 1990,
"s": 1868,
"text": "Input impedance or resistance: Ideally op-amp should have infinite input resistance (practically it should be very high)."
},
{
"code": null,
"e": 2109,
"s": 1990,
"text": "Output impedance or resistance: Ideally op-amp should have zero output resistance (practically it should be very low)."
},
{
"code": null,
"e": 2195,
"s": 2109,
"text": "Bandwidth: Ideally op-amp should have infinite bandwidth (practically it is limited)."
},
{
"code": null,
"e": 2328,
"s": 2195,
"text": "CMRR: Ideally op-amp should have infinite CMRR, Common Mode Rejection Ratio so that common noise voltage in the output becomes zero."
},
{
"code": null,
"e": 2472,
"s": 2328,
"text": "Slew Rate: Ideally op-amp should have infinite SR, slew rate so that any change in the input voltage simultaneously changes the output voltage."
},
{
"code": null,
"e": 2508,
"s": 2472,
"text": "Basic terminologies of an op-amp – "
},
{
"code": null,
"e": 2683,
"s": 2508,
"text": "1. Slew Rate: The Slew rate (SR) of an op-amp is defined as the maximum rate of change of output voltage per unit of time. It is represented as volts per microsecond ( V/μs)."
},
{
"code": null,
"e": 2704,
"s": 2683,
"text": "SR = (dVo / dt) |max"
},
{
"code": null,
"e": 3011,
"s": 2704,
"text": "2. Output Offset Voltage: Output of the op-amp should be ideally zero when the voltage difference between the inputs is zero but, practically the output is non-zero, there is a voltage of very small magnitude. This unwanted voltage at the output side when no input is given is called Output Offset Voltage."
},
{
"code": null,
"e": 3166,
"s": 3011,
"text": "3. Input Offset Current: Magnitude of the difference of current entering inverting and non-inverting terminals, when no input voltage is given to op-amp. "
},
{
"code": null,
"e": 3247,
"s": 3166,
"text": "Io = |Ib1-Ib2|; \nIo-Input Offset Current, Ib1 & \nIb2-current at input terminals "
},
{
"code": null,
"e": 3271,
"s": 3247,
"text": "4. Input Bias Current: "
},
{
"code": null,
"e": 3295,
"s": 3271,
"text": " I(bias) = (Ib1+Ib2)/2 "
},
{
"code": null,
"e": 3467,
"s": 3295,
"text": "5. Input Offset Voltage: It is the voltage applied deliberately either at inverting or non-inverting terminal of an op-amp to nullify the effect of Output Offset Voltage. "
},
{
"code": null,
"e": 3573,
"s": 3467,
"text": " V(Input Offset Voltage) = 0 (ideally)\nV(Input Offset Voltage) = -V(Output Offset Voltage) (practically) "
},
{
"code": null,
"e": 3818,
"s": 3573,
"text": "6. Common Mode Rejection Ratio (CMRR): It is the ratio between the differential mode gain (when the different signals are applied to both inputs terminals) to the common-mode gain(when the signal is applied to just one of the input terminals). "
},
{
"code": null,
"e": 3874,
"s": 3818,
"text": "CMRR = |(differential mode gain) / (common mode gain)| "
},
{
"code": null,
"e": 4031,
"s": 3874,
"text": "7. Supply Voltage Rejection Ratio (SVRR): It is defined as the ratio of change in input offset voltage, Vio of an op-amp to change in the supply voltage, V."
},
{
"code": null,
"e": 4048,
"s": 4031,
"text": "SVRR = ΔVio / ΔV"
},
{
"code": null,
"e": 4082,
"s": 4048,
"text": "Application – It can be used as: "
},
{
"code": null,
"e": 4117,
"s": 4082,
"text": "Inverting and Non-inverting adder,"
},
{
"code": null,
"e": 4129,
"s": 4117,
"text": "Subtractor,"
},
{
"code": null,
"e": 4141,
"s": 4129,
"text": "Integrator,"
},
{
"code": null,
"e": 4157,
"s": 4141,
"text": "Differentiator,"
},
{
"code": null,
"e": 4184,
"s": 4157,
"text": "Logarithmic amplifier etc."
},
{
"code": null,
"e": 4194,
"s": 4184,
"text": "sanju6890"
},
{
"code": null,
"e": 4229,
"s": 4194,
"text": "Digital Electronics & Logic Design"
}
] |
Sum of all the prime numbers in a given range
|
21 Sep, 2021
Given a range [l, r], the task is to find the sum of all the prime numbers within that range.Examples:
Input : l=1 and r=6
Output : 10
Input : l=4 and r=13
Output : 36
Approach 1: (Naive Approach) Iterate the loop from ‘l’ to ‘r’ and add all the numbers which are prime.Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ Program to compute sum of prime number// in a given range#include <iostream>using namespace std; // Method to compute the prime number// Time Complexity is O(sqrt(N))bool checkPrime(int numberToCheck){ if(numberToCheck == 1) { return false; } for (int i = 2; i*i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true;} // Method to iterate the loop from l to r// If the current number is prime, sum the valueint primeSum(int l, int r){ int sum = 0; for (int i = r; i >= l; i--) { // Check for prime bool isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum;}// Time Complexity is O(r x sqrt(N)) //Driver codeint main(){ int l = 4, r = 13; // Call the method with l and r cout << primeSum(l, r);}
// Java Program to compute sum of prime number// in a given rangepublic class GFG { // Method to compute the prime number // Time Complexity is O(sqrt(N)) static boolean checkPrime(int numberToCheck) { if(numberToCheck == 1) { return false; } for (int i = 2; i*i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true; } // Method to iterate the loop from l to r // If prime number detects, sum the value static int primeSum(int l, int r) { int sum = 0; for (int i = r; i >= l; i--) { // Check for prime boolean isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum; } // Time Complexity is O(r x sqrt(N)) // Driver code public static void main(String[] args) { int l = 4, r = 13; // Call the method with l and r System.out.println(primeSum(l, r)); }}
# Python3 Program to compute sum# of prime number in a given range # from math lib import sqrt methodfrom math import sqrt # Function to compute the prime number# Time Complexity is O(sqrt(N))def checkPrime(numberToCheck) : if numberToCheck == 1 : return False for i in range(2, int(sqrt(numberToCheck)) + 1) : if numberToCheck % i == 0 : return False return True # Function to iterate the loop# from l to r. If the current# number is prime, sum the valuedef primeSum(l, r) : sum = 0 for i in range(r, (l - 1), -1) : # Check for prime isPrime = checkPrime(i) if (isPrime) : # Sum the prime number sum += i return sum # Time Complexity is O(r x sqrt(N)) # Driver code if __name__ == "__main__" : l, r = 4, 13 # Call the function with l and r print(primeSum(l, r)) # This code is contributed# by ANKITRAI1
// C# Program to compute sum// of prime number in a given rangeusing System; class GFG{ // Method to compute the prime// number Time Complexity is O(sqrt(N))static bool checkPrime(int numberToCheck){ if(numberToCheck == 1) { return false; } for (int i = 2; i * i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true;} // Method to iterate the loop from l to r// If prime number detects, sum the valuestatic int primeSum(int l, int r){ int sum = 0; for (int i = r; i >= l; i--) { // Check for prime bool isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum;}// Time Complexity is O(r x sqrt(N)) // Driver codepublic static void Main(){ int l = 4, r = 13; // Call the method with l and r Console.Write(primeSum(l, r));}} // This code is contributed// by ChitraNayal
<?php// PHP Program to compute sum of// prime number in a given range // Method to compute the prime number// Time Complexity is O(sqrt(N))function checkPrime($numberToCheck){ if($numberToCheck == 1) { return false; } for ($i = 2; $i * $i <= $numberToCheck; $i++) { if ($numberToCheck % $i == 0) { return false; } } return true;} // Method to iterate the loop from// l to r. If the current number// is prime, sum the valuefunction primeSum($l, $r){ $sum = 0; for ($i = $r; $i >= $l; $i--) { // Check for prime $isPrime = checkPrime($i); if ($isPrime) { // Sum the prime number $sum = $sum + $i; } } return $sum;} // Time Complexity is O(r x sqrt(N)) // Driver code$l = 4; $r = 13; // Call the method with l and recho primeSum($l, $r); // This code is contributed by ajit?>
<script> // Javascript Program to compute sum // of prime number in a given range // Method to compute the prime // number Time Complexity is O(sqrt(N)) function checkPrime(numberToCheck) { if(numberToCheck == 1) { return false; } for (let i = 2; i * i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true; } // Method to iterate the loop from l to r // If prime number detects, sum the value function primeSum(l, r) { let sum = 0; for (let i = r; i >= l; i--) { // Check for prime let isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum; } let l = 4, r = 13; // Call the method with l and r document.write(primeSum(l, r)); </script>
Output:
36
Time Complexity: Space Complexity: Approach 2: (Dynamic Programming)
Declare an array dp and arrFill the array arr to 0Iterate the loop till sqrt(N) and if arr[i] = 0 (marked as prime), then set all of it’s multiples as non-prime by marking the respective location as 1Update the dp array with the running prime numbers sum, where each location ‘dp[i]’ holds the sum of all the prime numbers withing the range [1, i]
Declare an array dp and arr
Fill the array arr to 0
Iterate the loop till sqrt(N) and if arr[i] = 0 (marked as prime), then set all of it’s multiples as non-prime by marking the respective location as 1
Update the dp array with the running prime numbers sum, where each location ‘dp[i]’ holds the sum of all the prime numbers withing the range [1, i]
Image Representation
C++
Java
Python 3
C#
Javascript
// C++ Program to compute sum of prime number// in a given range#include <bits/stdc++.h>using namespace std; // Suppose the constraint is N<=1000const int N = 1000; // Declare an array for dynamic approachint dp[N + 1]; // Method to compute the arrayvoid sieve(){ // Declare an extra array as arr int arr[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; // Here, dp[i] is the sum of all the prime numbers // within the range [1, i] dp[i] = runningPrimeSum; }} // Driver codeint main(){ int l = 4, r = 13; // Compute dp sieve(); cout << dp[r] - dp[l - 1]; return 0;} // This code is contributed by divyesh072019
// Java Program to compute sum of prime number// in a given rangepublic class GFG { // Suppose the constraint is N<=1000 static int N = 1000; // Declare an array for dynamic approach static long dp[] = new long[N + 1]; // Method to compute the array static void sieve() { // Declare an extra array as arr int arr[] = new int[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= Math.sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code public static void main(String[] args) { int l = 4, r = 13; // Compute dp sieve(); System.out.println(dp[r] - dp[l - 1]); }}
# Python3 Program to compute sum of prime number# in a given rangeimport math # for sqrt and ceil function # Suppose the constraint is N<=1000N = 1000 # Declare an array for dynamic approachdp = [0] * (N + 1) # Method to compute the arraydef sieve(): # Declare an extra array as array array = [0] * (N + 1) array[0] = 1 array[1] = 1 # Iterate the loop till sqrt(N) # Time Complexity is O(log(n) X sqrt(N)) for i in range(2, math.ceil(math.sqrt(N) + 1)): # if ith element of arr is 0 # i.e. marked as prime if array[i] == 0: # mark all of it's multiples till N as # non-prime by setting the locations to 1 for j in range(i * i, N + 1, i): array[j] = 1 runningPrimeSum = 0 # Update the array 'dp' with the running sum # of prime numbers within the range [1, N] # Time Complexity is O(n) for i in range(1, N + 1): if array[i] == 0: runningPrimeSum += i # Here, dp[i] is the sum of all the prime numbers # within the range [1, i] dp[i] = runningPrimeSum # Driver Codel = 4r = 13sieve()print(dp[r] - dp[l - 1]) # This code is contributed by Vivek Kumar Singh
// C# Program to compute sum of prime number// in a given rangeusing System;public class GFG { // Suppose the constraint is N<=1000 static int N = 1000; // Declare an array for dynamic approach static long[] dp = new long[N + 1]; // Method to compute the array static void sieve() { // Declare an extra array as arr int []arr = new int[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= Math.Sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code public static void Main() { int l = 4, r = 13; // Compute dp sieve(); Console.WriteLine(dp[r] - dp[l - 1]); }} /*This code is contributed by 29AjayKumar*/
<script>// Javascript Program to compute sum of prime number// in a given range // Suppose the constraint is N<=1000 let N = 1000; // Declare an array for dynamic approach let dp=new Array(N+1); for(let i=0;i<dp.length;i++) { dp[i]=0; } // Method to compute the array function sieve() { let arr=new Array(N+1); for(let i=0;i<arr.length;i++) { arr[i]=0; } arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (let i = 2; i <= Math.ceil(Math.sqrt(N)+1); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (let j = i * i; j <= N; j += i) arr[j] = 1; let runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (let i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code let l = 4, r = 13; // Compute dp sieve(); document.write(dp[r] - dp[l - 1]); // This code is contributed by avanitrachhadiya2155</script>
Output:
36
Time Complexity: Space Complexity:
ankthon
ukasp
jit_t
29AjayKumar
Vivekkumar Singh
divyeshrabadiya07
suresh07
avanitrachhadiya2155
saurabh1990aror
bunnyram19
simmytarika5
Prime Number
sieve
Technical Scripter 2018
Mathematical
Technical Scripter
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 157,
"s": 52,
"text": "Given a range [l, r], the task is to find the sum of all the prime numbers within that range.Examples: "
},
{
"code": null,
"e": 224,
"s": 157,
"text": "Input : l=1 and r=6\nOutput : 10\n\nInput : l=4 and r=13\nOutput : 36\n"
},
{
"code": null,
"e": 381,
"s": 226,
"text": "Approach 1: (Naive Approach) Iterate the loop from ‘l’ to ‘r’ and add all the numbers which are prime.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 385,
"s": 381,
"text": "C++"
},
{
"code": null,
"e": 390,
"s": 385,
"text": "Java"
},
{
"code": null,
"e": 399,
"s": 390,
"text": "Python 3"
},
{
"code": null,
"e": 402,
"s": 399,
"text": "C#"
},
{
"code": null,
"e": 406,
"s": 402,
"text": "PHP"
},
{
"code": null,
"e": 417,
"s": 406,
"text": "Javascript"
},
{
"code": "// C++ Program to compute sum of prime number// in a given range#include <iostream>using namespace std; // Method to compute the prime number// Time Complexity is O(sqrt(N))bool checkPrime(int numberToCheck){ if(numberToCheck == 1) { return false; } for (int i = 2; i*i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true;} // Method to iterate the loop from l to r// If the current number is prime, sum the valueint primeSum(int l, int r){ int sum = 0; for (int i = r; i >= l; i--) { // Check for prime bool isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum;}// Time Complexity is O(r x sqrt(N)) //Driver codeint main(){ int l = 4, r = 13; // Call the method with l and r cout << primeSum(l, r);}",
"e": 1313,
"s": 417,
"text": null
},
{
"code": "// Java Program to compute sum of prime number// in a given rangepublic class GFG { // Method to compute the prime number // Time Complexity is O(sqrt(N)) static boolean checkPrime(int numberToCheck) { if(numberToCheck == 1) { return false; } for (int i = 2; i*i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true; } // Method to iterate the loop from l to r // If prime number detects, sum the value static int primeSum(int l, int r) { int sum = 0; for (int i = r; i >= l; i--) { // Check for prime boolean isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum; } // Time Complexity is O(r x sqrt(N)) // Driver code public static void main(String[] args) { int l = 4, r = 13; // Call the method with l and r System.out.println(primeSum(l, r)); }}",
"e": 2392,
"s": 1313,
"text": null
},
{
"code": "# Python3 Program to compute sum# of prime number in a given range # from math lib import sqrt methodfrom math import sqrt # Function to compute the prime number# Time Complexity is O(sqrt(N))def checkPrime(numberToCheck) : if numberToCheck == 1 : return False for i in range(2, int(sqrt(numberToCheck)) + 1) : if numberToCheck % i == 0 : return False return True # Function to iterate the loop# from l to r. If the current# number is prime, sum the valuedef primeSum(l, r) : sum = 0 for i in range(r, (l - 1), -1) : # Check for prime isPrime = checkPrime(i) if (isPrime) : # Sum the prime number sum += i return sum # Time Complexity is O(r x sqrt(N)) # Driver code if __name__ == \"__main__\" : l, r = 4, 13 # Call the function with l and r print(primeSum(l, r)) # This code is contributed# by ANKITRAI1",
"e": 3314,
"s": 2392,
"text": null
},
{
"code": "// C# Program to compute sum// of prime number in a given rangeusing System; class GFG{ // Method to compute the prime// number Time Complexity is O(sqrt(N))static bool checkPrime(int numberToCheck){ if(numberToCheck == 1) { return false; } for (int i = 2; i * i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true;} // Method to iterate the loop from l to r// If prime number detects, sum the valuestatic int primeSum(int l, int r){ int sum = 0; for (int i = r; i >= l; i--) { // Check for prime bool isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum;}// Time Complexity is O(r x sqrt(N)) // Driver codepublic static void Main(){ int l = 4, r = 13; // Call the method with l and r Console.Write(primeSum(l, r));}} // This code is contributed// by ChitraNayal",
"e": 4307,
"s": 3314,
"text": null
},
{
"code": "<?php// PHP Program to compute sum of// prime number in a given range // Method to compute the prime number// Time Complexity is O(sqrt(N))function checkPrime($numberToCheck){ if($numberToCheck == 1) { return false; } for ($i = 2; $i * $i <= $numberToCheck; $i++) { if ($numberToCheck % $i == 0) { return false; } } return true;} // Method to iterate the loop from// l to r. If the current number// is prime, sum the valuefunction primeSum($l, $r){ $sum = 0; for ($i = $r; $i >= $l; $i--) { // Check for prime $isPrime = checkPrime($i); if ($isPrime) { // Sum the prime number $sum = $sum + $i; } } return $sum;} // Time Complexity is O(r x sqrt(N)) // Driver code$l = 4; $r = 13; // Call the method with l and recho primeSum($l, $r); // This code is contributed by ajit?>",
"e": 5214,
"s": 4307,
"text": null
},
{
"code": "<script> // Javascript Program to compute sum // of prime number in a given range // Method to compute the prime // number Time Complexity is O(sqrt(N)) function checkPrime(numberToCheck) { if(numberToCheck == 1) { return false; } for (let i = 2; i * i <= numberToCheck; i++) { if (numberToCheck % i == 0) { return false; } } return true; } // Method to iterate the loop from l to r // If prime number detects, sum the value function primeSum(l, r) { let sum = 0; for (let i = r; i >= l; i--) { // Check for prime let isPrime = checkPrime(i); if (isPrime) { // Sum the prime number sum = sum + i; } } return sum; } let l = 4, r = 13; // Call the method with l and r document.write(primeSum(l, r)); </script>",
"e": 6210,
"s": 5214,
"text": null
},
{
"code": null,
"e": 6220,
"s": 6210,
"text": "Output: "
},
{
"code": null,
"e": 6223,
"s": 6220,
"text": "36"
},
{
"code": null,
"e": 6294,
"s": 6223,
"text": "Time Complexity: Space Complexity: Approach 2: (Dynamic Programming) "
},
{
"code": null,
"e": 6642,
"s": 6294,
"text": "Declare an array dp and arrFill the array arr to 0Iterate the loop till sqrt(N) and if arr[i] = 0 (marked as prime), then set all of it’s multiples as non-prime by marking the respective location as 1Update the dp array with the running prime numbers sum, where each location ‘dp[i]’ holds the sum of all the prime numbers withing the range [1, i]"
},
{
"code": null,
"e": 6670,
"s": 6642,
"text": "Declare an array dp and arr"
},
{
"code": null,
"e": 6694,
"s": 6670,
"text": "Fill the array arr to 0"
},
{
"code": null,
"e": 6845,
"s": 6694,
"text": "Iterate the loop till sqrt(N) and if arr[i] = 0 (marked as prime), then set all of it’s multiples as non-prime by marking the respective location as 1"
},
{
"code": null,
"e": 6993,
"s": 6845,
"text": "Update the dp array with the running prime numbers sum, where each location ‘dp[i]’ holds the sum of all the prime numbers withing the range [1, i]"
},
{
"code": null,
"e": 7016,
"s": 6993,
"text": "Image Representation "
},
{
"code": null,
"e": 7022,
"s": 7018,
"text": "C++"
},
{
"code": null,
"e": 7027,
"s": 7022,
"text": "Java"
},
{
"code": null,
"e": 7036,
"s": 7027,
"text": "Python 3"
},
{
"code": null,
"e": 7039,
"s": 7036,
"text": "C#"
},
{
"code": null,
"e": 7050,
"s": 7039,
"text": "Javascript"
},
{
"code": "// C++ Program to compute sum of prime number// in a given range#include <bits/stdc++.h>using namespace std; // Suppose the constraint is N<=1000const int N = 1000; // Declare an array for dynamic approachint dp[N + 1]; // Method to compute the arrayvoid sieve(){ // Declare an extra array as arr int arr[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; // Here, dp[i] is the sum of all the prime numbers // within the range [1, i] dp[i] = runningPrimeSum; }} // Driver codeint main(){ int l = 4, r = 13; // Compute dp sieve(); cout << dp[r] - dp[l - 1]; return 0;} // This code is contributed by divyesh072019",
"e": 8334,
"s": 7050,
"text": null
},
{
"code": "// Java Program to compute sum of prime number// in a given rangepublic class GFG { // Suppose the constraint is N<=1000 static int N = 1000; // Declare an array for dynamic approach static long dp[] = new long[N + 1]; // Method to compute the array static void sieve() { // Declare an extra array as arr int arr[] = new int[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= Math.sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code public static void main(String[] args) { int l = 4, r = 13; // Compute dp sieve(); System.out.println(dp[r] - dp[l - 1]); }}",
"e": 9774,
"s": 8334,
"text": null
},
{
"code": "# Python3 Program to compute sum of prime number# in a given rangeimport math # for sqrt and ceil function # Suppose the constraint is N<=1000N = 1000 # Declare an array for dynamic approachdp = [0] * (N + 1) # Method to compute the arraydef sieve(): # Declare an extra array as array array = [0] * (N + 1) array[0] = 1 array[1] = 1 # Iterate the loop till sqrt(N) # Time Complexity is O(log(n) X sqrt(N)) for i in range(2, math.ceil(math.sqrt(N) + 1)): # if ith element of arr is 0 # i.e. marked as prime if array[i] == 0: # mark all of it's multiples till N as # non-prime by setting the locations to 1 for j in range(i * i, N + 1, i): array[j] = 1 runningPrimeSum = 0 # Update the array 'dp' with the running sum # of prime numbers within the range [1, N] # Time Complexity is O(n) for i in range(1, N + 1): if array[i] == 0: runningPrimeSum += i # Here, dp[i] is the sum of all the prime numbers # within the range [1, i] dp[i] = runningPrimeSum # Driver Codel = 4r = 13sieve()print(dp[r] - dp[l - 1]) # This code is contributed by Vivek Kumar Singh",
"e": 11004,
"s": 9774,
"text": null
},
{
"code": "// C# Program to compute sum of prime number// in a given rangeusing System;public class GFG { // Suppose the constraint is N<=1000 static int N = 1000; // Declare an array for dynamic approach static long[] dp = new long[N + 1]; // Method to compute the array static void sieve() { // Declare an extra array as arr int []arr = new int[N + 1]; arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (int i = 2; i <= Math.Sqrt(N); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (int j = i * i; j <= N; j += i) arr[j] = 1; long runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (int i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code public static void Main() { int l = 4, r = 13; // Compute dp sieve(); Console.WriteLine(dp[r] - dp[l - 1]); }} /*This code is contributed by 29AjayKumar*/",
"e": 12487,
"s": 11004,
"text": null
},
{
"code": "<script>// Javascript Program to compute sum of prime number// in a given range // Suppose the constraint is N<=1000 let N = 1000; // Declare an array for dynamic approach let dp=new Array(N+1); for(let i=0;i<dp.length;i++) { dp[i]=0; } // Method to compute the array function sieve() { let arr=new Array(N+1); for(let i=0;i<arr.length;i++) { arr[i]=0; } arr[0] = 1; arr[1] = 1; // Iterate the loop till sqrt(n) // Time Complexity is O(log(n) X sqrt(n)) for (let i = 2; i <= Math.ceil(Math.sqrt(N)+1); i++) // if ith element of arr is 0 i.e. marked as prime if (arr[i] == 0) // mark all of it's multiples till N as non-prime // by setting the locations to 1 for (let j = i * i; j <= N; j += i) arr[j] = 1; let runningPrimeSum = 0; // Update the array 'dp' with the running sum // of prime numbers within the range [1, N] // Time Complexity is O(n) for (let i = 1; i <= N; i++) { if (arr[i] == 0) runningPrimeSum += i; //Here, dp[i] is the sum of all the prime numbers //within the range [1, i] dp[i] = runningPrimeSum; } } // Driver code let l = 4, r = 13; // Compute dp sieve(); document.write(dp[r] - dp[l - 1]); // This code is contributed by avanitrachhadiya2155</script>",
"e": 14024,
"s": 12487,
"text": null
},
{
"code": null,
"e": 14034,
"s": 14024,
"text": "Output: "
},
{
"code": null,
"e": 14037,
"s": 14034,
"text": "36"
},
{
"code": null,
"e": 14074,
"s": 14037,
"text": "Time Complexity: Space Complexity: "
},
{
"code": null,
"e": 14082,
"s": 14074,
"text": "ankthon"
},
{
"code": null,
"e": 14088,
"s": 14082,
"text": "ukasp"
},
{
"code": null,
"e": 14094,
"s": 14088,
"text": "jit_t"
},
{
"code": null,
"e": 14106,
"s": 14094,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14123,
"s": 14106,
"text": "Vivekkumar Singh"
},
{
"code": null,
"e": 14141,
"s": 14123,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 14150,
"s": 14141,
"text": "suresh07"
},
{
"code": null,
"e": 14171,
"s": 14150,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14187,
"s": 14171,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 14198,
"s": 14187,
"text": "bunnyram19"
},
{
"code": null,
"e": 14211,
"s": 14198,
"text": "simmytarika5"
},
{
"code": null,
"e": 14224,
"s": 14211,
"text": "Prime Number"
},
{
"code": null,
"e": 14230,
"s": 14224,
"text": "sieve"
},
{
"code": null,
"e": 14254,
"s": 14230,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 14267,
"s": 14254,
"text": "Mathematical"
},
{
"code": null,
"e": 14286,
"s": 14267,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14299,
"s": 14286,
"text": "Mathematical"
},
{
"code": null,
"e": 14312,
"s": 14299,
"text": "Prime Number"
},
{
"code": null,
"e": 14318,
"s": 14312,
"text": "sieve"
}
] |
How to Rotate and Scale images using PyGame ?
|
21 Apr, 2021
In this article, we are going to see how to Rotate and Scale the image. Image Scaling refers to the resizing of the original image and Image Rotation refers to the turning of an image with some angle. Rotations in the coordinate plane are counterclockwise. Let’s proceed with the methods used and the complete code to perform these tasks.
To scale the image we use the pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) method where we pass the image that we are going to scale and the default image size that we will set manually according to our need.
Example:
Image Used:
Python3
# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Scale the image to your needed sizeimage = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)
Output:
To rotate the image we use the pygame.transform.rotate(image, degree) method where we pass the image that we are going to rotate and the degree by which rotation is to be done.
Example:
Python3
# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Rotate the image by any degreeimage = pygame.transform.rotate(image, 180) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)
Output:
Let us see how to perform the Scaling and Rotation of an image given. We will set the default image size that is agreeable and the default image position where we want to see our image on the window screen. The same methods that are explained above will be used for scaling and rotation the image.
Example:
Python3
# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Scale the image to your needed sizeimage = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) # Rotate the image by any degreeimage = pygame.transform.rotate(image, 90) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)
Output:
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 393,
"s": 54,
"text": "In this article, we are going to see how to Rotate and Scale the image. Image Scaling refers to the resizing of the original image and Image Rotation refers to the turning of an image with some angle. Rotations in the coordinate plane are counterclockwise. Let’s proceed with the methods used and the complete code to perform these tasks."
},
{
"code": null,
"e": 608,
"s": 393,
"text": "To scale the image we use the pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) method where we pass the image that we are going to scale and the default image size that we will set manually according to our need. "
},
{
"code": null,
"e": 617,
"s": 608,
"text": "Example:"
},
{
"code": null,
"e": 629,
"s": 617,
"text": "Image Used:"
},
{
"code": null,
"e": 637,
"s": 629,
"text": "Python3"
},
{
"code": "# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Scale the image to your needed sizeimage = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)",
"e": 1475,
"s": 637,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Output:"
},
{
"code": null,
"e": 1661,
"s": 1483,
"text": "To rotate the image we use the pygame.transform.rotate(image, degree) method where we pass the image that we are going to rotate and the degree by which rotation is to be done. "
},
{
"code": null,
"e": 1670,
"s": 1661,
"text": "Example:"
},
{
"code": null,
"e": 1678,
"s": 1670,
"text": "Python3"
},
{
"code": "# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Rotate the image by any degreeimage = pygame.transform.rotate(image, 180) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)",
"e": 2497,
"s": 1678,
"text": null
},
{
"code": null,
"e": 2505,
"s": 2497,
"text": "Output:"
},
{
"code": null,
"e": 2805,
"s": 2505,
"text": "Let us see how to perform the Scaling and Rotation of an image given. We will set the default image size that is agreeable and the default image position where we want to see our image on the window screen. The same methods that are explained above will be used for scaling and rotation the image. "
},
{
"code": null,
"e": 2814,
"s": 2805,
"text": "Example:"
},
{
"code": null,
"e": 2822,
"s": 2814,
"text": "Python3"
},
{
"code": "# Import pygameimport pygame # Initialise pygamepygame.init() # Set window sizesize = width,height = 600, 600screen = pygame.display.set_mode(size) # Clockclock = pygame.time.Clock() # Load imageimage = pygame.image.load('gfg.png') # Set the size for the imageDEFAULT_IMAGE_SIZE = (200, 200) # Scale the image to your needed sizeimage = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE) # Rotate the image by any degreeimage = pygame.transform.rotate(image, 90) # Set a default positionDEFAULT_IMAGE_POSITION = (200,200) # Prepare loop conditionrunning = False # Event loopwhile not running: # Close window event for event in pygame.event.get(): if event.type == pygame.QUIT: running = True # Background Color screen.fill((0, 0, 0)) # Show the image screen.blit(image, DEFAULT_IMAGE_POSITION) # Part of event loop pygame.display.flip() clock.tick(30)",
"e": 3736,
"s": 2822,
"text": null
},
{
"code": null,
"e": 3744,
"s": 3736,
"text": "Output:"
},
{
"code": null,
"e": 3751,
"s": 3744,
"text": "Picked"
},
{
"code": null,
"e": 3765,
"s": 3751,
"text": "Python-PyGame"
},
{
"code": null,
"e": 3772,
"s": 3765,
"text": "Python"
}
] |
How to extend Interfaces in Java
|
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface extends another interface like a class implements an interface in interface inheritance.
A program that demonstrates extending interfaces in Java is given as follows:
Live Demo
interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}
This is funcA
This is funcB
Now let us understand the above program.
The interface A has an abstract method funcA(). The interface B extends the interface A and has an abstract method funcB(). The class C implements the interface B. A code snippet which demonstrates this is as follows:
interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}
}
In the method main() in class Demo, an object obj of class C is created. Then the methods funcA() and funcB() are called. A code snippet which demonstrates this is as follows:
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}
|
[
{
"code": null,
"e": 1418,
"s": 1187,
"text": "An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface extends another interface like a class implements an interface in interface inheritance."
},
{
"code": null,
"e": 1496,
"s": 1418,
"text": "A program that demonstrates extending interfaces in Java is given as follows:"
},
{
"code": null,
"e": 1507,
"s": 1496,
"text": " Live Demo"
},
{
"code": null,
"e": 1886,
"s": 1507,
"text": "interface A {\n void funcA();\n}\ninterface B extends A {\n void funcB();\n}\nclass C implements B {\n public void funcA() {\n System.out.println(\"This is funcA\");\n }\n public void funcB() {\n System.out.println(\"This is funcB\");\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n C obj = new C();\n obj.funcA();\n obj.funcB();\n }\n}"
},
{
"code": null,
"e": 1914,
"s": 1886,
"text": "This is funcA\nThis is funcB"
},
{
"code": null,
"e": 1955,
"s": 1914,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2173,
"s": 1955,
"text": "The interface A has an abstract method funcA(). The interface B extends the interface A and has an abstract method funcB(). The class C implements the interface B. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2420,
"s": 2173,
"text": "interface A {\n void funcA();\n}\ninterface B extends A {\n void funcB();\n}\nclass C implements B {\n public void funcA() {\n System.out.println(\"This is funcA\");\n }\n public void funcB() {\n System.out.println(\"This is funcB\");\n }\n}"
},
{
"code": null,
"e": 2596,
"s": 2420,
"text": "In the method main() in class Demo, an object obj of class C is created. Then the methods funcA() and funcB() are called. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2728,
"s": 2596,
"text": "public class Demo {\n public static void main(String args[]) {\n C obj = new C();\n obj.funcA();\n obj.funcB();\n }\n}"
}
] |
How To Plot Time Series. Produce elegant plots that tell a story | by Nadim Kawwa | Towards Data Science
|
Dealing with time series can be one of the most insightful parts of exploratory data analysis, if done right. In This post, we are going to use the checkin log from the Yelp Dataset to explore trends across different time periods using Pandas and Matplotlib.
After downloading the data, we need to know what to use. The block below shows a sample entry from the checkin.json file based on the Yelp Documentation:
{ // string, 22 character business id, maps to business in business.json "business_id": "tnhfDv5Il8EaGSXZGiuQGg" // string which is a comma-separated list of timestamps for each checkin, each with format YYYY-MM-DD HH:MM:SS "date": "2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-10-15 02:45:18, 2016-11-18 01:54:50, 2017-04-20 18:39:06, 2017-05-03 17:58:02"}
We can read the input file with pandas read_json method with arguments orient=columns and Lines=True.
Upon reading the data, our dataframe looks something like this:
The date column entries are strings such that each date is separated by a comma. By looking at them we can tell that the format is indeedYYYY-MM-DD HH:MM:SS.
For readability, we want our dataframe to look more like this:
The unfolded event log makes more sense from an EDA perspective whereas the format in the JSON format makes more sense for memory storage.
We can obtain this result by creating a dictionary where the keys correspond to dates and the values correspond to business_id. Here we assume that the dates are granular enough so that no two dates are the same. Keep in mind that the python documentation does not allow duplicate keys within a single dictionary.
The implementation can be done as follows:
Say we want to know what are the total checkins for all the years available. We will use this as a gateway to introduce the pandas Grouper which can be used inside the groupby method. For more information about frequency aliases refer to the pandas docs.
The code returns this neat plot:
it is a good start, however what if we want to dive deeper? We will zoom in on the year 2014, though any other year will do. Selecting date ranges is an easy one-liner:
A first indicator of seasonality is to look at the weekend, since the data is from the USA & Canada the weekend is Saturday and Sunday. Bear in mind that the weekend varies by country, for example Dubai’s weekend is Friday and Saturday.
We therefore want to detect the days that are a weekend and write a customizable function for it:
The function above returns indices that are weekends. Next for plotting we define another helper function to highlight spans of the plot that would correspond to these indices with the help of pyplot axvspan:
Finally we can use these two functions inside a larger one that takes in a dataframe:
The result is this neat plot:
The plot above matches the intuition that people go out more on weekends than weekdays. To take a better look at that buildup we can take a closer look at April 2014 using the same function.
What if we want to show a more granular view of April? Since each entry in the original dataframe is a single checkin, we can groupby 30 minute frequencies and count as follows:
The result is the plot below:
We saw how we can zoom in on time periods to get a sense of seasonality. However, businesses also want to know what is the expected number of checkins for a given day and how it might vary. For example, we might be solving for a regression.
Therefore we need to build plots that show the average checkin for a given day of the week and some sort of confidence interval.
We will use the checkin_halfhour defined in the previous section to extract the day of the week:
Our dataframe now looks as follows:
Next, we build the day_avg dataframe using pandas aggregate method. For our purposes we will aggregate:
Sum
Mean
Standard Deviation
The code block below does this for us:
We now have a dataframe we can use to draw intervals:
How we define the interval depends on the distribution of the data and the business value of narrow/larger intervals. In our case, we want to generate the expected checkin for each day of the week and grab all the information within two standard deviations.
Doing so is a matter of watching out for the levels in the index of day_avg as shown below:
The resulting plots reveal a lot in terms of checkin behavior, for illustration we show Monday, Wednesday, and Saturday.
The amount and depth of time series analysis depends on the problem we are trying to solve for. For example, we might want to evaluate restaurants, or businesses that only open from 8AM to 3PM such as cafés.
An objective of EDA is to prepare for feature extraction. With the exercise above we can start thinking about features such as the most common checkin time, or checkins by day.
|
[
{
"code": null,
"e": 305,
"s": 46,
"text": "Dealing with time series can be one of the most insightful parts of exploratory data analysis, if done right. In This post, we are going to use the checkin log from the Yelp Dataset to explore trends across different time periods using Pandas and Matplotlib."
},
{
"code": null,
"e": 459,
"s": 305,
"text": "After downloading the data, we need to know what to use. The block below shows a sample entry from the checkin.json file based on the Yelp Documentation:"
},
{
"code": null,
"e": 831,
"s": 459,
"text": "{ // string, 22 character business id, maps to business in business.json \"business_id\": \"tnhfDv5Il8EaGSXZGiuQGg\" // string which is a comma-separated list of timestamps for each checkin, each with format YYYY-MM-DD HH:MM:SS \"date\": \"2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-10-15 02:45:18, 2016-11-18 01:54:50, 2017-04-20 18:39:06, 2017-05-03 17:58:02\"}"
},
{
"code": null,
"e": 933,
"s": 831,
"text": "We can read the input file with pandas read_json method with arguments orient=columns and Lines=True."
},
{
"code": null,
"e": 997,
"s": 933,
"text": "Upon reading the data, our dataframe looks something like this:"
},
{
"code": null,
"e": 1155,
"s": 997,
"text": "The date column entries are strings such that each date is separated by a comma. By looking at them we can tell that the format is indeedYYYY-MM-DD HH:MM:SS."
},
{
"code": null,
"e": 1218,
"s": 1155,
"text": "For readability, we want our dataframe to look more like this:"
},
{
"code": null,
"e": 1357,
"s": 1218,
"text": "The unfolded event log makes more sense from an EDA perspective whereas the format in the JSON format makes more sense for memory storage."
},
{
"code": null,
"e": 1671,
"s": 1357,
"text": "We can obtain this result by creating a dictionary where the keys correspond to dates and the values correspond to business_id. Here we assume that the dates are granular enough so that no two dates are the same. Keep in mind that the python documentation does not allow duplicate keys within a single dictionary."
},
{
"code": null,
"e": 1714,
"s": 1671,
"text": "The implementation can be done as follows:"
},
{
"code": null,
"e": 1969,
"s": 1714,
"text": "Say we want to know what are the total checkins for all the years available. We will use this as a gateway to introduce the pandas Grouper which can be used inside the groupby method. For more information about frequency aliases refer to the pandas docs."
},
{
"code": null,
"e": 2002,
"s": 1969,
"text": "The code returns this neat plot:"
},
{
"code": null,
"e": 2171,
"s": 2002,
"text": "it is a good start, however what if we want to dive deeper? We will zoom in on the year 2014, though any other year will do. Selecting date ranges is an easy one-liner:"
},
{
"code": null,
"e": 2408,
"s": 2171,
"text": "A first indicator of seasonality is to look at the weekend, since the data is from the USA & Canada the weekend is Saturday and Sunday. Bear in mind that the weekend varies by country, for example Dubai’s weekend is Friday and Saturday."
},
{
"code": null,
"e": 2506,
"s": 2408,
"text": "We therefore want to detect the days that are a weekend and write a customizable function for it:"
},
{
"code": null,
"e": 2715,
"s": 2506,
"text": "The function above returns indices that are weekends. Next for plotting we define another helper function to highlight spans of the plot that would correspond to these indices with the help of pyplot axvspan:"
},
{
"code": null,
"e": 2801,
"s": 2715,
"text": "Finally we can use these two functions inside a larger one that takes in a dataframe:"
},
{
"code": null,
"e": 2831,
"s": 2801,
"text": "The result is this neat plot:"
},
{
"code": null,
"e": 3022,
"s": 2831,
"text": "The plot above matches the intuition that people go out more on weekends than weekdays. To take a better look at that buildup we can take a closer look at April 2014 using the same function."
},
{
"code": null,
"e": 3200,
"s": 3022,
"text": "What if we want to show a more granular view of April? Since each entry in the original dataframe is a single checkin, we can groupby 30 minute frequencies and count as follows:"
},
{
"code": null,
"e": 3230,
"s": 3200,
"text": "The result is the plot below:"
},
{
"code": null,
"e": 3471,
"s": 3230,
"text": "We saw how we can zoom in on time periods to get a sense of seasonality. However, businesses also want to know what is the expected number of checkins for a given day and how it might vary. For example, we might be solving for a regression."
},
{
"code": null,
"e": 3600,
"s": 3471,
"text": "Therefore we need to build plots that show the average checkin for a given day of the week and some sort of confidence interval."
},
{
"code": null,
"e": 3697,
"s": 3600,
"text": "We will use the checkin_halfhour defined in the previous section to extract the day of the week:"
},
{
"code": null,
"e": 3733,
"s": 3697,
"text": "Our dataframe now looks as follows:"
},
{
"code": null,
"e": 3837,
"s": 3733,
"text": "Next, we build the day_avg dataframe using pandas aggregate method. For our purposes we will aggregate:"
},
{
"code": null,
"e": 3841,
"s": 3837,
"text": "Sum"
},
{
"code": null,
"e": 3846,
"s": 3841,
"text": "Mean"
},
{
"code": null,
"e": 3865,
"s": 3846,
"text": "Standard Deviation"
},
{
"code": null,
"e": 3904,
"s": 3865,
"text": "The code block below does this for us:"
},
{
"code": null,
"e": 3958,
"s": 3904,
"text": "We now have a dataframe we can use to draw intervals:"
},
{
"code": null,
"e": 4216,
"s": 3958,
"text": "How we define the interval depends on the distribution of the data and the business value of narrow/larger intervals. In our case, we want to generate the expected checkin for each day of the week and grab all the information within two standard deviations."
},
{
"code": null,
"e": 4308,
"s": 4216,
"text": "Doing so is a matter of watching out for the levels in the index of day_avg as shown below:"
},
{
"code": null,
"e": 4429,
"s": 4308,
"text": "The resulting plots reveal a lot in terms of checkin behavior, for illustration we show Monday, Wednesday, and Saturday."
},
{
"code": null,
"e": 4638,
"s": 4429,
"text": "The amount and depth of time series analysis depends on the problem we are trying to solve for. For example, we might want to evaluate restaurants, or businesses that only open from 8AM to 3PM such as cafés."
}
] |
Python Membership and Identity Operators - GeeksforGeeks
|
09 Dec, 2021
In this article, we are going to Python Membership and Identity Operators.
Membership operators are operators used to validate the membership of a value. It tests for membership in a sequence, such as strings, lists, or tuples.
in operator: The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluate to true if it finds a variable in the specified sequence and false otherwise.
Python3
# Python program to illustrate# Finding common member in list# using 'in' operatorlist1=[1,2,3,4,5]list2=[6,7,8,9]for item in list1: if item in list2: print("overlapping") else: print("not overlapping")
Output:
not overlapping
The same example without using in operator:
Python3
# Python program to illustrate# Finding common member in list# without using 'in' operator # Define a function() that takes two listsdef overlapping(list1,list2): c=0 d=0 for i in list1: c+=1 for i in list2: d+=1 for i in range(0,c): for j in range(0,d): if(list1[i]==list2[j]): return 1 return 0list1=[1,2,3,4,5]list2=[6,7,8,9]if(overlapping(list1,list2)): print("overlapping")else: print("not overlapping")
Output:
not overlapping
‘not in’ operator- Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
Python3
# Python program to illustrate# not 'in' operatorx = 24y = 20list = [10, 20, 30, 40, 50 ]; if ( x not in list ): print("x is NOT present in given list")else: print("x is present in given list") if ( y in list ): print("y is present in given list")else: print("y is NOT present in given list")
Output:
x is NOT present in given list
y is present in given list
In Python identity operators are used to determine whether a value is of a certain class or type. They are usually used to determine the type of data a certain variable contains. There are different identity operators such as
‘is’ operator – Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
Python3
# Python program to illustrate the use# of 'is' identity operatorx = 5if (type(x) is int): print("true")else: print("false")
Output:
true
‘is not’ operator – Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.
Python3
# Python program to illustrate the# use of 'is not' identity operatorx = 5.2if (type(x) is not int): print("true")else: print("false")
Output:
true
ismav_nurav
AlexArze
nandavardhan153
sandipranjanjan02
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41552,
"s": 41524,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 41627,
"s": 41552,
"text": "In this article, we are going to Python Membership and Identity Operators."
},
{
"code": null,
"e": 41781,
"s": 41627,
"text": "Membership operators are operators used to validate the membership of a value. It tests for membership in a sequence, such as strings, lists, or tuples. "
},
{
"code": null,
"e": 41956,
"s": 41781,
"text": "in operator: The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluate to true if it finds a variable in the specified sequence and false otherwise."
},
{
"code": null,
"e": 41964,
"s": 41956,
"text": "Python3"
},
{
"code": "# Python program to illustrate# Finding common member in list# using 'in' operatorlist1=[1,2,3,4,5]list2=[6,7,8,9]for item in list1: if item in list2: print(\"overlapping\") else: print(\"not overlapping\")",
"e": 42184,
"s": 41964,
"text": null
},
{
"code": null,
"e": 42192,
"s": 42184,
"text": "Output:"
},
{
"code": null,
"e": 42208,
"s": 42192,
"text": "not overlapping"
},
{
"code": null,
"e": 42252,
"s": 42208,
"text": "The same example without using in operator:"
},
{
"code": null,
"e": 42260,
"s": 42252,
"text": "Python3"
},
{
"code": "# Python program to illustrate# Finding common member in list# without using 'in' operator # Define a function() that takes two listsdef overlapping(list1,list2): c=0 d=0 for i in list1: c+=1 for i in list2: d+=1 for i in range(0,c): for j in range(0,d): if(list1[i]==list2[j]): return 1 return 0list1=[1,2,3,4,5]list2=[6,7,8,9]if(overlapping(list1,list2)): print(\"overlapping\")else: print(\"not overlapping\")",
"e": 42743,
"s": 42260,
"text": null
},
{
"code": null,
"e": 42751,
"s": 42743,
"text": "Output:"
},
{
"code": null,
"e": 42767,
"s": 42751,
"text": "not overlapping"
},
{
"code": null,
"e": 42883,
"s": 42767,
"text": "‘not in’ operator- Evaluates to true if it does not finds a variable in the specified sequence and false otherwise."
},
{
"code": null,
"e": 42891,
"s": 42883,
"text": "Python3"
},
{
"code": "# Python program to illustrate# not 'in' operatorx = 24y = 20list = [10, 20, 30, 40, 50 ]; if ( x not in list ): print(\"x is NOT present in given list\")else: print(\"x is present in given list\") if ( y in list ): print(\"y is present in given list\")else: print(\"y is NOT present in given list\")",
"e": 43193,
"s": 42891,
"text": null
},
{
"code": null,
"e": 43201,
"s": 43193,
"text": "Output:"
},
{
"code": null,
"e": 43259,
"s": 43201,
"text": "x is NOT present in given list\ny is present in given list"
},
{
"code": null,
"e": 43486,
"s": 43259,
"text": "In Python identity operators are used to determine whether a value is of a certain class or type. They are usually used to determine the type of data a certain variable contains. There are different identity operators such as "
},
{
"code": null,
"e": 43614,
"s": 43486,
"text": "‘is’ operator – Evaluates to true if the variables on either side of the operator point to the same object and false otherwise."
},
{
"code": null,
"e": 43622,
"s": 43614,
"text": "Python3"
},
{
"code": "# Python program to illustrate the use# of 'is' identity operatorx = 5if (type(x) is int): print(\"true\")else: print(\"false\")",
"e": 43753,
"s": 43622,
"text": null
},
{
"code": null,
"e": 43762,
"s": 43753,
"text": "Output: "
},
{
"code": null,
"e": 43767,
"s": 43762,
"text": "true"
},
{
"code": null,
"e": 43899,
"s": 43767,
"text": "‘is not’ operator – Evaluates to false if the variables on either side of the operator point to the same object and true otherwise."
},
{
"code": null,
"e": 43907,
"s": 43899,
"text": "Python3"
},
{
"code": "# Python program to illustrate the# use of 'is not' identity operatorx = 5.2if (type(x) is not int): print(\"true\")else: print(\"false\")",
"e": 44048,
"s": 43907,
"text": null
},
{
"code": null,
"e": 44056,
"s": 44048,
"text": "Output:"
},
{
"code": null,
"e": 44061,
"s": 44056,
"text": "true"
},
{
"code": null,
"e": 44073,
"s": 44061,
"text": "ismav_nurav"
},
{
"code": null,
"e": 44082,
"s": 44073,
"text": "AlexArze"
},
{
"code": null,
"e": 44098,
"s": 44082,
"text": "nandavardhan153"
},
{
"code": null,
"e": 44116,
"s": 44098,
"text": "sandipranjanjan02"
},
{
"code": null,
"e": 44123,
"s": 44116,
"text": "Python"
},
{
"code": null,
"e": 44221,
"s": 44123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44230,
"s": 44221,
"text": "Comments"
},
{
"code": null,
"e": 44243,
"s": 44230,
"text": "Old Comments"
},
{
"code": null,
"e": 44271,
"s": 44243,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44321,
"s": 44271,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44343,
"s": 44321,
"text": "Python map() function"
},
{
"code": null,
"e": 44387,
"s": 44343,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44422,
"s": 44387,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44444,
"s": 44422,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44476,
"s": 44444,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44506,
"s": 44476,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44548,
"s": 44506,
"text": "Different ways to create Pandas Dataframe"
}
] |
10 Of My Favorite Python Libraries For Data Analysis | by Emmett Boudreau | Towards Data Science
|
The most popular general purpose programming language on planet Earth right now is the Python programming language. This is not only because Python is incredibly easy, and relatively fast, but also that Python has a killer ecosystem with tools to fit every discipline from business to finance and science. One area that this is certainly proven to be true is in the wonderful world of data science.
Of course, Python is also the most popular programming language used today for data science. While most scientists working with the language might be familiar with a lot of well-known and widely used packages such as Scipy, Sklearn, and Matplotlib, there are some packages which most data scientists have never even heard of that are also quite awesome!
To start us off, I am going with a library for data visualization that is pretty well-known, but some might have never heard of. Plot.ly is a graphing library that takes interactivity to a whole new level. I would genuinely advise using Plot.ly over something like Matplotlib or Seaborn. This is because Plot.ly comes with a multitude of different tools that most scientists can certainly come to appreciate. Just how much is in Plot.ly?
Well...
Plot.ly comes preloaded with all of the fantastic tools that your average data scientist or even just computer programmer might expect. Scatter plots, bar charts, and line charts are all staples of the Plot.ly module. While Matplotlib can accomplish similar goals, Plot.ly has the same functionality while also having default styling and Java-script interactivity that makes it a lot more fun and a lot easier to explore data. On top of that, presentations are certainly a thing that could be served a benefit from using Plot.ly over many of its competitors.
On top of all of that, Plot.ly also has some lesser-known charts and graphs that you would be hard-pressed to find in most other data visualization packages. Funnel charts, pie charts, violin charts, and tree maps are just a few examples of some unique and fun ways to explore data using the Plot.ly library.
On top of the beautiful styling for basic plots, Plot.ly comes with a fully-featured 3D visualization system that rivals some of the best available with modern technology. One great advantage to the way that Plot.ly handles 3D is performance. Although 3D visualizations are of course quite complex and intensive, Plot.ly seems to handle a lot of these applications with relative ease. 3D visualizations are also awesome because the new axis allows for a greater amount of understanding by exploring data’s positional values in 3D space. Furthermore, the Z axis can also represent a variety of features — making it possible to view several different correlations at once.
One thing that has become surprising in the recent development of technology is geo-data. Geo-data has evolutionized with FIPS to such an extent primarily because of smart-phones and global positioning systems (GPS,) and this has given way to a strong foundation for data science to build on top of. This is of course because data is now more readily available than it ever has been for free with geo-data included.
It is hard to argue with Plot.ly’s beautiful approach to maps, as well. Plot.ly’s clorepleths in particular are an absolute joy to use and can make compelling visualizations in a matter of seconds.
Although the financial side of things is certainly not where most of my domain knowledge falls, Plot.ly has great support for several financial visualizations. This goes to show Plot.ly’s versatility as well, as visualizations rely both in and out of many scientist’s domain. Like everything in Plot.ly, financial charts are easy to use and beautiful — a while ago I worked on a project where we tracked the value of currencies and created a full web-app with an LSTM model that would retrain itself and predict new data based on what it had learnt. Plot.ly really came in handy with its easy to use and Javascript integrated visualizations for candlestick data in this circumstance.
To add to the unreasonable power of Plot.ly, Plot.ly also supports several different types of statistical plots. Furthermore, Plot.ly’s statistical plotting is incredibly mature and makes things like plotting distributions relatively simple and easy.
Another great thing about Plot.ly is that it is written in C. As a result, it uses the LLVM compiler libraries and is compatible with a whole array of programming languages with just a simple API. Not only is Plot.ly available for Python users, but also R users, C users, and any other language’s user base that is willing to implement it. There is even an implementation for the Julia language using the Plots.jl package.
The last great thing about Plot.ly is that it is open-source. While this isn’t as big of a benefit to some, being able to make changes if required or understand how code is being ran on your machine is always a plus. Being open-source software also means that Plot.ly can be used in practical business applications, making it valuable not only to those who program as a hobby, but also for real-world professionals.
The second great tool I would recommend for data analysis with Python is GGPlot.py. Any scientist who has experience in the R programming language has likely used GGPlot or GGPlot2. Both the R and Python package are fantastic and make plotting a breeze and furthermore in-depth. While the R implementation is certainly worth checking out, the Pythonic version is certainly pretty awesome as well.
A significant difference between the GGPlot package and the Plot.ly package for Python is that GGPlot is much more statistically-focused. Plot.ly is a great tool for data visualization, but is also targeted at more typical data visualization, rather than specifically statistical plotting.
Another significant thing to note about GGPlot is its approach to graphics and visualization. Generally, GGPlot is more geometrically modular. This means that compositions can often be added to or altered quite easily. This is further beneficial to data science, as often there is a certain idea or data point that might want to be emphasized more than others.
Bokeh is another interactive plotting library that was built with modern web-browsing and computing in mind. Similarly to Plot.ly, Bokeh might not be as extendable as something like GGPlot, but presents a host of benefits over the former by being incredibly integrated with Javascript. Every data scientist loves interactive visualizations, and Bokeh often takes this to a very high-level and simple API with stunning results.
Bokeh as a visualization tool is incredibly similar to Plot.ly, and that isn’t a bad thing at all. This means that Bokeh can be used to create beautiful and interactive visualizations incredibly easily.
While Bokeh is similar to Plot.ly in a lot of ways, this is certainly not the case in what is possible with Bokeh. Not only is there support for all of the typical visualization techniques, but Bokeh also allows a user to create interesting and interactive visualizations of nearly anything. One relatively common use for Bokeh is the visualization of network graphs, which is really cool! On top of that, it does come with the geo-data visualizations that one might expect from the Plot.ly library.
Steering away from the world of visualization is a fantastic Python package called SymPy. MATLAB, Mathematica, and Julia programmers, hold on to your hats — SymPy is a Python module that allows Pythonic programmers and scientists to use more mathematical bindings. This allows the language to shift from a typically more software engineering approach to mathematics to the other end of the spectrum where code is frequently written as math.
Many awesome implementations of Pythonic code and math use SymPy for mathematical calculations on the back-end. Here are some notable examples pulled straight from their homepage:
Cadabra: Tensor algebra and (quantum) field theory system using SymPy for scalar algebra.
ChemPy: A package useful for chemistry written in Python.
Lcapy: Experimental Python package for teaching linear circuit analysis.
Spyder: The Scientific Python Development Environment, a Python equivalent to Rstudio or MATLAB; full SymPy support can be enabled in Spyder’s IPython Consoles.
Easily the coolest thing that SymPy has to offer is the ability to lambdify any expression or function inside of the language. I have talked before about why I think Lambda is one of the greatest tools available for Python developers. If you would like to read an article all about that topic, you can check it out here:
towardsdatascience.com
While Python’s lambda is great as an in-line argument on its own, it becomes even more powerful with the Lambdify function from SymPy. Here is how it works:
First, you can create an expression to be used as a mathematical function, in this example sin(x).
import numpya = numpy.arange(10)expr = sin(x)
That function can then be put through lambdify and become a very functional version of itself:
f = lambdify(x, expr, "numpy")
This is the basis for all of SymPy and makes scientific computing with the Python programming language a lot easier. The use of this function can actually allow Python to explore one of the benefits to the Julia language, syntactical expressions. If you’d like to learn more about how the Julia language uses expressions, you can check out a full tutorial on it here:
towardsdatascience.com
The Blaze Ecosystem is a set of Pythonic libraries that make it far easier to query and process data in the Python programming language. The Blaze ecosystem actually consists of several different packages:
Blaze
Dask
DataShape
DyND
Odo
These are all fantastic, useful, and well-made tools for the Python programming language. However, I will be focusing on the two that I have used the most and found to be the most valuable as it pertains to scientific computing.
Blaze is an interface for querying all sorts of data on entirely different storage systems. This is incredibly useful for retrieving and analyzing big data dumps that might need to be taken apart by an algorithm, and furthermore might be in separate parts of different storage mediums. It is an incredibly useful tool for those who work in those particular circumstances, and has saved my life multiple times.
Dask is an incredibly unique package that allows for simple and most of all mutable parallel computing in Python. Parallel computing in Python has always been somewhat of a challenge in the language, and furthermore, optimizations have become incredibly difficult with many of the biggest packages available to the language because the language was not built with the idea of parallel computing in mind.
That being said, as the language itself moves more into this direction, Dask is a great tool for consistency with GPU support and working with CuArrays. Dask also features dynamic task scheduling that is explicitly coded by the programmer involved and big data collections.
Orange is a Python library for data mining. How does this pertain to data analytics? Orange has a whole ecosystem of awesome tools for collecting data that can later be used for analysis, and analysis cannot happen without data. That being said, data wrangling is a very important step in the process of data science, and Orange helps to make that process a little more simpler.
Even cooler, the module comes with a few classification and regression models that you can use on your freshly mined data!
Genism is a Python library for topic modeling. What is great about Genism is that it is both easy to use, and very powerful. Using Gensim, you can create scalable statistical semantics that take up more memory than your computer has that can also be deployed into a real production environment. Furthermore, Genism can easily be implemented to perform natural language processing.
Theano is another mathematical Python library that allows a programmer to work with copious amounts of data efficiently. While it might not match the mathematics-centric nature of something like SymPy, it does a lot really cool and interesting things that make linear algebra in Python a lot more fun. On top of that, Theano is very accurate and relatively quick compared to a lot of similar solutions. On top of that, the package is tightly integrated with Numpy and dynamically integrates C code to make Python run faster.
If you’ve been using Python for statistics for even a week, it is likely that you have used SciPy. SciPy is the go-to package for statistical testing in the Python language. SciPy is not only generally a fast package to use, but it is also venerable and has been proven overtime to work incredibly well. The combination of SciPy, Pandas, and Numpy are what make Python a great language for general scientists and even more-so data scientists to work in.
One thing that can definitely be said about SciPy is that the module is very inclusive. While this might mean that occasionally it will be hard to find exactly what you need, it also means that everything you need is at your fingertips — a good trade, in my opinion. The SciPy library brings everything from statistics to distributions and even differential equations into easy to understand and simple functions that anyone could use!
The last awesome tool I would recommend for data analysis in the Python programming language is a Pythonic classic:
Seaborn.
Seaborn is an extension of MatPlotLib.PyPlot that integrates statistical plotting into the module. Seaborn provides a high-level interface for drawing, manipulating, and working with beautiful statistical graphics. While the appearance of Seaborn might pale in comparison to something like Bokeh or Plot.ly, it is incredibly significant in the margins of speed. When working with datasets with a lot of observations, it might be a good idea to try and use Seaborn rather than Plot.ly or Bokeh for your data visualizations. The simplicity of Seaborn is its greatest benefit, as it makes it fast and easy to use with familiar bindings from MatPlotLib.
If one language used by modern developers has the best ecosystem for data analysis and visualization, it is most likely Python. Python has tools that are not only great for statistical observations, but are also great for making the language act more statistical in itself. Furthermore, in terms of visualization, few languages rival the amazing modules that the Python programming languages gives to Python-based scientists. That being said, these are some modules I really like — but there are a lot more, so it would certainly be interesting to know more about those in the responses!
|
[
{
"code": null,
"e": 571,
"s": 172,
"text": "The most popular general purpose programming language on planet Earth right now is the Python programming language. This is not only because Python is incredibly easy, and relatively fast, but also that Python has a killer ecosystem with tools to fit every discipline from business to finance and science. One area that this is certainly proven to be true is in the wonderful world of data science."
},
{
"code": null,
"e": 925,
"s": 571,
"text": "Of course, Python is also the most popular programming language used today for data science. While most scientists working with the language might be familiar with a lot of well-known and widely used packages such as Scipy, Sklearn, and Matplotlib, there are some packages which most data scientists have never even heard of that are also quite awesome!"
},
{
"code": null,
"e": 1363,
"s": 925,
"text": "To start us off, I am going with a library for data visualization that is pretty well-known, but some might have never heard of. Plot.ly is a graphing library that takes interactivity to a whole new level. I would genuinely advise using Plot.ly over something like Matplotlib or Seaborn. This is because Plot.ly comes with a multitude of different tools that most scientists can certainly come to appreciate. Just how much is in Plot.ly?"
},
{
"code": null,
"e": 1371,
"s": 1363,
"text": "Well..."
},
{
"code": null,
"e": 1930,
"s": 1371,
"text": "Plot.ly comes preloaded with all of the fantastic tools that your average data scientist or even just computer programmer might expect. Scatter plots, bar charts, and line charts are all staples of the Plot.ly module. While Matplotlib can accomplish similar goals, Plot.ly has the same functionality while also having default styling and Java-script interactivity that makes it a lot more fun and a lot easier to explore data. On top of that, presentations are certainly a thing that could be served a benefit from using Plot.ly over many of its competitors."
},
{
"code": null,
"e": 2239,
"s": 1930,
"text": "On top of all of that, Plot.ly also has some lesser-known charts and graphs that you would be hard-pressed to find in most other data visualization packages. Funnel charts, pie charts, violin charts, and tree maps are just a few examples of some unique and fun ways to explore data using the Plot.ly library."
},
{
"code": null,
"e": 2910,
"s": 2239,
"text": "On top of the beautiful styling for basic plots, Plot.ly comes with a fully-featured 3D visualization system that rivals some of the best available with modern technology. One great advantage to the way that Plot.ly handles 3D is performance. Although 3D visualizations are of course quite complex and intensive, Plot.ly seems to handle a lot of these applications with relative ease. 3D visualizations are also awesome because the new axis allows for a greater amount of understanding by exploring data’s positional values in 3D space. Furthermore, the Z axis can also represent a variety of features — making it possible to view several different correlations at once."
},
{
"code": null,
"e": 3326,
"s": 2910,
"text": "One thing that has become surprising in the recent development of technology is geo-data. Geo-data has evolutionized with FIPS to such an extent primarily because of smart-phones and global positioning systems (GPS,) and this has given way to a strong foundation for data science to build on top of. This is of course because data is now more readily available than it ever has been for free with geo-data included."
},
{
"code": null,
"e": 3524,
"s": 3326,
"text": "It is hard to argue with Plot.ly’s beautiful approach to maps, as well. Plot.ly’s clorepleths in particular are an absolute joy to use and can make compelling visualizations in a matter of seconds."
},
{
"code": null,
"e": 4208,
"s": 3524,
"text": "Although the financial side of things is certainly not where most of my domain knowledge falls, Plot.ly has great support for several financial visualizations. This goes to show Plot.ly’s versatility as well, as visualizations rely both in and out of many scientist’s domain. Like everything in Plot.ly, financial charts are easy to use and beautiful — a while ago I worked on a project where we tracked the value of currencies and created a full web-app with an LSTM model that would retrain itself and predict new data based on what it had learnt. Plot.ly really came in handy with its easy to use and Javascript integrated visualizations for candlestick data in this circumstance."
},
{
"code": null,
"e": 4459,
"s": 4208,
"text": "To add to the unreasonable power of Plot.ly, Plot.ly also supports several different types of statistical plots. Furthermore, Plot.ly’s statistical plotting is incredibly mature and makes things like plotting distributions relatively simple and easy."
},
{
"code": null,
"e": 4882,
"s": 4459,
"text": "Another great thing about Plot.ly is that it is written in C. As a result, it uses the LLVM compiler libraries and is compatible with a whole array of programming languages with just a simple API. Not only is Plot.ly available for Python users, but also R users, C users, and any other language’s user base that is willing to implement it. There is even an implementation for the Julia language using the Plots.jl package."
},
{
"code": null,
"e": 5298,
"s": 4882,
"text": "The last great thing about Plot.ly is that it is open-source. While this isn’t as big of a benefit to some, being able to make changes if required or understand how code is being ran on your machine is always a plus. Being open-source software also means that Plot.ly can be used in practical business applications, making it valuable not only to those who program as a hobby, but also for real-world professionals."
},
{
"code": null,
"e": 5695,
"s": 5298,
"text": "The second great tool I would recommend for data analysis with Python is GGPlot.py. Any scientist who has experience in the R programming language has likely used GGPlot or GGPlot2. Both the R and Python package are fantastic and make plotting a breeze and furthermore in-depth. While the R implementation is certainly worth checking out, the Pythonic version is certainly pretty awesome as well."
},
{
"code": null,
"e": 5985,
"s": 5695,
"text": "A significant difference between the GGPlot package and the Plot.ly package for Python is that GGPlot is much more statistically-focused. Plot.ly is a great tool for data visualization, but is also targeted at more typical data visualization, rather than specifically statistical plotting."
},
{
"code": null,
"e": 6346,
"s": 5985,
"text": "Another significant thing to note about GGPlot is its approach to graphics and visualization. Generally, GGPlot is more geometrically modular. This means that compositions can often be added to or altered quite easily. This is further beneficial to data science, as often there is a certain idea or data point that might want to be emphasized more than others."
},
{
"code": null,
"e": 6773,
"s": 6346,
"text": "Bokeh is another interactive plotting library that was built with modern web-browsing and computing in mind. Similarly to Plot.ly, Bokeh might not be as extendable as something like GGPlot, but presents a host of benefits over the former by being incredibly integrated with Javascript. Every data scientist loves interactive visualizations, and Bokeh often takes this to a very high-level and simple API with stunning results."
},
{
"code": null,
"e": 6976,
"s": 6773,
"text": "Bokeh as a visualization tool is incredibly similar to Plot.ly, and that isn’t a bad thing at all. This means that Bokeh can be used to create beautiful and interactive visualizations incredibly easily."
},
{
"code": null,
"e": 7476,
"s": 6976,
"text": "While Bokeh is similar to Plot.ly in a lot of ways, this is certainly not the case in what is possible with Bokeh. Not only is there support for all of the typical visualization techniques, but Bokeh also allows a user to create interesting and interactive visualizations of nearly anything. One relatively common use for Bokeh is the visualization of network graphs, which is really cool! On top of that, it does come with the geo-data visualizations that one might expect from the Plot.ly library."
},
{
"code": null,
"e": 7917,
"s": 7476,
"text": "Steering away from the world of visualization is a fantastic Python package called SymPy. MATLAB, Mathematica, and Julia programmers, hold on to your hats — SymPy is a Python module that allows Pythonic programmers and scientists to use more mathematical bindings. This allows the language to shift from a typically more software engineering approach to mathematics to the other end of the spectrum where code is frequently written as math."
},
{
"code": null,
"e": 8097,
"s": 7917,
"text": "Many awesome implementations of Pythonic code and math use SymPy for mathematical calculations on the back-end. Here are some notable examples pulled straight from their homepage:"
},
{
"code": null,
"e": 8187,
"s": 8097,
"text": "Cadabra: Tensor algebra and (quantum) field theory system using SymPy for scalar algebra."
},
{
"code": null,
"e": 8245,
"s": 8187,
"text": "ChemPy: A package useful for chemistry written in Python."
},
{
"code": null,
"e": 8318,
"s": 8245,
"text": "Lcapy: Experimental Python package for teaching linear circuit analysis."
},
{
"code": null,
"e": 8479,
"s": 8318,
"text": "Spyder: The Scientific Python Development Environment, a Python equivalent to Rstudio or MATLAB; full SymPy support can be enabled in Spyder’s IPython Consoles."
},
{
"code": null,
"e": 8800,
"s": 8479,
"text": "Easily the coolest thing that SymPy has to offer is the ability to lambdify any expression or function inside of the language. I have talked before about why I think Lambda is one of the greatest tools available for Python developers. If you would like to read an article all about that topic, you can check it out here:"
},
{
"code": null,
"e": 8823,
"s": 8800,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8980,
"s": 8823,
"text": "While Python’s lambda is great as an in-line argument on its own, it becomes even more powerful with the Lambdify function from SymPy. Here is how it works:"
},
{
"code": null,
"e": 9079,
"s": 8980,
"text": "First, you can create an expression to be used as a mathematical function, in this example sin(x)."
},
{
"code": null,
"e": 9125,
"s": 9079,
"text": "import numpya = numpy.arange(10)expr = sin(x)"
},
{
"code": null,
"e": 9220,
"s": 9125,
"text": "That function can then be put through lambdify and become a very functional version of itself:"
},
{
"code": null,
"e": 9251,
"s": 9220,
"text": "f = lambdify(x, expr, \"numpy\")"
},
{
"code": null,
"e": 9619,
"s": 9251,
"text": "This is the basis for all of SymPy and makes scientific computing with the Python programming language a lot easier. The use of this function can actually allow Python to explore one of the benefits to the Julia language, syntactical expressions. If you’d like to learn more about how the Julia language uses expressions, you can check out a full tutorial on it here:"
},
{
"code": null,
"e": 9642,
"s": 9619,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9848,
"s": 9642,
"text": "The Blaze Ecosystem is a set of Pythonic libraries that make it far easier to query and process data in the Python programming language. The Blaze ecosystem actually consists of several different packages:"
},
{
"code": null,
"e": 9854,
"s": 9848,
"text": "Blaze"
},
{
"code": null,
"e": 9859,
"s": 9854,
"text": "Dask"
},
{
"code": null,
"e": 9869,
"s": 9859,
"text": "DataShape"
},
{
"code": null,
"e": 9874,
"s": 9869,
"text": "DyND"
},
{
"code": null,
"e": 9878,
"s": 9874,
"text": "Odo"
},
{
"code": null,
"e": 10107,
"s": 9878,
"text": "These are all fantastic, useful, and well-made tools for the Python programming language. However, I will be focusing on the two that I have used the most and found to be the most valuable as it pertains to scientific computing."
},
{
"code": null,
"e": 10517,
"s": 10107,
"text": "Blaze is an interface for querying all sorts of data on entirely different storage systems. This is incredibly useful for retrieving and analyzing big data dumps that might need to be taken apart by an algorithm, and furthermore might be in separate parts of different storage mediums. It is an incredibly useful tool for those who work in those particular circumstances, and has saved my life multiple times."
},
{
"code": null,
"e": 10921,
"s": 10517,
"text": "Dask is an incredibly unique package that allows for simple and most of all mutable parallel computing in Python. Parallel computing in Python has always been somewhat of a challenge in the language, and furthermore, optimizations have become incredibly difficult with many of the biggest packages available to the language because the language was not built with the idea of parallel computing in mind."
},
{
"code": null,
"e": 11195,
"s": 10921,
"text": "That being said, as the language itself moves more into this direction, Dask is a great tool for consistency with GPU support and working with CuArrays. Dask also features dynamic task scheduling that is explicitly coded by the programmer involved and big data collections."
},
{
"code": null,
"e": 11574,
"s": 11195,
"text": "Orange is a Python library for data mining. How does this pertain to data analytics? Orange has a whole ecosystem of awesome tools for collecting data that can later be used for analysis, and analysis cannot happen without data. That being said, data wrangling is a very important step in the process of data science, and Orange helps to make that process a little more simpler."
},
{
"code": null,
"e": 11697,
"s": 11574,
"text": "Even cooler, the module comes with a few classification and regression models that you can use on your freshly mined data!"
},
{
"code": null,
"e": 12078,
"s": 11697,
"text": "Genism is a Python library for topic modeling. What is great about Genism is that it is both easy to use, and very powerful. Using Gensim, you can create scalable statistical semantics that take up more memory than your computer has that can also be deployed into a real production environment. Furthermore, Genism can easily be implemented to perform natural language processing."
},
{
"code": null,
"e": 12603,
"s": 12078,
"text": "Theano is another mathematical Python library that allows a programmer to work with copious amounts of data efficiently. While it might not match the mathematics-centric nature of something like SymPy, it does a lot really cool and interesting things that make linear algebra in Python a lot more fun. On top of that, Theano is very accurate and relatively quick compared to a lot of similar solutions. On top of that, the package is tightly integrated with Numpy and dynamically integrates C code to make Python run faster."
},
{
"code": null,
"e": 13057,
"s": 12603,
"text": "If you’ve been using Python for statistics for even a week, it is likely that you have used SciPy. SciPy is the go-to package for statistical testing in the Python language. SciPy is not only generally a fast package to use, but it is also venerable and has been proven overtime to work incredibly well. The combination of SciPy, Pandas, and Numpy are what make Python a great language for general scientists and even more-so data scientists to work in."
},
{
"code": null,
"e": 13493,
"s": 13057,
"text": "One thing that can definitely be said about SciPy is that the module is very inclusive. While this might mean that occasionally it will be hard to find exactly what you need, it also means that everything you need is at your fingertips — a good trade, in my opinion. The SciPy library brings everything from statistics to distributions and even differential equations into easy to understand and simple functions that anyone could use!"
},
{
"code": null,
"e": 13609,
"s": 13493,
"text": "The last awesome tool I would recommend for data analysis in the Python programming language is a Pythonic classic:"
},
{
"code": null,
"e": 13618,
"s": 13609,
"text": "Seaborn."
},
{
"code": null,
"e": 14268,
"s": 13618,
"text": "Seaborn is an extension of MatPlotLib.PyPlot that integrates statistical plotting into the module. Seaborn provides a high-level interface for drawing, manipulating, and working with beautiful statistical graphics. While the appearance of Seaborn might pale in comparison to something like Bokeh or Plot.ly, it is incredibly significant in the margins of speed. When working with datasets with a lot of observations, it might be a good idea to try and use Seaborn rather than Plot.ly or Bokeh for your data visualizations. The simplicity of Seaborn is its greatest benefit, as it makes it fast and easy to use with familiar bindings from MatPlotLib."
}
] |
How to analyze stratified random sampled data | by Jason Sadowski | Towards Data Science
|
When constructing an experiment, one of the most important questions to ask is: How should I sample from my population? Clearly you want to conduct some sort of random sampling procedure, but exactly how the random sampling is done can have a large impact on your analysis. While there are many useful guides on how to conduct stratified random sampling, I’ve noticed that there are few guidelines on how to correctly analyze your stratified sampled data. In this article, I’m going to discuss how to conduct stratified sampling and how to analyze the resultant data using some simulated data as an example.
First, I want to briefly go over stratified sampling and why it is important. Let’s say I am the data scientist at Company X. Company X has user base of about 500,000 people from across the United States. Most of our users live in cities, but there is also a large proportion that live in small towns. I’m interested in running an experiment to see how changing the user interface of our app could change the click-through probability from the app onto a secondary web site. A pretty straightforward A/B test. Assuming that I have the relevant permissions and sufficiently anonymized data, how should I select the users for this experiment?
I have two choices: 1) I could sample randomly from across the user base or 2) I could stratify my sampling accounting for the two subgroups in my users (Cities vs. Towns). If I wanted to use stratified sampling, I would sample randomly from each of the subgroups and assign half of each to the A or B treatments.
But why would I want to do this? In this case, I would stratify if I thought that there were real differences between the subgroups. For example, maybe my Cities subgroup baseline click through probability is higher than the Towns subgroup. The other possibility is that the effect of treatment B could differ between Cities and Towns. Maybe people in Cities have different aesthetics than people in Towns and really like treatment B, leading to a stronger effect of treatment B on the click through probability. I won’t be addressing that possibility in this case, but there are other cases where it may be important.
In this article I’m going to simulate a user base and conduct an experiment with a hypothesized response. First using complete random sampling (AKA simple random sampling) and then using stratified random sampling. Then I’ll examine how my inferences about the experiment change between the two sampling regimes. The baseline click through probability will differ substantially between the two subgroups, but the treatment effect will be the same for each group.
I’ll be using pandas, numpy, scipy, and statsmodels for conducting this analysis. You could do some of this with sklearn instead of statsmodels but I prefer the statistical outputs of statsmodels.
The first thing I need to do is to create a user base.
First, for reproducibility, I set a random seed for numpy to use in its random choice algorithms. Each row in the population dataframe represents one unique user. My user base has 500,000 people, and people from cities are 15 times more abundant than people from towns. In the simulated dataset the ratio of people in cities to towns isn’t exactly 15:1 since I’m using a random process:
city 468520town 31480
Coming from an R background, I also include an id column in this dataframe. Pandas usually accounts for this with its indexing functionality, but I like to have an invariant id number when I’m sampling from a population.
For this experiment, I’m interested in whether the probability of a user making a click on the app will increase after implementing a change. For example, maybe Company X is interested is changing a button that leads to a partner site in order to increase traffic.
In the first case, I’m going to randomly sample from the population as a whole, without taking into account the differences between towns and cities.
In the code above, I set a sample size of 500 users per treatment (1000 users total). I then sample 1000 users from the overall population and create a new dataframe based on those samples. Ideally, you would decide on a sample size using a power analysis. But I’ll come back to that at the end of the article.
The next step is to assign the treatments. To make things easy on myself I created a function that would do this for both the complete random sampling and the stratified random sampling.
At the end of this process we get a dataframe that looks like this:
I’ve added a column for the assigned treatment as well as columns for each dummy variable. The dummy variable columns will make synthesizing the response variable easier.
How many of each city category was assigned to each treatment?
Right off the bat we can see some concerns. The Town category is very undersampled relative to the City category (as we expected based off of their abundance in the population). More importantly, there is almost double the Town individuals in Treatment B than in Treatment A. If Town individuals are very different from City individuals, this could be a real problem. (Hint: It will be a problem here.)
In order to calculate an expected signal, I need to specify the baseline click through probabilities as well as the lift created by the interface change. For this example I assume that City users have a baseline click through probability of 0.3 while users in Towns have a baseline click through probability of 0.1. I then assume that users in the B group will have experience an additional 0.05 increase in their click-through probability. It’s a bit large, but useful in this toy example.
To create response data, I sampled from the binomial distribution for each group according to the probabilities that I listed in the paragraph above.
To break down what is going on in the code block above, start with the np.random.binomial() function. There I am sampling 500 times from a binomial distribution with only one trial each, where the the probability of success is any of the probabilities I just listed (0.3, 0.1, or the other two plus an additional 0.05). Here is where the dummy variables come in handy. Remember that the city column is 1 only when the user is from a city and 0 everywhere else, the same is true for the A, B, and town columns. That means we can multiply each of the four binomial response variables by each of their respective dummy variables, then add all 4 columns together to get one response variable column. This process is analogous to the one used by general linear regression models to analyze categorical data.
From here we can easily conduct a t-test to see if our treatment has an effect.
responseA = completerandom_df['response'][completerandom_df['A']==1]responseB = completerandom_df['response'][completerandom_df['B']==1]stats.ttest_ind(responseA, responseB)
Running this code gives us a t-statistic of -0.90 and a p-value of 0.37. Not great. If we plot the data we can get an idea of what’s going on.
Now instead of conducting simple random sampling, let’s use stratified random sampling and see how the analytical results change.
So how do we conduct stratified random sampling? Turns out this is pretty similar to the original complete random sampling.
Here’s the steps:
Define the subpopulations you want to sample fromFrom each subpopulation conduct complete random sampling
Define the subpopulations you want to sample from
From each subpopulation conduct complete random sampling
The way that I like to do this protocol is by creating k lists of indices, one for each of the subpopulations I want to sample. Then I concatenate them into one long list, and use that new index list to extract the data from my original population. I like to do it this way so that I can keep track of how the dataframe was built, but there probably is a more efficient solution.
At this point, I calculate the response variable in the same way as I did above, then run the
The code for the t-test remains the same:
responseA = stratified_df['response'][stratified_df['A']==1]responseB = stratified_df['response'][stratified_df['B']==1]stats.ttest_ind(responseA, responseB)
The output here is a t-value of 2.55 and a p-value of 0.011. Much better than the original complete random sampling regime.
I could conduct a t-test on this data again, just as I did above. However, now that I’ve made sure to sample from both subpopulations I can use an ANOVA to account for some of the variance and boost the signal.
But what happens when we use the extra information of the subpopulation and run a two-way ANOVA on the data?
model = ols('response ~ treatment + cities', data = stratified_df).fit()aov_table = anova_lm(model, typ=1)print(aov_table) df sum_sq mean_sq F PR(>F)treatment 1 1.16 1.16 6.89 0.0090town_size 1 10.82 10.82 64.47 2.75e-15Residual 997 167.27 0.17 NaN NaN
The two-way ANOVA is estimating how much each of the variables (treatment and response) contributes to the total error of the response. You can see this output in the sum_sq term in the second column of the table. Based off of this it looks like the cities variable contributes about 9.4X more variance than the treatment variable, which makes sense based on how I constructed the response variable. Also, in this case I’m not getting a much lower p-value for the treatment effect than from a traditional t-test. That’s mainly because the effect of treatment is the same between the two cities. When the effect of treatment is the same across sub groups, whether or not a two-way ANOVA outperforms a simple t-test depends on the exact distribution of the sampled data.
If we look at the plot, we can see why an ANOVA performs so well.
Because we increased the power of our analysis using the stratified random sampling, our initial sample size calculations would be different between a stratified random sampling and a complete random sampling procedure. I will not go into this in depth here, but essentially our estimates of the variance of each population changes when we go from complete random sampling to stratified random sampling.
There are two main takeaways from this article. First, consider conducting stratified random sampling when the signal could be very different between subpopulations. Second, when you use stratified random sampling to conduct an experiment, use an analytical method that can take into account categorical variables.
Overall, stratified random sampling increases the power of your analysis. In the initial complete random sampling experiment, the signal of the A/B test was diluted by the extra variation introduced by the unaccounted for Town subpopulation. Once I accounted for that subpopulation, then the signal of the A/B test became clear.
I hope that helps with your stratified random sampling needs! I’ve added the Jupyter notebook where I conducted this analysis and a similar R script to my GitHub repository. Here are some links for further reading on ANOVAs and stratified random sampling:
There are a many articles online that go over the different types of sampling methodologies. See here, here, or here.
This course from Penn State goes much deeper into the statistics of stratified random sampling.
Examples of how to conduct an ANOVA on the iris dataset in R and in Python.
How to conduct a power analysis using traditional methods, and using simulated data.
|
[
{
"code": null,
"e": 780,
"s": 172,
"text": "When constructing an experiment, one of the most important questions to ask is: How should I sample from my population? Clearly you want to conduct some sort of random sampling procedure, but exactly how the random sampling is done can have a large impact on your analysis. While there are many useful guides on how to conduct stratified random sampling, I’ve noticed that there are few guidelines on how to correctly analyze your stratified sampled data. In this article, I’m going to discuss how to conduct stratified sampling and how to analyze the resultant data using some simulated data as an example."
},
{
"code": null,
"e": 1421,
"s": 780,
"text": "First, I want to briefly go over stratified sampling and why it is important. Let’s say I am the data scientist at Company X. Company X has user base of about 500,000 people from across the United States. Most of our users live in cities, but there is also a large proportion that live in small towns. I’m interested in running an experiment to see how changing the user interface of our app could change the click-through probability from the app onto a secondary web site. A pretty straightforward A/B test. Assuming that I have the relevant permissions and sufficiently anonymized data, how should I select the users for this experiment?"
},
{
"code": null,
"e": 1735,
"s": 1421,
"text": "I have two choices: 1) I could sample randomly from across the user base or 2) I could stratify my sampling accounting for the two subgroups in my users (Cities vs. Towns). If I wanted to use stratified sampling, I would sample randomly from each of the subgroups and assign half of each to the A or B treatments."
},
{
"code": null,
"e": 2354,
"s": 1735,
"text": "But why would I want to do this? In this case, I would stratify if I thought that there were real differences between the subgroups. For example, maybe my Cities subgroup baseline click through probability is higher than the Towns subgroup. The other possibility is that the effect of treatment B could differ between Cities and Towns. Maybe people in Cities have different aesthetics than people in Towns and really like treatment B, leading to a stronger effect of treatment B on the click through probability. I won’t be addressing that possibility in this case, but there are other cases where it may be important."
},
{
"code": null,
"e": 2817,
"s": 2354,
"text": "In this article I’m going to simulate a user base and conduct an experiment with a hypothesized response. First using complete random sampling (AKA simple random sampling) and then using stratified random sampling. Then I’ll examine how my inferences about the experiment change between the two sampling regimes. The baseline click through probability will differ substantially between the two subgroups, but the treatment effect will be the same for each group."
},
{
"code": null,
"e": 3014,
"s": 2817,
"text": "I’ll be using pandas, numpy, scipy, and statsmodels for conducting this analysis. You could do some of this with sklearn instead of statsmodels but I prefer the statistical outputs of statsmodels."
},
{
"code": null,
"e": 3069,
"s": 3014,
"text": "The first thing I need to do is to create a user base."
},
{
"code": null,
"e": 3456,
"s": 3069,
"text": "First, for reproducibility, I set a random seed for numpy to use in its random choice algorithms. Each row in the population dataframe represents one unique user. My user base has 500,000 people, and people from cities are 15 times more abundant than people from towns. In the simulated dataset the ratio of people in cities to towns isn’t exactly 15:1 since I’m using a random process:"
},
{
"code": null,
"e": 3491,
"s": 3456,
"text": "city 468520town 31480"
},
{
"code": null,
"e": 3712,
"s": 3491,
"text": "Coming from an R background, I also include an id column in this dataframe. Pandas usually accounts for this with its indexing functionality, but I like to have an invariant id number when I’m sampling from a population."
},
{
"code": null,
"e": 3977,
"s": 3712,
"text": "For this experiment, I’m interested in whether the probability of a user making a click on the app will increase after implementing a change. For example, maybe Company X is interested is changing a button that leads to a partner site in order to increase traffic."
},
{
"code": null,
"e": 4127,
"s": 3977,
"text": "In the first case, I’m going to randomly sample from the population as a whole, without taking into account the differences between towns and cities."
},
{
"code": null,
"e": 4438,
"s": 4127,
"text": "In the code above, I set a sample size of 500 users per treatment (1000 users total). I then sample 1000 users from the overall population and create a new dataframe based on those samples. Ideally, you would decide on a sample size using a power analysis. But I’ll come back to that at the end of the article."
},
{
"code": null,
"e": 4625,
"s": 4438,
"text": "The next step is to assign the treatments. To make things easy on myself I created a function that would do this for both the complete random sampling and the stratified random sampling."
},
{
"code": null,
"e": 4693,
"s": 4625,
"text": "At the end of this process we get a dataframe that looks like this:"
},
{
"code": null,
"e": 4864,
"s": 4693,
"text": "I’ve added a column for the assigned treatment as well as columns for each dummy variable. The dummy variable columns will make synthesizing the response variable easier."
},
{
"code": null,
"e": 4927,
"s": 4864,
"text": "How many of each city category was assigned to each treatment?"
},
{
"code": null,
"e": 5330,
"s": 4927,
"text": "Right off the bat we can see some concerns. The Town category is very undersampled relative to the City category (as we expected based off of their abundance in the population). More importantly, there is almost double the Town individuals in Treatment B than in Treatment A. If Town individuals are very different from City individuals, this could be a real problem. (Hint: It will be a problem here.)"
},
{
"code": null,
"e": 5821,
"s": 5330,
"text": "In order to calculate an expected signal, I need to specify the baseline click through probabilities as well as the lift created by the interface change. For this example I assume that City users have a baseline click through probability of 0.3 while users in Towns have a baseline click through probability of 0.1. I then assume that users in the B group will have experience an additional 0.05 increase in their click-through probability. It’s a bit large, but useful in this toy example."
},
{
"code": null,
"e": 5971,
"s": 5821,
"text": "To create response data, I sampled from the binomial distribution for each group according to the probabilities that I listed in the paragraph above."
},
{
"code": null,
"e": 6774,
"s": 5971,
"text": "To break down what is going on in the code block above, start with the np.random.binomial() function. There I am sampling 500 times from a binomial distribution with only one trial each, where the the probability of success is any of the probabilities I just listed (0.3, 0.1, or the other two plus an additional 0.05). Here is where the dummy variables come in handy. Remember that the city column is 1 only when the user is from a city and 0 everywhere else, the same is true for the A, B, and town columns. That means we can multiply each of the four binomial response variables by each of their respective dummy variables, then add all 4 columns together to get one response variable column. This process is analogous to the one used by general linear regression models to analyze categorical data."
},
{
"code": null,
"e": 6854,
"s": 6774,
"text": "From here we can easily conduct a t-test to see if our treatment has an effect."
},
{
"code": null,
"e": 7028,
"s": 6854,
"text": "responseA = completerandom_df['response'][completerandom_df['A']==1]responseB = completerandom_df['response'][completerandom_df['B']==1]stats.ttest_ind(responseA, responseB)"
},
{
"code": null,
"e": 7171,
"s": 7028,
"text": "Running this code gives us a t-statistic of -0.90 and a p-value of 0.37. Not great. If we plot the data we can get an idea of what’s going on."
},
{
"code": null,
"e": 7301,
"s": 7171,
"text": "Now instead of conducting simple random sampling, let’s use stratified random sampling and see how the analytical results change."
},
{
"code": null,
"e": 7425,
"s": 7301,
"text": "So how do we conduct stratified random sampling? Turns out this is pretty similar to the original complete random sampling."
},
{
"code": null,
"e": 7443,
"s": 7425,
"text": "Here’s the steps:"
},
{
"code": null,
"e": 7549,
"s": 7443,
"text": "Define the subpopulations you want to sample fromFrom each subpopulation conduct complete random sampling"
},
{
"code": null,
"e": 7599,
"s": 7549,
"text": "Define the subpopulations you want to sample from"
},
{
"code": null,
"e": 7656,
"s": 7599,
"text": "From each subpopulation conduct complete random sampling"
},
{
"code": null,
"e": 8036,
"s": 7656,
"text": "The way that I like to do this protocol is by creating k lists of indices, one for each of the subpopulations I want to sample. Then I concatenate them into one long list, and use that new index list to extract the data from my original population. I like to do it this way so that I can keep track of how the dataframe was built, but there probably is a more efficient solution."
},
{
"code": null,
"e": 8130,
"s": 8036,
"text": "At this point, I calculate the response variable in the same way as I did above, then run the"
},
{
"code": null,
"e": 8172,
"s": 8130,
"text": "The code for the t-test remains the same:"
},
{
"code": null,
"e": 8330,
"s": 8172,
"text": "responseA = stratified_df['response'][stratified_df['A']==1]responseB = stratified_df['response'][stratified_df['B']==1]stats.ttest_ind(responseA, responseB)"
},
{
"code": null,
"e": 8454,
"s": 8330,
"text": "The output here is a t-value of 2.55 and a p-value of 0.011. Much better than the original complete random sampling regime."
},
{
"code": null,
"e": 8665,
"s": 8454,
"text": "I could conduct a t-test on this data again, just as I did above. However, now that I’ve made sure to sample from both subpopulations I can use an ANOVA to account for some of the variance and boost the signal."
},
{
"code": null,
"e": 8774,
"s": 8665,
"text": "But what happens when we use the extra information of the subpopulation and run a two-way ANOVA on the data?"
},
{
"code": null,
"e": 9097,
"s": 8774,
"text": "model = ols('response ~ treatment + cities', data = stratified_df).fit()aov_table = anova_lm(model, typ=1)print(aov_table) df sum_sq mean_sq F PR(>F)treatment 1 1.16 1.16 6.89 0.0090town_size 1 10.82 10.82 64.47 2.75e-15Residual 997 167.27 0.17 NaN NaN"
},
{
"code": null,
"e": 9866,
"s": 9097,
"text": "The two-way ANOVA is estimating how much each of the variables (treatment and response) contributes to the total error of the response. You can see this output in the sum_sq term in the second column of the table. Based off of this it looks like the cities variable contributes about 9.4X more variance than the treatment variable, which makes sense based on how I constructed the response variable. Also, in this case I’m not getting a much lower p-value for the treatment effect than from a traditional t-test. That’s mainly because the effect of treatment is the same between the two cities. When the effect of treatment is the same across sub groups, whether or not a two-way ANOVA outperforms a simple t-test depends on the exact distribution of the sampled data."
},
{
"code": null,
"e": 9932,
"s": 9866,
"text": "If we look at the plot, we can see why an ANOVA performs so well."
},
{
"code": null,
"e": 10336,
"s": 9932,
"text": "Because we increased the power of our analysis using the stratified random sampling, our initial sample size calculations would be different between a stratified random sampling and a complete random sampling procedure. I will not go into this in depth here, but essentially our estimates of the variance of each population changes when we go from complete random sampling to stratified random sampling."
},
{
"code": null,
"e": 10651,
"s": 10336,
"text": "There are two main takeaways from this article. First, consider conducting stratified random sampling when the signal could be very different between subpopulations. Second, when you use stratified random sampling to conduct an experiment, use an analytical method that can take into account categorical variables."
},
{
"code": null,
"e": 10980,
"s": 10651,
"text": "Overall, stratified random sampling increases the power of your analysis. In the initial complete random sampling experiment, the signal of the A/B test was diluted by the extra variation introduced by the unaccounted for Town subpopulation. Once I accounted for that subpopulation, then the signal of the A/B test became clear."
},
{
"code": null,
"e": 11236,
"s": 10980,
"text": "I hope that helps with your stratified random sampling needs! I’ve added the Jupyter notebook where I conducted this analysis and a similar R script to my GitHub repository. Here are some links for further reading on ANOVAs and stratified random sampling:"
},
{
"code": null,
"e": 11354,
"s": 11236,
"text": "There are a many articles online that go over the different types of sampling methodologies. See here, here, or here."
},
{
"code": null,
"e": 11450,
"s": 11354,
"text": "This course from Penn State goes much deeper into the statistics of stratified random sampling."
},
{
"code": null,
"e": 11526,
"s": 11450,
"text": "Examples of how to conduct an ANOVA on the iris dataset in R and in Python."
}
] |
5 Python Libraries That You Don’t Know About, But Should | by Ismael Araujo | Towards Data Science
|
One of the best things about using Python is its infinity of open-source libraries. There is a library for basically anything. If you have read some of my previous blogs, you may have noticed that I’m a big fan of low-code libraries. That’s not because I’m lazy to type code but because I prefer investing my time working on a project with what really matters. If a library can solve a problem, why not save your precious time and give it a try? Today, I will introduce you to 5 libraries that you probably have never heard about but you should add to your pipeline. Let’s get started!
When you start typing your code for a project, what is your first step? You probably import the libraries you will need, right? The problem is that you never know how many libraries you will need until you need it and get an error. That’s why PyForest is one of the handiest libraries that I know. PyForest can import the 40 most popular libraries to your notebook with one line of code. Forget about trying to remember how to call each library. PyForest can do that for you. I have written a whole blog about it, but in short, you install it, call it, and use it! All that in a few seconds. How about the aliases? Don’t worry about it. They will be imported with the aliases that we are familiar with.
How to use it
Just type pip install pyforest and you are good to go. To import it to your notebook, type from pyforest import * and you can start using your libraries. To check which libraries were imported, type lazy_imports().
All the libraries above are good to use. Technically, they will only be imported if you use them. Otherwise, they will not. You can see libraries such as Pandas, Matplotlib, Seaborn, Tensorflow, Sklearn, NLTK, XGBoost, Plotly, Keras, Numpy, and many others.
I mostly use PyForest for my personal projects or projects that will not be reviewed by other people. If your code will be reviewed by other people, PyForest is not recommended for not making clear that these libraries are being imported.
Emot is a nice-to-have library that has the potential to improve by a lot your next NLP project. It transforms emojis and emoticons into descriptive information. For example, imagine that someone posted “I ❤️ Python” on Twitter. The person didn’t say the word love. Instead, they used an emoji. If you use this tweet in an NLP project, you will have to remove the emoji and lose a big piece of information. That's when Emot comes in. It transforms emojis and emoticons into words. For those who are not familiar, emoticons are ways to express sentiments using characters. For example, :) for a smiley face or :( for a sad face.
How to use
To install it, you can type pip install emot, and you are good to go. Then you will need to import it into your notebook by typing import emot. You will need to decide if you want to figure out the meaning of emojis or emoticons. For emojis, the code is emot.emoji(your_text). Let's check it out with an example:
You can see above that I added the sentence I ❤️ Python 🙂 and used Emot to figure it out. It returned a dictionary with the values, the description, and the location. Like any dictionary, you can slice it and focus on the information that you need. If I type ans['mean'], it will return only the emoji description.
I'm including Geemap to this list, but to be honest, it deserves an entire blog about it. In short, Geemap is a Python library that allows interactive mapping with Google Earth Engine. You are probably familiar with Google Earth and all its power, so why not use it for your next project? I'm planning to create a project to explore all its functionalities in the next few weeks. In the meantime, here is how you can install and start using it.
How to use it
You can install it by typing pip install geemap in your Terminal. To import it to your notebook, you can type import geemap. For demonstration purposes, I will create a folium-based interactive map using the following code:
import geemap.eefolium as geemapMap = geemap.Map(center=[40,-100], zoom=4)Map
As I mentioned, I haven’t explored it as much as it deserves, but they have a complete GitHub README talking more about how it works and what it can do.
I learned about Dabl yesterday, and after doing some research, I found out that it deserves its own blog, but let's cover the basics. Dabl aims to make machine learning modeling more accessible for beginners. For this reason, it uses low-code solutions for machine learning projects. Dabl simplifies data cleaning, creating visualizations, building baseline models, and explaining models. Let's quickly review some of its functionalities.
How to use
First, to install it, you can just type pip install dabl in your terminal. Then, you can import Dabl to your notebook by typing import dabl. You are good to go from here. You can use dabl.clean(data) to get information about features, such as if there is any useless features. It also shows continuous, categorical, and high-cardinality features.
You can use dabl.plot(data) to generate visualizations about a specific feature:
And finally, you can create multiple models with one line of code using dabl.AnyClassifier or dabl.Simplefier() just like you would do using Scikit-Learn. However, in this step, you will have to take some of the steps you would usually take, such as creating training and testing dataset, calling, fitting and predicting the model. Then, you can use Scikit-Learn to evaluate the model.
# Setting X and y variablesX, y = load_digits(return_X_y=True)# Splitting the dataset into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)# Calling the modelsc = dabl.SimpleClassifier().fit(X_train, y_train)# Evaluating accuracy scoreprint(“Accuracy score”, sc.score(X_test, y_test))
As we can see, Dabl iterated through multiple models, including Dummy Classifier, GaussianNB, Decision Trees with different depths, and Logistic Regression. At the end, it shows the best model. All these models in about 10 seconds. Cool, right? I decided to test the final model using Scikit-Learn to make sure that this result was trustworthy. Here is the result:
I got 0.968 accuracy using the conventional way to predict and 0.971 with Dabl. That's close enough for me! Note that I didn't have to import the Logistic Regression model from the Scikit-Learn library because it was already imported with PyForest. I need to confess that I prefer LazyPredict, but Dabl is worth trying. There is much more to show about Dabl, and I will work on a blog exclusively for it with more details. Stay tuned!
Sweetviz is a low-code Python library that generates beautiful visualizations to kickstart your exploratory data analysis with two lines of code. The output is an interactive HTML file. Like other libraries that I mentioned today, SweetViz deserves its own blog, and I will publish one soon. For now, let’s get a high overview of it.
How to use it
my_report = sv.analyze(dataframe)my_report.show_html()
Did you see that? Sweetviz was able to create an EDA HTML file with information about the entire dataset and break it down so that you can analyze each feature individually. You can get the numerical and categorical association to other features, largest, smallest, and most frequent values. The visualization also changes depending on the data type. You can do so much more with Sweetviz, but I will keep it for another blog. In the meantime, I highly recommend you trying it out.
PyForest, Emot, Geemap, Dabl, and Sweetviz are libraries that deserve to be known because it turns complicated tasks into straightforward ones. If you use these libraries, you will save your precious time with tasks that matter.
I recommend you try them out and explore their functionalities that I didn’t mention here. If you do, let me know what you found out about them. You can find the notebook I used to test them in my GitHub. Thank you for reading!
You might also like...
4 Cool Python Libraries That You Should Know About3 Awesome Python Libraries That You Should Know About3 Low-Code Python that You Should Know About
|
[
{
"code": null,
"e": 757,
"s": 171,
"text": "One of the best things about using Python is its infinity of open-source libraries. There is a library for basically anything. If you have read some of my previous blogs, you may have noticed that I’m a big fan of low-code libraries. That’s not because I’m lazy to type code but because I prefer investing my time working on a project with what really matters. If a library can solve a problem, why not save your precious time and give it a try? Today, I will introduce you to 5 libraries that you probably have never heard about but you should add to your pipeline. Let’s get started!"
},
{
"code": null,
"e": 1460,
"s": 757,
"text": "When you start typing your code for a project, what is your first step? You probably import the libraries you will need, right? The problem is that you never know how many libraries you will need until you need it and get an error. That’s why PyForest is one of the handiest libraries that I know. PyForest can import the 40 most popular libraries to your notebook with one line of code. Forget about trying to remember how to call each library. PyForest can do that for you. I have written a whole blog about it, but in short, you install it, call it, and use it! All that in a few seconds. How about the aliases? Don’t worry about it. They will be imported with the aliases that we are familiar with."
},
{
"code": null,
"e": 1474,
"s": 1460,
"text": "How to use it"
},
{
"code": null,
"e": 1689,
"s": 1474,
"text": "Just type pip install pyforest and you are good to go. To import it to your notebook, type from pyforest import * and you can start using your libraries. To check which libraries were imported, type lazy_imports()."
},
{
"code": null,
"e": 1947,
"s": 1689,
"text": "All the libraries above are good to use. Technically, they will only be imported if you use them. Otherwise, they will not. You can see libraries such as Pandas, Matplotlib, Seaborn, Tensorflow, Sklearn, NLTK, XGBoost, Plotly, Keras, Numpy, and many others."
},
{
"code": null,
"e": 2186,
"s": 1947,
"text": "I mostly use PyForest for my personal projects or projects that will not be reviewed by other people. If your code will be reviewed by other people, PyForest is not recommended for not making clear that these libraries are being imported."
},
{
"code": null,
"e": 2814,
"s": 2186,
"text": "Emot is a nice-to-have library that has the potential to improve by a lot your next NLP project. It transforms emojis and emoticons into descriptive information. For example, imagine that someone posted “I ❤️ Python” on Twitter. The person didn’t say the word love. Instead, they used an emoji. If you use this tweet in an NLP project, you will have to remove the emoji and lose a big piece of information. That's when Emot comes in. It transforms emojis and emoticons into words. For those who are not familiar, emoticons are ways to express sentiments using characters. For example, :) for a smiley face or :( for a sad face."
},
{
"code": null,
"e": 2825,
"s": 2814,
"text": "How to use"
},
{
"code": null,
"e": 3138,
"s": 2825,
"text": "To install it, you can type pip install emot, and you are good to go. Then you will need to import it into your notebook by typing import emot. You will need to decide if you want to figure out the meaning of emojis or emoticons. For emojis, the code is emot.emoji(your_text). Let's check it out with an example:"
},
{
"code": null,
"e": 3453,
"s": 3138,
"text": "You can see above that I added the sentence I ❤️ Python 🙂 and used Emot to figure it out. It returned a dictionary with the values, the description, and the location. Like any dictionary, you can slice it and focus on the information that you need. If I type ans['mean'], it will return only the emoji description."
},
{
"code": null,
"e": 3898,
"s": 3453,
"text": "I'm including Geemap to this list, but to be honest, it deserves an entire blog about it. In short, Geemap is a Python library that allows interactive mapping with Google Earth Engine. You are probably familiar with Google Earth and all its power, so why not use it for your next project? I'm planning to create a project to explore all its functionalities in the next few weeks. In the meantime, here is how you can install and start using it."
},
{
"code": null,
"e": 3912,
"s": 3898,
"text": "How to use it"
},
{
"code": null,
"e": 4136,
"s": 3912,
"text": "You can install it by typing pip install geemap in your Terminal. To import it to your notebook, you can type import geemap. For demonstration purposes, I will create a folium-based interactive map using the following code:"
},
{
"code": null,
"e": 4214,
"s": 4136,
"text": "import geemap.eefolium as geemapMap = geemap.Map(center=[40,-100], zoom=4)Map"
},
{
"code": null,
"e": 4367,
"s": 4214,
"text": "As I mentioned, I haven’t explored it as much as it deserves, but they have a complete GitHub README talking more about how it works and what it can do."
},
{
"code": null,
"e": 4806,
"s": 4367,
"text": "I learned about Dabl yesterday, and after doing some research, I found out that it deserves its own blog, but let's cover the basics. Dabl aims to make machine learning modeling more accessible for beginners. For this reason, it uses low-code solutions for machine learning projects. Dabl simplifies data cleaning, creating visualizations, building baseline models, and explaining models. Let's quickly review some of its functionalities."
},
{
"code": null,
"e": 4817,
"s": 4806,
"text": "How to use"
},
{
"code": null,
"e": 5164,
"s": 4817,
"text": "First, to install it, you can just type pip install dabl in your terminal. Then, you can import Dabl to your notebook by typing import dabl. You are good to go from here. You can use dabl.clean(data) to get information about features, such as if there is any useless features. It also shows continuous, categorical, and high-cardinality features."
},
{
"code": null,
"e": 5245,
"s": 5164,
"text": "You can use dabl.plot(data) to generate visualizations about a specific feature:"
},
{
"code": null,
"e": 5631,
"s": 5245,
"text": "And finally, you can create multiple models with one line of code using dabl.AnyClassifier or dabl.Simplefier() just like you would do using Scikit-Learn. However, in this step, you will have to take some of the steps you would usually take, such as creating training and testing dataset, calling, fitting and predicting the model. Then, you can use Scikit-Learn to evaluate the model."
},
{
"code": null,
"e": 5960,
"s": 5631,
"text": "# Setting X and y variablesX, y = load_digits(return_X_y=True)# Splitting the dataset into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)# Calling the modelsc = dabl.SimpleClassifier().fit(X_train, y_train)# Evaluating accuracy scoreprint(“Accuracy score”, sc.score(X_test, y_test))"
},
{
"code": null,
"e": 6325,
"s": 5960,
"text": "As we can see, Dabl iterated through multiple models, including Dummy Classifier, GaussianNB, Decision Trees with different depths, and Logistic Regression. At the end, it shows the best model. All these models in about 10 seconds. Cool, right? I decided to test the final model using Scikit-Learn to make sure that this result was trustworthy. Here is the result:"
},
{
"code": null,
"e": 6760,
"s": 6325,
"text": "I got 0.968 accuracy using the conventional way to predict and 0.971 with Dabl. That's close enough for me! Note that I didn't have to import the Logistic Regression model from the Scikit-Learn library because it was already imported with PyForest. I need to confess that I prefer LazyPredict, but Dabl is worth trying. There is much more to show about Dabl, and I will work on a blog exclusively for it with more details. Stay tuned!"
},
{
"code": null,
"e": 7094,
"s": 6760,
"text": "Sweetviz is a low-code Python library that generates beautiful visualizations to kickstart your exploratory data analysis with two lines of code. The output is an interactive HTML file. Like other libraries that I mentioned today, SweetViz deserves its own blog, and I will publish one soon. For now, let’s get a high overview of it."
},
{
"code": null,
"e": 7108,
"s": 7094,
"text": "How to use it"
},
{
"code": null,
"e": 7163,
"s": 7108,
"text": "my_report = sv.analyze(dataframe)my_report.show_html()"
},
{
"code": null,
"e": 7645,
"s": 7163,
"text": "Did you see that? Sweetviz was able to create an EDA HTML file with information about the entire dataset and break it down so that you can analyze each feature individually. You can get the numerical and categorical association to other features, largest, smallest, and most frequent values. The visualization also changes depending on the data type. You can do so much more with Sweetviz, but I will keep it for another blog. In the meantime, I highly recommend you trying it out."
},
{
"code": null,
"e": 7874,
"s": 7645,
"text": "PyForest, Emot, Geemap, Dabl, and Sweetviz are libraries that deserve to be known because it turns complicated tasks into straightforward ones. If you use these libraries, you will save your precious time with tasks that matter."
},
{
"code": null,
"e": 8102,
"s": 7874,
"text": "I recommend you try them out and explore their functionalities that I didn’t mention here. If you do, let me know what you found out about them. You can find the notebook I used to test them in my GitHub. Thank you for reading!"
},
{
"code": null,
"e": 8125,
"s": 8102,
"text": "You might also like..."
}
] |
Webkiller v2.0 - Tool Information Gathering tool in Kali Linux - GeeksforGeeks
|
11 Sep, 2021
Webkiller is a free and open-source tool available on GitHub. Webkiller is used as an information-gathering tool. Webkiller is used to scan websites for information gathering and finding vulnerabilities in websites and webapps. The whois data collection gives us information about Geoip lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP, and MX records lookup.
Webkiller’s interactive console provides a number of helpful features.
Webkiller is a complete package of Information gathering tools.
Webkiller can be used to find IP Addresses of targets.
Webkiller can be used to look for error-based SQL injections.
Webkiller can be used to find sensitive files such as robots.txt.
Webkiller can be used to find information about Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP using WHOIS lookup.
Webkiller is a free and open-source tool this means you can download and use it free of cost.
Webkiller is a complete package of information-gathering modules.
Webkiller works and acts as a web application/website scanner.
Webkiller is one of the easiest and useful tools for performing reconnaissance.
Webkiller is written in ruby language.
Webkiller interface is very similar to metasploitable 1 and metasploitable 2 that makes it easy to use.
Step 1: Open your Kali Linux operating system and install the tool using the following command and move to the directory using the second command.
git clone https://github.com/ultrasecurity/webkiller.git
cd webkiller
Step 2: Now you are in the directory of Webkiller. Now you have to install the requirements of the tool using the following command.
pip3 install -r requirements.txt
Step 3: Requirement has been covered use the following command to run the tool.
python3 webkiller.py
The tool is running successfully. Now we will see some examples to use the tool.
Example 1: Use the Webkiller tool to find the open and closed port of a domain.
Choose the option 1 information gathering tool.
1
Now use give the domain to the tool:
The tool has found open and closed ports on the <domain>. Similarly, you can find the open and closed port of your own domain.
Example 2: Use the Webkiller tool to find the admin page of a domain.
Choose option :
12
Give the domain address to the tool:
Similarly, you can find the admin pages if available publicly on the internet. Similarly, you can use the tool to find admin pages of the tool. Webkiller is a vulnerability Scanner. Webkiller has the following modules DNS Lookup, WHOIS lookup, GEO-Lookup, Subnet lookup, port scanner, Links extractor, etc. Webkiller can detect closed and open ports of networks.
adnanirshad158
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
tee command in Linux with examples
|
[
{
"code": null,
"e": 24776,
"s": 24748,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 25174,
"s": 24776,
"text": "Webkiller is a free and open-source tool available on GitHub. Webkiller is used as an information-gathering tool. Webkiller is used to scan websites for information gathering and finding vulnerabilities in websites and webapps. The whois data collection gives us information about Geoip lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP, and MX records lookup."
},
{
"code": null,
"e": 25245,
"s": 25174,
"text": "Webkiller’s interactive console provides a number of helpful features."
},
{
"code": null,
"e": 25309,
"s": 25245,
"text": "Webkiller is a complete package of Information gathering tools."
},
{
"code": null,
"e": 25364,
"s": 25309,
"text": "Webkiller can be used to find IP Addresses of targets."
},
{
"code": null,
"e": 25426,
"s": 25364,
"text": "Webkiller can be used to look for error-based SQL injections."
},
{
"code": null,
"e": 25492,
"s": 25426,
"text": "Webkiller can be used to find sensitive files such as robots.txt."
},
{
"code": null,
"e": 25654,
"s": 25492,
"text": "Webkiller can be used to find information about Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP using WHOIS lookup."
},
{
"code": null,
"e": 25748,
"s": 25654,
"text": "Webkiller is a free and open-source tool this means you can download and use it free of cost."
},
{
"code": null,
"e": 25814,
"s": 25748,
"text": "Webkiller is a complete package of information-gathering modules."
},
{
"code": null,
"e": 25877,
"s": 25814,
"text": "Webkiller works and acts as a web application/website scanner."
},
{
"code": null,
"e": 25957,
"s": 25877,
"text": "Webkiller is one of the easiest and useful tools for performing reconnaissance."
},
{
"code": null,
"e": 25996,
"s": 25957,
"text": "Webkiller is written in ruby language."
},
{
"code": null,
"e": 26100,
"s": 25996,
"text": "Webkiller interface is very similar to metasploitable 1 and metasploitable 2 that makes it easy to use."
},
{
"code": null,
"e": 26247,
"s": 26100,
"text": "Step 1: Open your Kali Linux operating system and install the tool using the following command and move to the directory using the second command."
},
{
"code": null,
"e": 26317,
"s": 26247,
"text": "git clone https://github.com/ultrasecurity/webkiller.git\ncd webkiller"
},
{
"code": null,
"e": 26450,
"s": 26317,
"text": "Step 2: Now you are in the directory of Webkiller. Now you have to install the requirements of the tool using the following command."
},
{
"code": null,
"e": 26483,
"s": 26450,
"text": "pip3 install -r requirements.txt"
},
{
"code": null,
"e": 26563,
"s": 26483,
"text": "Step 3: Requirement has been covered use the following command to run the tool."
},
{
"code": null,
"e": 26586,
"s": 26563,
"text": "python3 webkiller.py "
},
{
"code": null,
"e": 26668,
"s": 26586,
"text": "The tool is running successfully. Now we will see some examples to use the tool."
},
{
"code": null,
"e": 26748,
"s": 26668,
"text": "Example 1: Use the Webkiller tool to find the open and closed port of a domain."
},
{
"code": null,
"e": 26796,
"s": 26748,
"text": "Choose the option 1 information gathering tool."
},
{
"code": null,
"e": 26798,
"s": 26796,
"text": "1"
},
{
"code": null,
"e": 26835,
"s": 26798,
"text": "Now use give the domain to the tool:"
},
{
"code": null,
"e": 26962,
"s": 26835,
"text": "The tool has found open and closed ports on the <domain>. Similarly, you can find the open and closed port of your own domain."
},
{
"code": null,
"e": 27032,
"s": 26962,
"text": "Example 2: Use the Webkiller tool to find the admin page of a domain."
},
{
"code": null,
"e": 27048,
"s": 27032,
"text": "Choose option :"
},
{
"code": null,
"e": 27051,
"s": 27048,
"text": "12"
},
{
"code": null,
"e": 27088,
"s": 27051,
"text": "Give the domain address to the tool:"
},
{
"code": null,
"e": 27452,
"s": 27088,
"text": "Similarly, you can find the admin pages if available publicly on the internet. Similarly, you can use the tool to find admin pages of the tool. Webkiller is a vulnerability Scanner. Webkiller has the following modules DNS Lookup, WHOIS lookup, GEO-Lookup, Subnet lookup, port scanner, Links extractor, etc. Webkiller can detect closed and open ports of networks. "
},
{
"code": null,
"e": 27467,
"s": 27452,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27478,
"s": 27467,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27490,
"s": 27478,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27501,
"s": 27490,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27599,
"s": 27501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27608,
"s": 27599,
"text": "Comments"
},
{
"code": null,
"e": 27621,
"s": 27608,
"text": "Old Comments"
},
{
"code": null,
"e": 27659,
"s": 27621,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27694,
"s": 27659,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27729,
"s": 27694,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27770,
"s": 27729,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 27806,
"s": 27770,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27844,
"s": 27806,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27877,
"s": 27844,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 27915,
"s": 27877,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27951,
"s": 27915,
"text": "diff command in Linux with examples"
}
] |
Program to print half Diamond star pattern - GeeksforGeeks
|
31 Dec, 2020
Given an integer N, the task is to print half-diamond-star pattern.
************************************
Examples:
Input: N = 3
Output:
*
**
***
**
*
Input: N = 6
Output:
*
**
***
****
*****
******
*****
****
***
**
*
Approach: The idea is to break the pattern into two halves that is upper half and lower half. Then print then separately with the help of the loops. The key observation for printing the upper half and lower half is described as below:
Upper half: The upper half of the pattern contains star ‘*’ in increasing order where ith line contains following number of star:Number of '*' in ith line =
Number of '*' in ith line =
Lower Half: The lower half of the pattern contains star ‘*’ in decreasing order where ith line contains following number of star:Number of '*' in ith line =
Below is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation to print the// half diamond star pattern #include <iostream> using namespace std; // Function to print the// half diamond star patternvoid halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) cout << "*"; cout << "\n"; } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) cout << "*"; cout << "\n"; }} // Driver Codeint main(){ int N = 5; // Function Call halfDiamondStar(N);}Java// Java implementation to print the// half diamond star patternimport java.util.*; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) System.out.print("*"); System.out.print("\n"); } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) System.out.print("*"); System.out.print("\n"); }} // Driver Codepublic static void main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjanPython3# Python3 implementation to print the # half diamond star pattern # Function to print the # half diamond star pattern def halfDiamondStar(N): # Loop to print the upper half # diamond pattern for i in range(N): for j in range(0, i + 1): print("*", end = "") print() # Loop to print the lower half # diamond pattern for i in range(1, N): for j in range(i, N): print("*", end = "") print() # Driver Code N = 5; # Function Call halfDiamondStar(N); # This code is contributed by skylagsC#// C# implementation to print the// half diamond star patternusing System; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for(i = 0; i < N; i++) { for(j = 0; j < i + 1; j++) Console.Write("*"); Console.Write("\n"); } // Loop to print the lower half // diamond pattern for(i = 1; i < N; i++) { for(j = i; j < N; j++) Console.Write("*"); Console.Write("\n"); }} // Driver Codepublic static void Main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjanOutput:*
**
***
****
*****
****
***
**
*
My Personal Notes
arrow_drop_upSave
Number of '*' in ith line =
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation to print the// half diamond star pattern #include <iostream> using namespace std; // Function to print the// half diamond star patternvoid halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) cout << "*"; cout << "\n"; } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) cout << "*"; cout << "\n"; }} // Driver Codeint main(){ int N = 5; // Function Call halfDiamondStar(N);}
// Java implementation to print the// half diamond star patternimport java.util.*; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) System.out.print("*"); System.out.print("\n"); } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) System.out.print("*"); System.out.print("\n"); }} // Driver Codepublic static void main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjan
# Python3 implementation to print the # half diamond star pattern # Function to print the # half diamond star pattern def halfDiamondStar(N): # Loop to print the upper half # diamond pattern for i in range(N): for j in range(0, i + 1): print("*", end = "") print() # Loop to print the lower half # diamond pattern for i in range(1, N): for j in range(i, N): print("*", end = "") print() # Driver Code N = 5; # Function Call halfDiamondStar(N); # This code is contributed by skylags
// C# implementation to print the// half diamond star patternusing System; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for(i = 0; i < N; i++) { for(j = 0; j < i + 1; j++) Console.Write("*"); Console.Write("\n"); } // Loop to print the lower half // diamond pattern for(i = 1; i < N; i++) { for(j = i; j < N; j++) Console.Write("*"); Console.Write("\n"); }} // Driver Codepublic static void Main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjan
*
**
***
****
*****
****
***
**
*
Rohit_ranjan
skylags
pattern-printing
Python Pattern-printing
C Language
C#
C++
Java
Programming Language
Python
School Programming
pattern-printing
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Arrays of Strings
|
[
{
"code": null,
"e": 24562,
"s": 24534,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 24630,
"s": 24562,
"text": "Given an integer N, the task is to print half-diamond-star pattern."
},
{
"code": null,
"e": 24667,
"s": 24630,
"text": "************************************"
},
{
"code": null,
"e": 24677,
"s": 24667,
"text": "Examples:"
},
{
"code": null,
"e": 24782,
"s": 24677,
"text": "Input: N = 3\nOutput:\n*\n**\n***\n**\n*\n\nInput: N = 6\nOutput:\n*\n**\n***\n****\n*****\n******\n*****\n****\n***\n**\n*\n"
},
{
"code": null,
"e": 25017,
"s": 24782,
"text": "Approach: The idea is to break the pattern into two halves that is upper half and lower half. Then print then separately with the help of the loops. The key observation for printing the upper half and lower half is described as below:"
},
{
"code": null,
"e": 25176,
"s": 25017,
"text": "Upper half: The upper half of the pattern contains star ‘*’ in increasing order where ith line contains following number of star:Number of '*' in ith line = \n"
},
{
"code": null,
"e": 25206,
"s": 25176,
"text": "Number of '*' in ith line = \n"
},
{
"code": null,
"e": 28190,
"s": 25206,
"text": "Lower Half: The lower half of the pattern contains star ‘*’ in decreasing order where ith line contains following number of star:Number of '*' in ith line = \nBelow is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation to print the// half diamond star pattern #include <iostream> using namespace std; // Function to print the// half diamond star patternvoid halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) cout << \"*\"; cout << \"\\n\"; } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) cout << \"*\"; cout << \"\\n\"; }} // Driver Codeint main(){ int N = 5; // Function Call halfDiamondStar(N);}Java// Java implementation to print the// half diamond star patternimport java.util.*; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) System.out.print(\"*\"); System.out.print(\"\\n\"); } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) System.out.print(\"*\"); System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjanPython3# Python3 implementation to print the # half diamond star pattern # Function to print the # half diamond star pattern def halfDiamondStar(N): # Loop to print the upper half # diamond pattern for i in range(N): for j in range(0, i + 1): print(\"*\", end = \"\") print() # Loop to print the lower half # diamond pattern for i in range(1, N): for j in range(i, N): print(\"*\", end = \"\") print() # Driver Code N = 5; # Function Call halfDiamondStar(N); # This code is contributed by skylagsC#// C# implementation to print the// half diamond star patternusing System; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for(i = 0; i < N; i++) { for(j = 0; j < i + 1; j++) Console.Write(\"*\"); Console.Write(\"\\n\"); } // Loop to print the lower half // diamond pattern for(i = 1; i < N; i++) { for(j = i; j < N; j++) Console.Write(\"*\"); Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjanOutput:*\n**\n***\n****\n*****\n****\n***\n**\n*\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28220,
"s": 28190,
"text": "Number of '*' in ith line = \n"
},
{
"code": null,
"e": 28271,
"s": 28220,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28275,
"s": 28271,
"text": "C++"
},
{
"code": null,
"e": 28280,
"s": 28275,
"text": "Java"
},
{
"code": null,
"e": 28288,
"s": 28280,
"text": "Python3"
},
{
"code": null,
"e": 28291,
"s": 28288,
"text": "C#"
},
{
"code": "// C++ implementation to print the// half diamond star pattern #include <iostream> using namespace std; // Function to print the// half diamond star patternvoid halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) cout << \"*\"; cout << \"\\n\"; } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) cout << \"*\"; cout << \"\\n\"; }} // Driver Codeint main(){ int N = 5; // Function Call halfDiamondStar(N);}",
"e": 28922,
"s": 28291,
"text": null
},
{
"code": "// Java implementation to print the// half diamond star patternimport java.util.*; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for (i = 0; i < N; i++) { for (j = 0; j < i + 1; j++) System.out.print(\"*\"); System.out.print(\"\\n\"); } // Loop to print the lower half // diamond pattern for (i = 1; i < N; i++) { for (j = i; j < N; j++) System.out.print(\"*\"); System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjan",
"e": 29672,
"s": 28922,
"text": null
},
{
"code": "# Python3 implementation to print the # half diamond star pattern # Function to print the # half diamond star pattern def halfDiamondStar(N): # Loop to print the upper half # diamond pattern for i in range(N): for j in range(0, i + 1): print(\"*\", end = \"\") print() # Loop to print the lower half # diamond pattern for i in range(1, N): for j in range(i, N): print(\"*\", end = \"\") print() # Driver Code N = 5; # Function Call halfDiamondStar(N); # This code is contributed by skylags",
"e": 30244,
"s": 29672,
"text": null
},
{
"code": "// C# implementation to print the// half diamond star patternusing System; class GFG{ // Function to print the// half diamond star patternstatic void halfDiamondStar(int N){ int i, j; // Loop to print the upper half // diamond pattern for(i = 0; i < N; i++) { for(j = 0; j < i + 1; j++) Console.Write(\"*\"); Console.Write(\"\\n\"); } // Loop to print the lower half // diamond pattern for(i = 1; i < N; i++) { for(j = i; j < N; j++) Console.Write(\"*\"); Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(String[] args){ int N = 5; // Function Call halfDiamondStar(N);}} // This code is contributed by Rohit_ranjan",
"e": 30962,
"s": 30244,
"text": null
},
{
"code": null,
"e": 30997,
"s": 30962,
"text": "*\n**\n***\n****\n*****\n****\n***\n**\n*\n"
},
{
"code": null,
"e": 31010,
"s": 30997,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 31018,
"s": 31010,
"text": "skylags"
},
{
"code": null,
"e": 31035,
"s": 31018,
"text": "pattern-printing"
},
{
"code": null,
"e": 31059,
"s": 31035,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 31070,
"s": 31059,
"text": "C Language"
},
{
"code": null,
"e": 31073,
"s": 31070,
"text": "C#"
},
{
"code": null,
"e": 31077,
"s": 31073,
"text": "C++"
},
{
"code": null,
"e": 31082,
"s": 31077,
"text": "Java"
},
{
"code": null,
"e": 31103,
"s": 31082,
"text": "Programming Language"
},
{
"code": null,
"e": 31110,
"s": 31103,
"text": "Python"
},
{
"code": null,
"e": 31129,
"s": 31110,
"text": "School Programming"
},
{
"code": null,
"e": 31146,
"s": 31129,
"text": "pattern-printing"
},
{
"code": null,
"e": 31151,
"s": 31146,
"text": "Java"
},
{
"code": null,
"e": 31155,
"s": 31151,
"text": "CPP"
},
{
"code": null,
"e": 31253,
"s": 31155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31288,
"s": 31253,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 31316,
"s": 31288,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 31362,
"s": 31316,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 31374,
"s": 31362,
"text": "fork() in C"
},
{
"code": null,
"e": 31406,
"s": 31374,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 31460,
"s": 31406,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 31522,
"s": 31460,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 31550,
"s": 31522,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 31592,
"s": 31550,
"text": "String.Split() Method in C# with Examples"
}
] |
How to set font for Text in Tkinter?
|
Tkinter has many inbuilt methods and functions which are used to provide different features in the widgets. We can customize the font-property of text widget in a tkinter application using the font(‘font-family’,font-size, ‘style’) attribute. The tuple can be declared inside the Text constructor.
Let us have a look at the following example where we will create a text widget with a customized font property.
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Define a text widget with font-property
text= Text(win, height=15, font=('Times New Roman',17,'bold'))
text.insert(INSERT, "Hey Folks!, Welcome to TutorialsPoint!")
text.pack()
win.mainloop()
Running the above code will display a window that contains a text widget. The text written inside the text widget can be customized using the font property.
|
[
{
"code": null,
"e": 1360,
"s": 1062,
"text": "Tkinter has many inbuilt methods and functions which are used to provide different features in the widgets. We can customize the font-property of text widget in a tkinter application using the font(‘font-family’,font-size, ‘style’) attribute. The tuple can be declared inside the Text constructor."
},
{
"code": null,
"e": 1851,
"s": 1360,
"text": "Let us have a look at the following example where we will create a text widget with a customized font property.\n#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n#Define a text widget with font-property\ntext= Text(win, height=15, font=('Times New Roman',17,'bold'))\ntext.insert(INSERT, \"Hey Folks!, Welcome to TutorialsPoint!\")\ntext.pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2008,
"s": 1851,
"text": "Running the above code will display a window that contains a text widget. The text written inside the text widget can be customized using the font property."
}
] |
Introduction to Reinforcement Learning (DDPG and TD3) for News Recommendation | by Mikhail Scherbina | Towards Data Science
|
TL;DR: Reinforcement Learning is the ideal framework for a recommendation system because it has Markov Property. The state is movies rated by a user. Action is the movie chosen to watch next and the reward is its rating. I made a DDPG/TD3 implementation of the idea. The main section of the article covers implementation details, discusses parameter choice for RL, introduces novel concepts of action evaluation, addresses the optimizer choice (Radam for life), and analyzes the results.
I also had released an ml20m dataset version specifically adopted for Markov decision process and to use with RL.
Reinforcement learning as-is is a pretty hard topic. When I started to dig deeper, I realized the need for a good explanation. This article, coupled with the code is my school project. I am currently in a sophomore year of high school, and I understand the hard mathematical concepts in a more ‘social studies’ kind of way. I hope this article proves to be helpful for newcomers like me.
I created a GitHub project you can clone and follow along! Make sure to check it out. You can download everything that I processed on my PC in the downloads section. As well as FAQ, dataset description, some docs, how-tos and more. It is frequently updated. I haven’t pushed for a week because I was writing this article. I hope you like it! https://github.com/awarebayes/RecNN
This article provides a comparison of the most popular recommendation methods as well as an in-depth look at various reinforcement learning algorithms, overviewing each tweakable parameter and the aftermath of changing it. I also propose alternative ways to evaluate deep learning-powered recommenders and discuss different optimizers for that application. It is also my legacy because my final year of high school is coming, so I won’t have enough time to work on it. If you are interested in supporting the project, your contributions are welcome!
Static vs. Dynamic time series dataset
Why you should HDF5
Encoding time series
Similarity search
Matrix Factorization
Restricted Boltzmann machines
Factorization Machines
Reinforcement Learning
Methods comparison
Information Theory in Deep Learning
Information Plane Theorem
Why do embeddings=’bottleneck features’ make sense
Markov property, chains, games, and decisions
Reward vs .Value
Continuous State Markov Process
Simple explanation
Advanced explanation
Implementing in code
Why it doesn’t work
Optimizer choice
Results
Explanation
Implementation
Results
PPO: Proximal Policy Optimization
GAIL: Generative Adversarial Imitation Learning
Firstly, because of the frustration with the dataset being dynamic. When I started prototyping, it used to take more than 40 hours for just one iteration. With basic pandas and its optimization done, it shrinks down to 1.5. When I implemented dynamic dataset, the thing takes 10 minutes. If you encode the states with state representation, it comes down to 3. Also, I couldn’t get the DDPG working at all, and it added quite some impact. Thus, I ended up using a static time series dataset + TD3. However, more about it later.
However, above all, most of the articles on TDS are paid. Thus there are no premium articles, no Patreon, no money begging. You can clap to this article multiple times (please do so with the button up left) and go to the GitHub page and star the repo.
It is my school project, and starring, it is essential to me. It would also give me better chances at winning the project competition, maybe even university payment cut-offs.
As you can see, pandas can be optimized, but in the end, it is still quite costly to run because even my best optimization does not scale well. The x-axis represents the power of 10. The y-axis is the time it took (in seconds). Also, the thing with deep learning is that we often run the model on the same dataset over and over. So it would make total sense to make our dataset completely static, eliminating all pandas interaction whatsoever. Let’s just run our dataset generator and save the results. If you have forked my repo and following along, the notebook is located under notes/1. Vanilla RL/1. Generating the static dataset.ipynb. Note: It is entirely mandatory; you can download the dataset generated by me.
Sometimes the time-series cannot be entirely fed into your RAM. Also, the HDF5 format was developed specifically for that purpose. Use whenever possible because it works way faster than PyTorch and natively comes with numpy support. The only limit is your solid-state disk so you might want to buy a PCI Express one with fast reading.
If you are using a static size time series (also called ‘rolling’ ts), make sure you encode the data into lower dimensions. For the classic ML approach, we have Principal Component Analysis or PCA for short. Here is a video if this is a new word for you.
You can also use LSTM Autoencoders for dynamic length Time Series. From my experiments, I noticed that linear AEs perform poorly for rolling ts. However, I use state representation as the authors of the paper proposed. Rule #1337 of DL states that 90% of the actual learning happens in the first 10 minutes. So I ran the TD3 model and used its state representation module to encode the TS.
When I first started to dig into the stuff, it realized that there is no comprehensive guide to even basic techniques of recommendation. I recently had found out about Restricted Boltzmann Machines. This section aims to fix it. I attempt to overview some of the most popular ones and make a quick comparison. For more analytical results, look at the memes below.
SS is the most straightforward concept to understand. Just look for similar films liked or disliked among the users. State (being the films rated) is often represented as a metric space. There are a couple of ways to encode it from raw movies indexes. The first one is to use the embedding layer, which is often the case in modern DL applications. A similarity metric such as cosine or Euclidean distance is then used to rank them nicely. However, looking back to a more classical ML approach, we have the Locality Sensitive Hashing. LSH is an algorithmic technique that hashes similar input items into the same “buckets” with high probability. Either way, we end up with a bunch of ranked states that are similar to the one we are predicting for. Then we look at the films the users liked/disliked and recommend them. If you want to use this method, I suggest you check out Facebook’s Faiss library: GitHub link.
The idea of factorizing matrices, i.e., breaking a big matrix into a product of smaller ones, further extends similarity search. The big matrix can be expressed as a table with rows being the movies, columns being the users, and the values are the ratings. We extend that idea by assuming that the big matrix can be expressed as a dot product of two smaller matrices. They represent the hidden (embedding) representation. The process can is easily implemented using PyTorch:
user_matrix = user_embedding(users)film_matrix = film_embedding(films)ratings = (user_matrix * film_matrix).sum(1)loss = MeanSquares(ratings, target_ratings)loss.backward()
‘Users’ is an integer vector of userId. ‘Films’ is an integer vector of film_id. User and Film matrices are 2D embeddings for corresponding indexes. We calculate the dot product because we want to know the rating. As you might have noticed, the method is pretty limited due to the usage of embeddings. You cannot add new films/users to the existing ones unless you are using something like Incremental SGNS or Reservoir Computing. Just a good overview article of the methods above: link. Also, if you want to get an in-depth understanding of MF, I highly recommend this video by Luis Serrano.
RBS is an early variant of an autoencoder. It falls under the energy-based methods. As an autoencoder, it is used for dimensionality reduction. The restricted part of the naming means that there is no interlayer propagation. The architecture looks like a usual two-layered linear network. The forward pass looks precisely like the feedforward net.
The critical difference is that RBMs are probabilistic. They use Bayes stuff to work. Whenever you try to calculate the state of the network, i.e., the sample from these weights and biases distributions, you are met with the Boltzmann equation. It is an equation from particle physics. The learning of such model consists of two main steps: Gibbs Sampling and Contrastive divergence.
I found out about these machines from Andrew Ng’s interviews with Geoffrey Hinton. When asked about his greatest achievement, the latter acknowledged his contributions to training algorithms of RBMs. Just a reminder: G.H. is a man behind backpropagation. Indeed RBMs achieve state-of-the-art performance in the Netflix competition. If you want to learn more about the energy-based models: here are Yann LeCun’s notes.
Factorization Machines had proven to be super useful for click-through rate prediction. Their speed allows them to be highly scalable, but they are only applicable to data with categorical features. Nevertheless, they are worth a shout out. We need to incorporate feature data into our factorization process somehow. Of course, we can consider a single feature to be resourceful enough:
ratings = linear(features.size(1), 1)loss = MeanSquares(ratings, target_ratings)loss.backward()
As you can see, they cannot be used for a personalized recommendation!
However, it would be cool to take label-label cross-correlations of a feature into consideration. We just learned about the concept of order. Order is the number of features calculating the cross-correlation for. Assuming the order to be 2, we need to calculate the CC for two features. Nevertheless, the feature is a categorical variable, so how does one calculate the dot product for two cats? More latent variables to the god of the latent variables! Feature labels can be described using vectors, and those vectors can be regressed using the same idea of embeddings we utilized for matrix factorization.
ratings = linear(features.size(1), 1)(features)# factorization machinelatent = latent_embeddings(features)latent_gram = latent * latent.Tfeatures_gram = features * features.Tratings += (latent_gram * features_gram).sum(1)loss = MeanSquares(ratings, target_ratings)loss.backward()
Here is an article that helped me to understand this concept better: link.
The key advantages of using RL for news recommendation are Markov Property and State Representation. Because we do not rely on any embeddings, we can recommend any movies to any user. Movie embeddings generated for this application do not rely on the embedding layer. I used simple statistics, such as average rating, revenue, TF-IDF for texts, genres, etc.... + PCA. Thus, you can add a new movie for a recommendation without re-training the network. Alternatively, you can use these new embeddings for state representation. Markov property ensures that we can use static-length time series. More about it later.
warning: satire
To sum it up: RL allows learning on minibatches of any size, input of static length time series, does not depend on static embeddings, works on the client-side, can be used for transfer learning, has an adjustable adversary rate (in TD3), supports ensembling, works way faster than MF, and retains Markov Property. The most significant trade-off is the accuracy: big corporations such as Netflix/Amazon still rely on MF/RBM.
This particular application, unlike Q-Learning, aims to solve the continuous control problem. In Q-Learning state is often continuous, but the action itself is discrete. Whereas in our case, the action (=movie) is not discrete, but it is a vector instead.
But how do we get this vector we will be trying to somehow regress later on? Last time I checked the ML20M dataset, there were no vectors to be found. The answer is simple: I generated these vector representation of numerically indexed movies myself. Most of the stuff is trivial: I parsed the IMDB/TMDB data and applied basic statistics to make a vector of the gathered data (by encoding categories, using TF-IDF, applying PCA) But one of the most important things I utilized is Google’s BERT for text data embeddings. I know, embeddings are technically a different thing, and these are called ‘bottleneck features’, but I will stick to that word.
However, why does some middle layer of a neural network make sense? Why can you use that data as contextual information? Those questions are answered by the field of studies called Information Theory. It is not widely popular in the context of DL, but there are fascinating lectures by Naftali Tishby about the `maximization of preserved information` and other hints of why the nets learn. I recommend you to check these out!
Some highlights:
00:19:00 Information Plane Theorem — for a sizeable typical X, the sample complexity of a DNN is entirely determined by the mutual encoder information, I(X, T), of the last hidden layer; the decoder information determines the accuracy (generalization error), I(T, Y), of the previous hidden layer. This phenomenon is the thing I use in this app. You can see the visualization of this phenomenon at 00:23.
https://www.youtube.com/watch?v=pFWiauHOFpY
Now that we got our dataset working, understood how I transformed movie IDs into contextual vectors, it’s time to recap some things about reinforcement learning and game theory. If you read Arxiv papers on DL/RL, is is a common thing to see the basics sorted out.
News Recommendation can be thought of as a game that we are trying to win. We act based on the state, and the state is what we know about the user: ratings and movies watched combined. The action is produced based on the state and describes a point in space.
Everything from now on strictly obeys the Markov Property. Quoting Wikipedia: ‘ A stochastic process has the Markov property if the conditional probability distribution of future states of the process (conditional on both past and present states) depends only upon the present state, not on the sequence of events that preceded it.’ Why should I care, you might ask. We assume that we can act only based on the current state, ignoring anything that happened before. Having that in mind, the problem becomes way more natural to solve because we don’t have to worry about the past. Markov methods provide a framework that allows you to focus on the things that happen at the moment.
You also have heard that name, because DeepMind’s AlphaGo uses Markov Chain Monte Carlo. Monte Carlo part is only used for finite-state games such as chess or go. However, Markov Chains are everywhere! For simplicity purposes, let’s consider a discrete state. We are also assuming that recommendation is a stochastic process meaning that we randomly walk over the dataset. Like any other physical chain, Markov Chain consists of ‘loops’ called nodes. Each node has a conditional transition probability. Think about is as a random graph walk, and each node that is currently visited has probabilities that determine which adjacent node goes next. Here is a short article with 19k likes that goes into details. The cool thing is that it preserves the Markov property: transition is only dependent on the current state, being the node visited.
The idea of Markov Chains can be further applied to our ‘game’. We want to utilize the Markov Framework for our application because it is super handy. However, how do you apply an abstract chain to state-action-reward-state-action... process? Remember the graph example I introduced? Markov decision process can also be interpreted as a graph. We assume our current State to be some node in the graph. Because it retains that exact property, we don’t need to know anything that happened before we arrived at that State (node). From that node, there is a multitude of actions that can be taken with assigned probabilities. These actions can be interpreted as adjacent edges that bring us to the New_State. When we arrive at the new State, we immediately receive a Reward. There is also one thing in the dataset that is used for TD — Done because we don’t want to propagate temporal difference beyond the last step. Although, more about it later.
The dataset I built consists of State-Action-Reward-Next_State-Done values. There is an example on GitHub
One last thing to fully understand what is happening is that action is not discrete. I already have mentioned a couple of times that the action is a vector. I can understand how to move in the graph based on a discrete number, but where do you go with a vector? So instead of graphs think about the MDP as an N-dimensional plane. For simplicity purposes, I will use a 2D plane as an example. Let’s consider an ant agent moving on the playground. At the moment he knows that he probably needs to bring some leaves to its house. The only problem is there is no such discrete action ‘hard coded’ into its brain. So it needs to take continuous steps in the environment: move his limbs, clitch his jaws, and avoid the evil antlion. With each step it takes, the reward is added. It might be some realization that the leaves are somewhere nearby, and it is going in the right direction. One other important distinction is that we assume that time steps are discrete. The recommendation is only possible if we know a certain number of films and the ratings assigned by the user. It would be weird to try to suggest something taking 5.6 films and 1.3 ratings into consideration.
And if you look at the ‘continuous vs. discrete action ’ example above, there is a MuJoCo Ant agent. It takes limb positions and angular velocities as an input to supply the environment. Actually, there are a lot more funny agents to fiddle with such as cheetah and Boston Dynamics robot models.
.
.
.
This part is essential for understanding the Temporal Difference Loss, which will be covered a little bit later. In the context of Markov Games, we have such thing as the Value Function. So the Value Function does not imply a function that estimates the Reward. Value can only mean how good the action is for the current state. Although, as you will see, it does not necessarily mean ‘give me the reward’ for that action and state. It is a more abstract measure of ‘goodness’ and can be expressed as a continuous real-valued function. The range of the function can be any real number. Thus, the value is not an integer number in [-5, 5].
Now let’s forget for a brief moment about all the Markov stuff that we learned and try to get started with a basic DL approach. So you decided to build a deep-learning-powered recommender system, already know about Markov Decision process and the dataset structure, overall very eager to jump straight into the action. Let’s try a more fundamental approach, without reinforcement learning just yet. All you have is a simple linear perceptron and the dataset: a bunch of states, corresponding actions, and rewards to those actions. Translated to more human language: films watched, the movie chosen to see next and its rating by the user. I want you to go ahead and think about the things you would do with these tools.
We want to suggest good movies; hence, we train the network to generate movies like the action:
generated_action = model(state)if is_good(reward): loss = MeanSquares(generated_action, action) loss.backward()
This approach is called ‘Policy Learning’ because we learn the policy, being the action. It has its applications, but in the endpoint, PL is very limited. If you train a network like this, it will work fine and be somewhat usable. Still, did you notice the ‘is_good’ function? We learn only using ‘good’ actions, disregarding anything else.
So far we’d been looking at the reward as our ‘learning’ criteria. However, wouldn’t it be wiser to analyze the action instead? That is the main idea behind the Actor-Critic methods. For clarity’s sake, let me introduce the namings for the networks. The network we already contemplated is called Actor, and it acts based on the state. The network that tries to predict the reward based on the state and the Actor’s action is called Critic. As we all know, from watching Bob Ross: everyone needs a friend. So let’s add to our lonely Actor someone to mock his actions.
#teach the criticgenerated_reward = critic(state, action)reward_loss = MeanSquares(generated_reward, reward)reward_loss.backward()# teach the actorgenerated_action = actor(state)value = critic(state, generated_action)if value > 0: # learn the action action_loss = MeanSquares(generated_action, action) # learn action action_loss.backward()
Eventually it the actor will do better actions (maybe maybe maybe) and the loss will converge to zero or something. However, since that, we are working in the chad Pytorch; we can do wacky things with losses without worrying about the backpropagation! What if we want to directly use the critic-produced reward for the actor-generated action as a loss metric? With Pytorch it has never been easier!
#teach the criticgenerated_reward = critic(state, action)reward_loss = MeanSquares(generated_reward, reward)reward_loss.backward()# teach the actorgenerated_action = actor(state)action_loss = -critic(state, generated_action)action_loss.backward()
What we did here is that we used the critic as our loss function! As it was intended since the beginning. Note the minus before the criterion. We want to maximize the rewards. Still, there is no such thing as ‘maximize’ in machine learning. We often do the opposite: minimizing the negatives.
That is the DDPG algorithm. Although, if you look in the paper, the code for the critic training will be different. That’s what we are covering next.
There is something wrong with our Critic. We don’t need to estimate the rewards. Let’s bootstrap the Value for the action instead. Why might you ask? The answer is simple: future rewards may be dependant on the current action. Considering the actions as individual Markov chain steps, we want to maximize the Value. What is Value?
Value in the context of a Markov Game is a real-valued function: V(state, action) that indicates (not in terms of integer rewards -5 to 5, it can be any real number) how proper the particular action for the corresponding state.
So that’s where we need to bring back our Markov Chains. In this particular application, I use TD(1) version of the algorithm, meaning that I bootstrap the value 1 step in advance. You can implement TD(n), but the number of value iterations increases linearly.
To learn the value function, we bootstrap the reward and the value of the next state and text action. You can read more about TD here.
# train the actornext_action = actor(state)action_loss = -critic(state, next_action)action_loss.backward()reward_loss.backward()# train the criticnext_value= critic(next_state, next_action )expected_value = reward + next_valuevalue = value_net(state, action)value_loss = MeanSquares(value, expected_value))
There is only one last thing you need to understand the DDPG completely. It uses the concept of Target and Learning networks. Target network is more stable rather than the learning one because it is updated using learning parameters through the soft update. It shows less tendency to overfit and overall performs better. Also, the TD loss is slightly tweaked. We don’t need to bootstrap the value for endgame actions. Gamma parameter serves for stability, and I set it to around 0.9.
# train the actoraction_loss = -critic(state, actor(state))action_loss.backward()# train the criticnext_action = target_actor(state)target_value= target_critic(next_state, next_action )expected_value = reward + (1 — done) * gamma * next_valuevalue = value_net(state, action)value_loss = MeanSquares(value, expected_value))value_loss.backward()# soft updatedef soft_update(*networks, soft_tau=1e-2): for target, learning in networks.parameters(): target= target.data * (1.0 — soft_tau) + learning .data * soft_tausoft_update(actor, target_actor)soft_update(critic, target critic)
Here is the actual screenshot of the update function I use
That is basically what DDPG is about.
In the next section, we will try to compare and, primarily, evaluate different reinforcement learning algorithms. But how do we tell if the results are good or not? The critic network assigns the values to our actions; however, are you sure whether the value is meaningful. Well, they are based on critic loss. If critic loss is small and the policy loss makes sense, we taught the actor. But those metrics are not enough. I also consider euclidean and cosine distances for actions. A matrix often represents this. You can see the distances described as individual grid pieces varying by color. The warmer it is, the bigger the distance. For instance here is how real actions (those I produced with statistics embeddings) look like.
You will see similar matrices for training and testing actions later on. Another method to evaluate the ‘artificiality’ of actions is to use the autoencoder reconstruction error. I train the autoencoder model to reconstruct the embedding actions. The reconstruction error is used as artificiality metric. This technique is widely used for anomaly detection because it is unsupervised. Also, I perform Kernel Density Estimation on the error distribution for pretty plotting and visual comparison. Wasserstein distance or KL Divergence can also be implied.
The goal is to make the generated test distribution close to the true (real) one. Generated train (or just generated) may be of different forms.
All I did at this point is copypasting Higgsfield’s RL adventure code with minor tweaks to work with torch 1.1
It looks like we have something! Matrices look cool? Some correlation is showing up... The loss is descending... Wait, say what is on the scale bar? Why do I have next to no cosine distances? Why is the policy loss falling into the nether realm? Why don’t my pet AIs work as supposed?
And that’s when it comes to the true joy of RL!
Countless things can go wrong! Maybe I should play around wit the learning rate? Admittedly, that’s the first thing that comes in mind for a person familiar with DL. However, why my error is growing in the first place? I haven’t encountered these things in the DL... WTF is happening with the v-net optimization, PyTorch? It doesn’t seem to have much of an impact as the process starts, but then the gradients explode, and everything goes into oblivion... So, likely, the learning rate is excellent. Maybe that’s because of the Temporal Difference bootstrapping? But not only does the TDB use the target value network, which is soft updated via soft tau, the TD it also utilizes a parameter called gamma for weighting the future expectation.
P_gamma = 0.9P_min_value=-5P_max_value=5P_soft_tau=1e-2P_policy_lr = 1e-5P_value_lr = 1e-6P_actor_init_w = 3e-4P_critic_init_w = 3e-4
What am I supposed to tweak? Maybe I set the wrong parameter for clipping the value:
expected_value = torch.clamp(expected_value, min_value, max_value)
One thing that came as a bamboozler to me is that the weight inits trick works slightly differently than one would expect. If we initialize the last layer’s weights of the net with smaller numbers, it will generate smaller vectors. Wrong! It works exactly the opposite. So it is the main reason for the cosine distance being so short in comparison to the distribution of the real action. However, it doesn’t seem to have much of an effect for Euclidean.
Also, have you noticed the min and max parameters for the value clipping are min and max rewards, respectively? That also needs to be changed, as I mentioned it back in the Markov property stuff. I set it to reward * n_td_steps. That works fine, and at the end, the loss rarely goes below 6–7 at most.
You may not realize it, but a smaller learning rate for critic leads to actor overfitting. If the policy loss falls weirdly fast, change the LR, because the actor is overfitting. Keep in mind: not the most intuitive thing!
Always debug and keep track of the following parameters: value, target_value (mean, std), expected_value (mean, std), generated_action (cosine distances, Gramian, variance, std, means, samples KL distance to the original distribution). Always plot those metrics at the end of the testing.
P_critic_init_w=3e-5P_actor_init_w=3e-1P_min_value=-10 # or -100P_max_value=10 # or 100
We solved the RL part of a not working network, now the reasons for the loss to grow are purely DL. Here are some bits of advice for you:
Play around with the optimizers. There are so many of them for a reason. Start with Adam, try Hinton’s RMS prop, pure SGD, SGD with warm restarts and CosineAnnealingLR. Although, if you don’t care, there is a neat new algorithm for you to try out! It’s called RAdam: GitHub link. I use it whenever possible because it reduces the number of parameters to optimize. It is later explained.Use grad_clip extremely carefully. Using it on the value network changes the sign of the value function. I don’t understand why that is the case. But policy seems to work just fine. I spend almost a week figuring it out. No, for real.Weight decay is crucial to avoid overfitting. Moreover, it is easy to use with Pytorch optimizers. Set it to a smaller value, and the exploding gradients are gone within seconds. Also, use it with grad clip for the actor.
Play around with the optimizers. There are so many of them for a reason. Start with Adam, try Hinton’s RMS prop, pure SGD, SGD with warm restarts and CosineAnnealingLR. Although, if you don’t care, there is a neat new algorithm for you to try out! It’s called RAdam: GitHub link. I use it whenever possible because it reduces the number of parameters to optimize. It is later explained.
Use grad_clip extremely carefully. Using it on the value network changes the sign of the value function. I don’t understand why that is the case. But policy seems to work just fine. I spend almost a week figuring it out. No, for real.
Weight decay is crucial to avoid overfitting. Moreover, it is easy to use with Pytorch optimizers. Set it to a smaller value, and the exploding gradients are gone within seconds. Also, use it with grad clip for the actor.
This is supposed to bring back to life the DDPG on your/mine data.
Value network learning rate — affects Euclidean distanced between the generated action. It also improves the cosine distance, but on a smaller scale. Only works for SGD/Adam and does not matter for Radam.
Actor Weight Initialization — changes the diversity of the cosine distances in the action space. If you see next to no variance in your action distances, start by changing this parameter.
Soft tau — is responsible for the target network update. It affects the delay of the ‘rollercoaster’ of the loss function applied to the target network. You can see that both losses resemble each other. If you run the code, you will see that value loss slowly translates into the policy loss. As I said, it influences the smoothness of such translation. It is another critical parameter to consider if something does not work for you, but don’t overestimate it.
Gamma — is the weight of expected_action in temporal difference. Imho is not so important. Smaller values may lead to gradient explosions.
Min/Max values — I set them to +- 10. You can experiment with another large number. Alternatively, you can use x*n_td_iterations where x is min/max possible reward. It makes the learning process more rigid but defies the value function property. Alternatively, if you don’t care at all about the rollercoaster losses, you can use numpy infinity. The parameter has a positive influence on the value test loss.
Always look at the scale of the loss function. The value should be somewhere between [0, 10], whereas policy within min/max values for TD clipping. If it goes up to 10e7, you are wasting your time debugging!
I already paid attention to this, but I cannot stress it enough. Always use the state of the art optimizer. Check Arxiv daily, subscribe to the twitter bot and be on a lookout, because the Machine Learning community is now at its peak of productiveness.
Adam is often the default choice for optimization. Moreover, this should be changed. Adam is one of the worst options you have. Why? It’s very very learning rate sensitive. Thinking back about the learning rate schedulers: carefully memorizing which step to put the milestone at, using CosineAnnealingLR warm restarts SGD, CyclicLR. Everything of the techniques above is now in the past — no more fiddling with the learning rate. Just use RAdam! On the Variance of the Adaptive Learning Rate and Beyond!
RAdam is an ideological extension of Adam, and it uses a smart trick called Learning Rate Warmups. Unfortunately, the authors of Radam were not welcome enough to make the Medium article free, so there will be no detailed explanation. You can read their Axriv paper.
Nevertheless, I claim that just by changing the optimizer, I was able to achieve TD3 like performance with DDPG algorithm. And with way less overfitting in both cases
Here is how the Adam loss looks like. One does not have to be a Ph.D. to spot clear value overfitting. Also, do you notice the Policy Loss? It seems strangely small. The max reward is 5, and max TD clipping is 10.
Train actions seem to overfit, not much of Euclidean Distance is showing up, but alright...
Loss seems to be reasonable at 7.5. Or does it? Alright, let’s look at the autoencoder reconstruction error.
You can spot that something is wrong just by looking at the ae rec error distributions and/or comparing various metrics between them. The dumbest choice would be only to calculate KL/WDistance. You can also look at more meaningful statistical metrics such as mean/std/kurtosis/skewness instead.
CosDist < 0.4, Euc < 3. No words needed. Also, an observation by me: Cosine matrix defines an angle distribution of the direction of vectors. You can use basic math to visualize it.
Woah, that’s some good memory! I wish I could memorize that much. Unfortunately, that is not leaning. You can jump straight inro TD3, and it will undoubtedly help with the overfitting, but let’s try to use the RAdam instead. Just change optim.Adam to RAdam when you define the optimizers.
So I ran the same code with RAdam, and that’s what happened.
First Off — no nasty Value Overfitting. Moreover, the value loss is less. The convergence is way more delayed in comparison to Adam. There you can see a clear drop trend at around 400. Here it takes twice as many iterations to notice the pattern. Also, value loss is much smoother. The train actions are way more apart in terms of the Euclidean distance. The cosine dist seems to be preserved across all the experiments. All right, let’s see the test actions:
The results speak for themselves! Test distribution is approximated way better with RAdam, but the training one is more obscure. Nevertheless, we only care about testing.
However, RAdam comes with a drawback. It is hard to finetune models with it. If you leave the model running with RAdam, the training distribution will quickly converge to the true one. Also, the testing distro will be something like a small pine cone at the very right. Need to look out for the Policy loss approaching -5, or manually stop the learning. This is what happens if you do not stop it:
The policy network overfits: values are quickly dropping. It is not the case with Adam.
My end solution was to combine the two optimizers. First, I learn with RAdam, by creating checkpoints before overfitting I ensure that I have an excellent warmed up model. Then I load these models and train them with Adam to achieve even better performance. Unfortunately, there is no room for automatization: you find the smallest policy loss and start from the nearest checkpoint.
It results in better representation of the training distro, but the testing one is way worse. But this method of fine-tuning will be more useful for the TD3 algorithm. Which we are switching onto... Now!
P.S. all models are available for downloading on the github page(including raw Radam and Adam fine-tuned)
TD3 stands for Twin Delayed DDPG. Three is the number of improvements the authors of the paper propose. As I already stated, it is an extension of Deep Deterministic Policy Gradients. The differences are the following:
Double Q Learning with no clip. We have two value networks in this algorithm. Also, instead of clipping the expected value, we take the smallest of target values. This simple trick drastically reduces the chance of policy agent exploiting and fooling the critic, because now it has to fool both of them.
Double Q Learning with no clip. We have two value networks in this algorithm. Also, instead of clipping the expected value, we take the smallest of target values. This simple trick drastically reduces the chance of policy agent exploiting and fooling the critic, because now it has to fool both of them.
#ddpgtarget_q_value = target_value_net(next_state, next_action)expected_value = reward + (1.0 - done) * gamma * target_q_valueexpected_value = torch.clamp(expected_value, min_value, max_value)#td3target_q_value1 = target_value_net1(next_state, next_action)target_q_value2 = target_value_net2(next_state, next_action)target_q_value = torch.min(target_q_value1, target_q_value2)expected_value = reward + (1.0 - done) * gamma * target_q_value
2. Delayed Policy Updates. We update policy less frequently in comparison to values. For each three value update, we update the actor just once. This allows for better value estimation and also prevents actor fooling. P.S. it is not a hard concept and is super easy to implement. I used delayed policy updates with DDPG.
3. Action smoothing. TD3 adds noise to the target action, to make it harder for the policy to exploit Q-function errors by smoothing out Q along with changes in action. In my case, the noise is drawn from ~Normal(0, 0.1) and clipped to fit [-.3, .3].
next_action = target_policy_net(next_state)noise = torch.normal(torch.zeros(next_action.size()), noise_std)noise = torch.clamp(noise, -noise_clip, noise_clip)next_action += noise
The algorithm has pretty much the same parameters as the same as the DDPG (excluding min/max clip, adding noise params). All the code/dataset/pretrained models are on GitHub. TD3 is located under notes/1. Vanilla RL/2.ddpg
Phew! We’ve made it! What you see is my final result for the On-Policy methods. Now let’s discuss the losses and other stuff. First off: value loss is growing. This phenomenon is reasonable because if we look at the values, they are not overfitting. In ddpg, they were increasing and then decreasing again.
The distances cosine distances in real and generated actions differ. It is something around ~0.6 is generated whereas the real ones are ~1. It can be increased by setting the noise std to a higher value. However, I consider it cheating because we add more noise. Alternatively, you can use another loss function in couple with policy loss to add more cosine diversity
In one of my older commits, I implemented cosine and euclidian distance loss penalties with the new Pytorch JIT compiler. P.S. it returns the pairwise distance matrix, like the ones shown above. You can do whatever you want with this thing (i.e., compare variance, std, mean, KL) to make it look like one of the real actions.
@torch.jit.scriptdef torch_cdist_euc(x1, x2): x1_norm = x1.pow(2).sum(dim=-1, keepdim=True) x2_norm = x2.pow(2).sum(dim=-1, keepdim=True) res = torch.addmm(x2_norm.transpose(-2, -1), x1, x2.transpose(-2, -1), alpha=-2).add_(x1_norm) res = res.clamp_min_(1e-30).sqrt_() return res@torch.jit.scriptdef torch_cdist_cos(x1, x2): x1_norm = x1 / x1.norm(dim=1, p=2).unsqueeze(1) x2_norm = x2 / x2.norm(dim=1, p=2).unsqueeze(1) res = 1 - torch.mm(x1_norm, x2_norm.transpose(0,1)) return res
It’s time to test our algorithms. You can download all the pre-trained models and test them yourself. The file is under notes/results/1. Ranking/ (clickable).
Below you will see examples of distance ranking. It supports scipy. spatial distances or your ones. In the notebook, I included the following: euclidean, cosine, correlation, Canberra, Minkowski, Chebyshev, Bray-Curtis, and city block (Manhatten). Cosine ranking allows for better language and genres diversity and looks very similar to correlation.
That is it! You can see all the ranking examples for both of the algorithms here.
So here we are. Congratulations if you have finally made it. It might seem like a simple project: just using the existing Higgsfield’s algorithm implementation for new data, but I had been working 6 hours a day for the last month to get it working, to figure out the parameters in DDPG, and to understand the depths of PyTorch although the article was the hardest part of it. I am already writing this conclusion, but I haven’t finished Restricted Boltzmann Machines in the comparison section yet. The repo is unpushed. I wonder how it had turned out... Did you understand it?
TD3 implementation is promising. Moreover, the ranking works fine, although there is room for improvement. I am using O(n) algorithm. Highly recommend you check out the Milvus library if you want to use embeddings in production.
I am also yet to implement a web app. Already got a commit on my other repo with react and basic layout. Hopefully, it will be published soon. If not, you can do it yourself: all the models are released.
I honestly don’t have much else to say. I am passing 7131 words already.
Anyway here are some ideas from me:
Because it is recommendation project, you could use top k ranking for action. Those ranking results can be used to help the learning process:
Because it is recommendation project, you could use top k ranking for action. Those ranking results can be used to help the learning process:
You could add another loss that would calculate distances between real ranked and generated actions. (Another loss for the critic)
How different is the Value function for the ranked actions? Can it be further adjusted concerning the distances?
2. Add yet another cosine/euclidean loss to the generated actions. The scripts are published above.
3. Implement a ranking network. It is an extension of the policy. It takes action as input and learns to generate real actions based on top k ranking.
If you happen to implement these, feel free to commit.
Medium: Ping Guo, 임한동[ 학부재학 / 기계공학부 ], Jacky Noah, Shady Hassab, Alexander Makeev, Shivam Akhauri, Diksha Garg, Siddharth Prabhu, Zohar Komarovsky, Hary Prasad, Panagiotis Kapros, Vishal Shrinivas, Yvette Li, Lxs Lxs, Nils Schluter, Ayush Kumar, Dean Soe, Cody Bushnell, Marcus Au, باربری تهران اتوبار تهران, Navi Xie, Sang Huynh, Simon Yu, Yuzhou Zhang, Hoglan Huang, Lambjed Ben, Axel Schwanke, Anirban Saha, Baris Can Tauris, Mingju He, Jean-Philippe Corbeil, Shoaib Hafiz — It was your follow that made me feel somewhat important for the community.
GitHub: navy-xie, KnightofK9, tomatatto, lystahi, jungi21cc, nutorbit, davidjiangt, kiminh, hb1500, YerinMin, Saleh-Hassan, ImranRolo, limtete, erikson92, miladfa7, sudongtan, Belobobr, noaRricky, q710245300, andrebola, chenmingxia, ashdtu, dindanovitasari, kk-hainq, bazitur, youyiandyou, Vi-Sri, sanjmen, YvetteLi — You believed in my project back before it was implemented. Those starts begiventh by thee motivated me to keep on working.
DeepLearningSchool (www.dlschool.org) I wouldn’t be writing this article if it wasn’t for your excellent lessons and mentoring. Hope I make it to MIPT in the next year.
Feel free to tell about yourself. I started deep learning when I went to high school. Although, back then, I created countless GitHub projects of other thematics, that were by no means less ambitious. The only problem was that no one knew about it — not a single soul except for a couple of friends. If you are working hard on something, be sure to tell you about it. It’s other’s appreciation that keeps you moving forward. P.S. don’t write yet another Keras for preschoolers tutorial ;)
Recently I have published a new article covering reinforce recommender systems:
towardsdatascience.com
Next article will address some problems with the fact that we have no exploration. It surely will take some time to make, but as I see it BCQ easily integrates with the DDPG. If you want to know more about RL applications with a static dataset here are these links:
Arxiv article: https://arxiv.org/abs/1812.02900
Pytorch Code: https://github.com/sfujim/BCQ
Have some questions? The comments are open...
GitHub repo: https://github.com/awarebayes/RecNN
Don’t forget to clap!
|
[
{
"code": null,
"e": 660,
"s": 172,
"text": "TL;DR: Reinforcement Learning is the ideal framework for a recommendation system because it has Markov Property. The state is movies rated by a user. Action is the movie chosen to watch next and the reward is its rating. I made a DDPG/TD3 implementation of the idea. The main section of the article covers implementation details, discusses parameter choice for RL, introduces novel concepts of action evaluation, addresses the optimizer choice (Radam for life), and analyzes the results."
},
{
"code": null,
"e": 774,
"s": 660,
"text": "I also had released an ml20m dataset version specifically adopted for Markov decision process and to use with RL."
},
{
"code": null,
"e": 1162,
"s": 774,
"text": "Reinforcement learning as-is is a pretty hard topic. When I started to dig deeper, I realized the need for a good explanation. This article, coupled with the code is my school project. I am currently in a sophomore year of high school, and I understand the hard mathematical concepts in a more ‘social studies’ kind of way. I hope this article proves to be helpful for newcomers like me."
},
{
"code": null,
"e": 1540,
"s": 1162,
"text": "I created a GitHub project you can clone and follow along! Make sure to check it out. You can download everything that I processed on my PC in the downloads section. As well as FAQ, dataset description, some docs, how-tos and more. It is frequently updated. I haven’t pushed for a week because I was writing this article. I hope you like it! https://github.com/awarebayes/RecNN"
},
{
"code": null,
"e": 2090,
"s": 1540,
"text": "This article provides a comparison of the most popular recommendation methods as well as an in-depth look at various reinforcement learning algorithms, overviewing each tweakable parameter and the aftermath of changing it. I also propose alternative ways to evaluate deep learning-powered recommenders and discuss different optimizers for that application. It is also my legacy because my final year of high school is coming, so I won’t have enough time to work on it. If you are interested in supporting the project, your contributions are welcome!"
},
{
"code": null,
"e": 2129,
"s": 2090,
"text": "Static vs. Dynamic time series dataset"
},
{
"code": null,
"e": 2149,
"s": 2129,
"text": "Why you should HDF5"
},
{
"code": null,
"e": 2170,
"s": 2149,
"text": "Encoding time series"
},
{
"code": null,
"e": 2188,
"s": 2170,
"text": "Similarity search"
},
{
"code": null,
"e": 2209,
"s": 2188,
"text": "Matrix Factorization"
},
{
"code": null,
"e": 2239,
"s": 2209,
"text": "Restricted Boltzmann machines"
},
{
"code": null,
"e": 2262,
"s": 2239,
"text": "Factorization Machines"
},
{
"code": null,
"e": 2285,
"s": 2262,
"text": "Reinforcement Learning"
},
{
"code": null,
"e": 2304,
"s": 2285,
"text": "Methods comparison"
},
{
"code": null,
"e": 2340,
"s": 2304,
"text": "Information Theory in Deep Learning"
},
{
"code": null,
"e": 2366,
"s": 2340,
"text": "Information Plane Theorem"
},
{
"code": null,
"e": 2417,
"s": 2366,
"text": "Why do embeddings=’bottleneck features’ make sense"
},
{
"code": null,
"e": 2463,
"s": 2417,
"text": "Markov property, chains, games, and decisions"
},
{
"code": null,
"e": 2480,
"s": 2463,
"text": "Reward vs .Value"
},
{
"code": null,
"e": 2512,
"s": 2480,
"text": "Continuous State Markov Process"
},
{
"code": null,
"e": 2531,
"s": 2512,
"text": "Simple explanation"
},
{
"code": null,
"e": 2552,
"s": 2531,
"text": "Advanced explanation"
},
{
"code": null,
"e": 2573,
"s": 2552,
"text": "Implementing in code"
},
{
"code": null,
"e": 2593,
"s": 2573,
"text": "Why it doesn’t work"
},
{
"code": null,
"e": 2610,
"s": 2593,
"text": "Optimizer choice"
},
{
"code": null,
"e": 2618,
"s": 2610,
"text": "Results"
},
{
"code": null,
"e": 2630,
"s": 2618,
"text": "Explanation"
},
{
"code": null,
"e": 2645,
"s": 2630,
"text": "Implementation"
},
{
"code": null,
"e": 2653,
"s": 2645,
"text": "Results"
},
{
"code": null,
"e": 2687,
"s": 2653,
"text": "PPO: Proximal Policy Optimization"
},
{
"code": null,
"e": 2735,
"s": 2687,
"text": "GAIL: Generative Adversarial Imitation Learning"
},
{
"code": null,
"e": 3262,
"s": 2735,
"text": "Firstly, because of the frustration with the dataset being dynamic. When I started prototyping, it used to take more than 40 hours for just one iteration. With basic pandas and its optimization done, it shrinks down to 1.5. When I implemented dynamic dataset, the thing takes 10 minutes. If you encode the states with state representation, it comes down to 3. Also, I couldn’t get the DDPG working at all, and it added quite some impact. Thus, I ended up using a static time series dataset + TD3. However, more about it later."
},
{
"code": null,
"e": 3514,
"s": 3262,
"text": "However, above all, most of the articles on TDS are paid. Thus there are no premium articles, no Patreon, no money begging. You can clap to this article multiple times (please do so with the button up left) and go to the GitHub page and star the repo."
},
{
"code": null,
"e": 3689,
"s": 3514,
"text": "It is my school project, and starring, it is essential to me. It would also give me better chances at winning the project competition, maybe even university payment cut-offs."
},
{
"code": null,
"e": 4408,
"s": 3689,
"text": "As you can see, pandas can be optimized, but in the end, it is still quite costly to run because even my best optimization does not scale well. The x-axis represents the power of 10. The y-axis is the time it took (in seconds). Also, the thing with deep learning is that we often run the model on the same dataset over and over. So it would make total sense to make our dataset completely static, eliminating all pandas interaction whatsoever. Let’s just run our dataset generator and save the results. If you have forked my repo and following along, the notebook is located under notes/1. Vanilla RL/1. Generating the static dataset.ipynb. Note: It is entirely mandatory; you can download the dataset generated by me."
},
{
"code": null,
"e": 4743,
"s": 4408,
"text": "Sometimes the time-series cannot be entirely fed into your RAM. Also, the HDF5 format was developed specifically for that purpose. Use whenever possible because it works way faster than PyTorch and natively comes with numpy support. The only limit is your solid-state disk so you might want to buy a PCI Express one with fast reading."
},
{
"code": null,
"e": 4998,
"s": 4743,
"text": "If you are using a static size time series (also called ‘rolling’ ts), make sure you encode the data into lower dimensions. For the classic ML approach, we have Principal Component Analysis or PCA for short. Here is a video if this is a new word for you."
},
{
"code": null,
"e": 5388,
"s": 4998,
"text": "You can also use LSTM Autoencoders for dynamic length Time Series. From my experiments, I noticed that linear AEs perform poorly for rolling ts. However, I use state representation as the authors of the paper proposed. Rule #1337 of DL states that 90% of the actual learning happens in the first 10 minutes. So I ran the TD3 model and used its state representation module to encode the TS."
},
{
"code": null,
"e": 5751,
"s": 5388,
"text": "When I first started to dig into the stuff, it realized that there is no comprehensive guide to even basic techniques of recommendation. I recently had found out about Restricted Boltzmann Machines. This section aims to fix it. I attempt to overview some of the most popular ones and make a quick comparison. For more analytical results, look at the memes below."
},
{
"code": null,
"e": 6665,
"s": 5751,
"text": "SS is the most straightforward concept to understand. Just look for similar films liked or disliked among the users. State (being the films rated) is often represented as a metric space. There are a couple of ways to encode it from raw movies indexes. The first one is to use the embedding layer, which is often the case in modern DL applications. A similarity metric such as cosine or Euclidean distance is then used to rank them nicely. However, looking back to a more classical ML approach, we have the Locality Sensitive Hashing. LSH is an algorithmic technique that hashes similar input items into the same “buckets” with high probability. Either way, we end up with a bunch of ranked states that are similar to the one we are predicting for. Then we look at the films the users liked/disliked and recommend them. If you want to use this method, I suggest you check out Facebook’s Faiss library: GitHub link."
},
{
"code": null,
"e": 7140,
"s": 6665,
"text": "The idea of factorizing matrices, i.e., breaking a big matrix into a product of smaller ones, further extends similarity search. The big matrix can be expressed as a table with rows being the movies, columns being the users, and the values are the ratings. We extend that idea by assuming that the big matrix can be expressed as a dot product of two smaller matrices. They represent the hidden (embedding) representation. The process can is easily implemented using PyTorch:"
},
{
"code": null,
"e": 7313,
"s": 7140,
"text": "user_matrix = user_embedding(users)film_matrix = film_embedding(films)ratings = (user_matrix * film_matrix).sum(1)loss = MeanSquares(ratings, target_ratings)loss.backward()"
},
{
"code": null,
"e": 7906,
"s": 7313,
"text": "‘Users’ is an integer vector of userId. ‘Films’ is an integer vector of film_id. User and Film matrices are 2D embeddings for corresponding indexes. We calculate the dot product because we want to know the rating. As you might have noticed, the method is pretty limited due to the usage of embeddings. You cannot add new films/users to the existing ones unless you are using something like Incremental SGNS or Reservoir Computing. Just a good overview article of the methods above: link. Also, if you want to get an in-depth understanding of MF, I highly recommend this video by Luis Serrano."
},
{
"code": null,
"e": 8254,
"s": 7906,
"text": "RBS is an early variant of an autoencoder. It falls under the energy-based methods. As an autoencoder, it is used for dimensionality reduction. The restricted part of the naming means that there is no interlayer propagation. The architecture looks like a usual two-layered linear network. The forward pass looks precisely like the feedforward net."
},
{
"code": null,
"e": 8638,
"s": 8254,
"text": "The critical difference is that RBMs are probabilistic. They use Bayes stuff to work. Whenever you try to calculate the state of the network, i.e., the sample from these weights and biases distributions, you are met with the Boltzmann equation. It is an equation from particle physics. The learning of such model consists of two main steps: Gibbs Sampling and Contrastive divergence."
},
{
"code": null,
"e": 9056,
"s": 8638,
"text": "I found out about these machines from Andrew Ng’s interviews with Geoffrey Hinton. When asked about his greatest achievement, the latter acknowledged his contributions to training algorithms of RBMs. Just a reminder: G.H. is a man behind backpropagation. Indeed RBMs achieve state-of-the-art performance in the Netflix competition. If you want to learn more about the energy-based models: here are Yann LeCun’s notes."
},
{
"code": null,
"e": 9443,
"s": 9056,
"text": "Factorization Machines had proven to be super useful for click-through rate prediction. Their speed allows them to be highly scalable, but they are only applicable to data with categorical features. Nevertheless, they are worth a shout out. We need to incorporate feature data into our factorization process somehow. Of course, we can consider a single feature to be resourceful enough:"
},
{
"code": null,
"e": 9539,
"s": 9443,
"text": "ratings = linear(features.size(1), 1)loss = MeanSquares(ratings, target_ratings)loss.backward()"
},
{
"code": null,
"e": 9610,
"s": 9539,
"text": "As you can see, they cannot be used for a personalized recommendation!"
},
{
"code": null,
"e": 10218,
"s": 9610,
"text": "However, it would be cool to take label-label cross-correlations of a feature into consideration. We just learned about the concept of order. Order is the number of features calculating the cross-correlation for. Assuming the order to be 2, we need to calculate the CC for two features. Nevertheless, the feature is a categorical variable, so how does one calculate the dot product for two cats? More latent variables to the god of the latent variables! Feature labels can be described using vectors, and those vectors can be regressed using the same idea of embeddings we utilized for matrix factorization."
},
{
"code": null,
"e": 10498,
"s": 10218,
"text": "ratings = linear(features.size(1), 1)(features)# factorization machinelatent = latent_embeddings(features)latent_gram = latent * latent.Tfeatures_gram = features * features.Tratings += (latent_gram * features_gram).sum(1)loss = MeanSquares(ratings, target_ratings)loss.backward()"
},
{
"code": null,
"e": 10573,
"s": 10498,
"text": "Here is an article that helped me to understand this concept better: link."
},
{
"code": null,
"e": 11187,
"s": 10573,
"text": "The key advantages of using RL for news recommendation are Markov Property and State Representation. Because we do not rely on any embeddings, we can recommend any movies to any user. Movie embeddings generated for this application do not rely on the embedding layer. I used simple statistics, such as average rating, revenue, TF-IDF for texts, genres, etc.... + PCA. Thus, you can add a new movie for a recommendation without re-training the network. Alternatively, you can use these new embeddings for state representation. Markov property ensures that we can use static-length time series. More about it later."
},
{
"code": null,
"e": 11203,
"s": 11187,
"text": "warning: satire"
},
{
"code": null,
"e": 11628,
"s": 11203,
"text": "To sum it up: RL allows learning on minibatches of any size, input of static length time series, does not depend on static embeddings, works on the client-side, can be used for transfer learning, has an adjustable adversary rate (in TD3), supports ensembling, works way faster than MF, and retains Markov Property. The most significant trade-off is the accuracy: big corporations such as Netflix/Amazon still rely on MF/RBM."
},
{
"code": null,
"e": 11884,
"s": 11628,
"text": "This particular application, unlike Q-Learning, aims to solve the continuous control problem. In Q-Learning state is often continuous, but the action itself is discrete. Whereas in our case, the action (=movie) is not discrete, but it is a vector instead."
},
{
"code": null,
"e": 12533,
"s": 11884,
"text": "But how do we get this vector we will be trying to somehow regress later on? Last time I checked the ML20M dataset, there were no vectors to be found. The answer is simple: I generated these vector representation of numerically indexed movies myself. Most of the stuff is trivial: I parsed the IMDB/TMDB data and applied basic statistics to make a vector of the gathered data (by encoding categories, using TF-IDF, applying PCA) But one of the most important things I utilized is Google’s BERT for text data embeddings. I know, embeddings are technically a different thing, and these are called ‘bottleneck features’, but I will stick to that word."
},
{
"code": null,
"e": 12959,
"s": 12533,
"text": "However, why does some middle layer of a neural network make sense? Why can you use that data as contextual information? Those questions are answered by the field of studies called Information Theory. It is not widely popular in the context of DL, but there are fascinating lectures by Naftali Tishby about the `maximization of preserved information` and other hints of why the nets learn. I recommend you to check these out!"
},
{
"code": null,
"e": 12976,
"s": 12959,
"text": "Some highlights:"
},
{
"code": null,
"e": 13381,
"s": 12976,
"text": "00:19:00 Information Plane Theorem — for a sizeable typical X, the sample complexity of a DNN is entirely determined by the mutual encoder information, I(X, T), of the last hidden layer; the decoder information determines the accuracy (generalization error), I(T, Y), of the previous hidden layer. This phenomenon is the thing I use in this app. You can see the visualization of this phenomenon at 00:23."
},
{
"code": null,
"e": 13425,
"s": 13381,
"text": "https://www.youtube.com/watch?v=pFWiauHOFpY"
},
{
"code": null,
"e": 13689,
"s": 13425,
"text": "Now that we got our dataset working, understood how I transformed movie IDs into contextual vectors, it’s time to recap some things about reinforcement learning and game theory. If you read Arxiv papers on DL/RL, is is a common thing to see the basics sorted out."
},
{
"code": null,
"e": 13948,
"s": 13689,
"text": "News Recommendation can be thought of as a game that we are trying to win. We act based on the state, and the state is what we know about the user: ratings and movies watched combined. The action is produced based on the state and describes a point in space."
},
{
"code": null,
"e": 14629,
"s": 13948,
"text": "Everything from now on strictly obeys the Markov Property. Quoting Wikipedia: ‘ A stochastic process has the Markov property if the conditional probability distribution of future states of the process (conditional on both past and present states) depends only upon the present state, not on the sequence of events that preceded it.’ Why should I care, you might ask. We assume that we can act only based on the current state, ignoring anything that happened before. Having that in mind, the problem becomes way more natural to solve because we don’t have to worry about the past. Markov methods provide a framework that allows you to focus on the things that happen at the moment."
},
{
"code": null,
"e": 15470,
"s": 14629,
"text": "You also have heard that name, because DeepMind’s AlphaGo uses Markov Chain Monte Carlo. Monte Carlo part is only used for finite-state games such as chess or go. However, Markov Chains are everywhere! For simplicity purposes, let’s consider a discrete state. We are also assuming that recommendation is a stochastic process meaning that we randomly walk over the dataset. Like any other physical chain, Markov Chain consists of ‘loops’ called nodes. Each node has a conditional transition probability. Think about is as a random graph walk, and each node that is currently visited has probabilities that determine which adjacent node goes next. Here is a short article with 19k likes that goes into details. The cool thing is that it preserves the Markov property: transition is only dependent on the current state, being the node visited."
},
{
"code": null,
"e": 16415,
"s": 15470,
"text": "The idea of Markov Chains can be further applied to our ‘game’. We want to utilize the Markov Framework for our application because it is super handy. However, how do you apply an abstract chain to state-action-reward-state-action... process? Remember the graph example I introduced? Markov decision process can also be interpreted as a graph. We assume our current State to be some node in the graph. Because it retains that exact property, we don’t need to know anything that happened before we arrived at that State (node). From that node, there is a multitude of actions that can be taken with assigned probabilities. These actions can be interpreted as adjacent edges that bring us to the New_State. When we arrive at the new State, we immediately receive a Reward. There is also one thing in the dataset that is used for TD — Done because we don’t want to propagate temporal difference beyond the last step. Although, more about it later."
},
{
"code": null,
"e": 16521,
"s": 16415,
"text": "The dataset I built consists of State-Action-Reward-Next_State-Done values. There is an example on GitHub"
},
{
"code": null,
"e": 17691,
"s": 16521,
"text": "One last thing to fully understand what is happening is that action is not discrete. I already have mentioned a couple of times that the action is a vector. I can understand how to move in the graph based on a discrete number, but where do you go with a vector? So instead of graphs think about the MDP as an N-dimensional plane. For simplicity purposes, I will use a 2D plane as an example. Let’s consider an ant agent moving on the playground. At the moment he knows that he probably needs to bring some leaves to its house. The only problem is there is no such discrete action ‘hard coded’ into its brain. So it needs to take continuous steps in the environment: move his limbs, clitch his jaws, and avoid the evil antlion. With each step it takes, the reward is added. It might be some realization that the leaves are somewhere nearby, and it is going in the right direction. One other important distinction is that we assume that time steps are discrete. The recommendation is only possible if we know a certain number of films and the ratings assigned by the user. It would be weird to try to suggest something taking 5.6 films and 1.3 ratings into consideration."
},
{
"code": null,
"e": 17987,
"s": 17691,
"text": "And if you look at the ‘continuous vs. discrete action ’ example above, there is a MuJoCo Ant agent. It takes limb positions and angular velocities as an input to supply the environment. Actually, there are a lot more funny agents to fiddle with such as cheetah and Boston Dynamics robot models."
},
{
"code": null,
"e": 17989,
"s": 17987,
"text": "."
},
{
"code": null,
"e": 17991,
"s": 17989,
"text": "."
},
{
"code": null,
"e": 17993,
"s": 17991,
"text": "."
},
{
"code": null,
"e": 18631,
"s": 17993,
"text": "This part is essential for understanding the Temporal Difference Loss, which will be covered a little bit later. In the context of Markov Games, we have such thing as the Value Function. So the Value Function does not imply a function that estimates the Reward. Value can only mean how good the action is for the current state. Although, as you will see, it does not necessarily mean ‘give me the reward’ for that action and state. It is a more abstract measure of ‘goodness’ and can be expressed as a continuous real-valued function. The range of the function can be any real number. Thus, the value is not an integer number in [-5, 5]."
},
{
"code": null,
"e": 19350,
"s": 18631,
"text": "Now let’s forget for a brief moment about all the Markov stuff that we learned and try to get started with a basic DL approach. So you decided to build a deep-learning-powered recommender system, already know about Markov Decision process and the dataset structure, overall very eager to jump straight into the action. Let’s try a more fundamental approach, without reinforcement learning just yet. All you have is a simple linear perceptron and the dataset: a bunch of states, corresponding actions, and rewards to those actions. Translated to more human language: films watched, the movie chosen to see next and its rating by the user. I want you to go ahead and think about the things you would do with these tools."
},
{
"code": null,
"e": 19446,
"s": 19350,
"text": "We want to suggest good movies; hence, we train the network to generate movies like the action:"
},
{
"code": null,
"e": 19558,
"s": 19446,
"text": "generated_action = model(state)if is_good(reward): loss = MeanSquares(generated_action, action) loss.backward()"
},
{
"code": null,
"e": 19899,
"s": 19558,
"text": "This approach is called ‘Policy Learning’ because we learn the policy, being the action. It has its applications, but in the endpoint, PL is very limited. If you train a network like this, it will work fine and be somewhat usable. Still, did you notice the ‘is_good’ function? We learn only using ‘good’ actions, disregarding anything else."
},
{
"code": null,
"e": 20466,
"s": 19899,
"text": "So far we’d been looking at the reward as our ‘learning’ criteria. However, wouldn’t it be wiser to analyze the action instead? That is the main idea behind the Actor-Critic methods. For clarity’s sake, let me introduce the namings for the networks. The network we already contemplated is called Actor, and it acts based on the state. The network that tries to predict the reward based on the state and the Actor’s action is called Critic. As we all know, from watching Bob Ross: everyone needs a friend. So let’s add to our lonely Actor someone to mock his actions."
},
{
"code": null,
"e": 20806,
"s": 20466,
"text": "#teach the criticgenerated_reward = critic(state, action)reward_loss = MeanSquares(generated_reward, reward)reward_loss.backward()# teach the actorgenerated_action = actor(state)value = critic(state, generated_action)if value > 0: # learn the action action_loss = MeanSquares(generated_action, action) # learn action action_loss.backward()"
},
{
"code": null,
"e": 21205,
"s": 20806,
"text": "Eventually it the actor will do better actions (maybe maybe maybe) and the loss will converge to zero or something. However, since that, we are working in the chad Pytorch; we can do wacky things with losses without worrying about the backpropagation! What if we want to directly use the critic-produced reward for the actor-generated action as a loss metric? With Pytorch it has never been easier!"
},
{
"code": null,
"e": 21452,
"s": 21205,
"text": "#teach the criticgenerated_reward = critic(state, action)reward_loss = MeanSquares(generated_reward, reward)reward_loss.backward()# teach the actorgenerated_action = actor(state)action_loss = -critic(state, generated_action)action_loss.backward()"
},
{
"code": null,
"e": 21745,
"s": 21452,
"text": "What we did here is that we used the critic as our loss function! As it was intended since the beginning. Note the minus before the criterion. We want to maximize the rewards. Still, there is no such thing as ‘maximize’ in machine learning. We often do the opposite: minimizing the negatives."
},
{
"code": null,
"e": 21895,
"s": 21745,
"text": "That is the DDPG algorithm. Although, if you look in the paper, the code for the critic training will be different. That’s what we are covering next."
},
{
"code": null,
"e": 22226,
"s": 21895,
"text": "There is something wrong with our Critic. We don’t need to estimate the rewards. Let’s bootstrap the Value for the action instead. Why might you ask? The answer is simple: future rewards may be dependant on the current action. Considering the actions as individual Markov chain steps, we want to maximize the Value. What is Value?"
},
{
"code": null,
"e": 22454,
"s": 22226,
"text": "Value in the context of a Markov Game is a real-valued function: V(state, action) that indicates (not in terms of integer rewards -5 to 5, it can be any real number) how proper the particular action for the corresponding state."
},
{
"code": null,
"e": 22715,
"s": 22454,
"text": "So that’s where we need to bring back our Markov Chains. In this particular application, I use TD(1) version of the algorithm, meaning that I bootstrap the value 1 step in advance. You can implement TD(n), but the number of value iterations increases linearly."
},
{
"code": null,
"e": 22850,
"s": 22715,
"text": "To learn the value function, we bootstrap the reward and the value of the next state and text action. You can read more about TD here."
},
{
"code": null,
"e": 23157,
"s": 22850,
"text": "# train the actornext_action = actor(state)action_loss = -critic(state, next_action)action_loss.backward()reward_loss.backward()# train the criticnext_value= critic(next_state, next_action )expected_value = reward + next_valuevalue = value_net(state, action)value_loss = MeanSquares(value, expected_value))"
},
{
"code": null,
"e": 23641,
"s": 23157,
"text": "There is only one last thing you need to understand the DDPG completely. It uses the concept of Target and Learning networks. Target network is more stable rather than the learning one because it is updated using learning parameters through the soft update. It shows less tendency to overfit and overall performs better. Also, the TD loss is slightly tweaked. We don’t need to bootstrap the value for endgame actions. Gamma parameter serves for stability, and I set it to around 0.9."
},
{
"code": null,
"e": 24220,
"s": 23641,
"text": "# train the actoraction_loss = -critic(state, actor(state))action_loss.backward()# train the criticnext_action = target_actor(state)target_value= target_critic(next_state, next_action )expected_value = reward + (1 — done) * gamma * next_valuevalue = value_net(state, action)value_loss = MeanSquares(value, expected_value))value_loss.backward()# soft updatedef soft_update(*networks, soft_tau=1e-2): for target, learning in networks.parameters(): target= target.data * (1.0 — soft_tau) + learning .data * soft_tausoft_update(actor, target_actor)soft_update(critic, target critic)"
},
{
"code": null,
"e": 24279,
"s": 24220,
"text": "Here is the actual screenshot of the update function I use"
},
{
"code": null,
"e": 24317,
"s": 24279,
"text": "That is basically what DDPG is about."
},
{
"code": null,
"e": 25050,
"s": 24317,
"text": "In the next section, we will try to compare and, primarily, evaluate different reinforcement learning algorithms. But how do we tell if the results are good or not? The critic network assigns the values to our actions; however, are you sure whether the value is meaningful. Well, they are based on critic loss. If critic loss is small and the policy loss makes sense, we taught the actor. But those metrics are not enough. I also consider euclidean and cosine distances for actions. A matrix often represents this. You can see the distances described as individual grid pieces varying by color. The warmer it is, the bigger the distance. For instance here is how real actions (those I produced with statistics embeddings) look like."
},
{
"code": null,
"e": 25605,
"s": 25050,
"text": "You will see similar matrices for training and testing actions later on. Another method to evaluate the ‘artificiality’ of actions is to use the autoencoder reconstruction error. I train the autoencoder model to reconstruct the embedding actions. The reconstruction error is used as artificiality metric. This technique is widely used for anomaly detection because it is unsupervised. Also, I perform Kernel Density Estimation on the error distribution for pretty plotting and visual comparison. Wasserstein distance or KL Divergence can also be implied."
},
{
"code": null,
"e": 25750,
"s": 25605,
"text": "The goal is to make the generated test distribution close to the true (real) one. Generated train (or just generated) may be of different forms."
},
{
"code": null,
"e": 25861,
"s": 25750,
"text": "All I did at this point is copypasting Higgsfield’s RL adventure code with minor tweaks to work with torch 1.1"
},
{
"code": null,
"e": 26146,
"s": 25861,
"text": "It looks like we have something! Matrices look cool? Some correlation is showing up... The loss is descending... Wait, say what is on the scale bar? Why do I have next to no cosine distances? Why is the policy loss falling into the nether realm? Why don’t my pet AIs work as supposed?"
},
{
"code": null,
"e": 26194,
"s": 26146,
"text": "And that’s when it comes to the true joy of RL!"
},
{
"code": null,
"e": 26936,
"s": 26194,
"text": "Countless things can go wrong! Maybe I should play around wit the learning rate? Admittedly, that’s the first thing that comes in mind for a person familiar with DL. However, why my error is growing in the first place? I haven’t encountered these things in the DL... WTF is happening with the v-net optimization, PyTorch? It doesn’t seem to have much of an impact as the process starts, but then the gradients explode, and everything goes into oblivion... So, likely, the learning rate is excellent. Maybe that’s because of the Temporal Difference bootstrapping? But not only does the TDB use the target value network, which is soft updated via soft tau, the TD it also utilizes a parameter called gamma for weighting the future expectation."
},
{
"code": null,
"e": 27070,
"s": 26936,
"text": "P_gamma = 0.9P_min_value=-5P_max_value=5P_soft_tau=1e-2P_policy_lr = 1e-5P_value_lr = 1e-6P_actor_init_w = 3e-4P_critic_init_w = 3e-4"
},
{
"code": null,
"e": 27155,
"s": 27070,
"text": "What am I supposed to tweak? Maybe I set the wrong parameter for clipping the value:"
},
{
"code": null,
"e": 27222,
"s": 27155,
"text": "expected_value = torch.clamp(expected_value, min_value, max_value)"
},
{
"code": null,
"e": 27676,
"s": 27222,
"text": "One thing that came as a bamboozler to me is that the weight inits trick works slightly differently than one would expect. If we initialize the last layer’s weights of the net with smaller numbers, it will generate smaller vectors. Wrong! It works exactly the opposite. So it is the main reason for the cosine distance being so short in comparison to the distribution of the real action. However, it doesn’t seem to have much of an effect for Euclidean."
},
{
"code": null,
"e": 27978,
"s": 27676,
"text": "Also, have you noticed the min and max parameters for the value clipping are min and max rewards, respectively? That also needs to be changed, as I mentioned it back in the Markov property stuff. I set it to reward * n_td_steps. That works fine, and at the end, the loss rarely goes below 6–7 at most."
},
{
"code": null,
"e": 28201,
"s": 27978,
"text": "You may not realize it, but a smaller learning rate for critic leads to actor overfitting. If the policy loss falls weirdly fast, change the LR, because the actor is overfitting. Keep in mind: not the most intuitive thing!"
},
{
"code": null,
"e": 28490,
"s": 28201,
"text": "Always debug and keep track of the following parameters: value, target_value (mean, std), expected_value (mean, std), generated_action (cosine distances, Gramian, variance, std, means, samples KL distance to the original distribution). Always plot those metrics at the end of the testing."
},
{
"code": null,
"e": 28580,
"s": 28490,
"text": "P_critic_init_w=3e-5P_actor_init_w=3e-1P_min_value=-10 # or -100P_max_value=10 # or 100"
},
{
"code": null,
"e": 28718,
"s": 28580,
"text": "We solved the RL part of a not working network, now the reasons for the loss to grow are purely DL. Here are some bits of advice for you:"
},
{
"code": null,
"e": 29560,
"s": 28718,
"text": "Play around with the optimizers. There are so many of them for a reason. Start with Adam, try Hinton’s RMS prop, pure SGD, SGD with warm restarts and CosineAnnealingLR. Although, if you don’t care, there is a neat new algorithm for you to try out! It’s called RAdam: GitHub link. I use it whenever possible because it reduces the number of parameters to optimize. It is later explained.Use grad_clip extremely carefully. Using it on the value network changes the sign of the value function. I don’t understand why that is the case. But policy seems to work just fine. I spend almost a week figuring it out. No, for real.Weight decay is crucial to avoid overfitting. Moreover, it is easy to use with Pytorch optimizers. Set it to a smaller value, and the exploding gradients are gone within seconds. Also, use it with grad clip for the actor."
},
{
"code": null,
"e": 29947,
"s": 29560,
"text": "Play around with the optimizers. There are so many of them for a reason. Start with Adam, try Hinton’s RMS prop, pure SGD, SGD with warm restarts and CosineAnnealingLR. Although, if you don’t care, there is a neat new algorithm for you to try out! It’s called RAdam: GitHub link. I use it whenever possible because it reduces the number of parameters to optimize. It is later explained."
},
{
"code": null,
"e": 30182,
"s": 29947,
"text": "Use grad_clip extremely carefully. Using it on the value network changes the sign of the value function. I don’t understand why that is the case. But policy seems to work just fine. I spend almost a week figuring it out. No, for real."
},
{
"code": null,
"e": 30404,
"s": 30182,
"text": "Weight decay is crucial to avoid overfitting. Moreover, it is easy to use with Pytorch optimizers. Set it to a smaller value, and the exploding gradients are gone within seconds. Also, use it with grad clip for the actor."
},
{
"code": null,
"e": 30471,
"s": 30404,
"text": "This is supposed to bring back to life the DDPG on your/mine data."
},
{
"code": null,
"e": 30676,
"s": 30471,
"text": "Value network learning rate — affects Euclidean distanced between the generated action. It also improves the cosine distance, but on a smaller scale. Only works for SGD/Adam and does not matter for Radam."
},
{
"code": null,
"e": 30864,
"s": 30676,
"text": "Actor Weight Initialization — changes the diversity of the cosine distances in the action space. If you see next to no variance in your action distances, start by changing this parameter."
},
{
"code": null,
"e": 31326,
"s": 30864,
"text": "Soft tau — is responsible for the target network update. It affects the delay of the ‘rollercoaster’ of the loss function applied to the target network. You can see that both losses resemble each other. If you run the code, you will see that value loss slowly translates into the policy loss. As I said, it influences the smoothness of such translation. It is another critical parameter to consider if something does not work for you, but don’t overestimate it."
},
{
"code": null,
"e": 31465,
"s": 31326,
"text": "Gamma — is the weight of expected_action in temporal difference. Imho is not so important. Smaller values may lead to gradient explosions."
},
{
"code": null,
"e": 31874,
"s": 31465,
"text": "Min/Max values — I set them to +- 10. You can experiment with another large number. Alternatively, you can use x*n_td_iterations where x is min/max possible reward. It makes the learning process more rigid but defies the value function property. Alternatively, if you don’t care at all about the rollercoaster losses, you can use numpy infinity. The parameter has a positive influence on the value test loss."
},
{
"code": null,
"e": 32082,
"s": 31874,
"text": "Always look at the scale of the loss function. The value should be somewhere between [0, 10], whereas policy within min/max values for TD clipping. If it goes up to 10e7, you are wasting your time debugging!"
},
{
"code": null,
"e": 32336,
"s": 32082,
"text": "I already paid attention to this, but I cannot stress it enough. Always use the state of the art optimizer. Check Arxiv daily, subscribe to the twitter bot and be on a lookout, because the Machine Learning community is now at its peak of productiveness."
},
{
"code": null,
"e": 32840,
"s": 32336,
"text": "Adam is often the default choice for optimization. Moreover, this should be changed. Adam is one of the worst options you have. Why? It’s very very learning rate sensitive. Thinking back about the learning rate schedulers: carefully memorizing which step to put the milestone at, using CosineAnnealingLR warm restarts SGD, CyclicLR. Everything of the techniques above is now in the past — no more fiddling with the learning rate. Just use RAdam! On the Variance of the Adaptive Learning Rate and Beyond!"
},
{
"code": null,
"e": 33106,
"s": 32840,
"text": "RAdam is an ideological extension of Adam, and it uses a smart trick called Learning Rate Warmups. Unfortunately, the authors of Radam were not welcome enough to make the Medium article free, so there will be no detailed explanation. You can read their Axriv paper."
},
{
"code": null,
"e": 33273,
"s": 33106,
"text": "Nevertheless, I claim that just by changing the optimizer, I was able to achieve TD3 like performance with DDPG algorithm. And with way less overfitting in both cases"
},
{
"code": null,
"e": 33487,
"s": 33273,
"text": "Here is how the Adam loss looks like. One does not have to be a Ph.D. to spot clear value overfitting. Also, do you notice the Policy Loss? It seems strangely small. The max reward is 5, and max TD clipping is 10."
},
{
"code": null,
"e": 33579,
"s": 33487,
"text": "Train actions seem to overfit, not much of Euclidean Distance is showing up, but alright..."
},
{
"code": null,
"e": 33688,
"s": 33579,
"text": "Loss seems to be reasonable at 7.5. Or does it? Alright, let’s look at the autoencoder reconstruction error."
},
{
"code": null,
"e": 33983,
"s": 33688,
"text": "You can spot that something is wrong just by looking at the ae rec error distributions and/or comparing various metrics between them. The dumbest choice would be only to calculate KL/WDistance. You can also look at more meaningful statistical metrics such as mean/std/kurtosis/skewness instead."
},
{
"code": null,
"e": 34165,
"s": 33983,
"text": "CosDist < 0.4, Euc < 3. No words needed. Also, an observation by me: Cosine matrix defines an angle distribution of the direction of vectors. You can use basic math to visualize it."
},
{
"code": null,
"e": 34454,
"s": 34165,
"text": "Woah, that’s some good memory! I wish I could memorize that much. Unfortunately, that is not leaning. You can jump straight inro TD3, and it will undoubtedly help with the overfitting, but let’s try to use the RAdam instead. Just change optim.Adam to RAdam when you define the optimizers."
},
{
"code": null,
"e": 34515,
"s": 34454,
"text": "So I ran the same code with RAdam, and that’s what happened."
},
{
"code": null,
"e": 34975,
"s": 34515,
"text": "First Off — no nasty Value Overfitting. Moreover, the value loss is less. The convergence is way more delayed in comparison to Adam. There you can see a clear drop trend at around 400. Here it takes twice as many iterations to notice the pattern. Also, value loss is much smoother. The train actions are way more apart in terms of the Euclidean distance. The cosine dist seems to be preserved across all the experiments. All right, let’s see the test actions:"
},
{
"code": null,
"e": 35146,
"s": 34975,
"text": "The results speak for themselves! Test distribution is approximated way better with RAdam, but the training one is more obscure. Nevertheless, we only care about testing."
},
{
"code": null,
"e": 35544,
"s": 35146,
"text": "However, RAdam comes with a drawback. It is hard to finetune models with it. If you leave the model running with RAdam, the training distribution will quickly converge to the true one. Also, the testing distro will be something like a small pine cone at the very right. Need to look out for the Policy loss approaching -5, or manually stop the learning. This is what happens if you do not stop it:"
},
{
"code": null,
"e": 35632,
"s": 35544,
"text": "The policy network overfits: values are quickly dropping. It is not the case with Adam."
},
{
"code": null,
"e": 36015,
"s": 35632,
"text": "My end solution was to combine the two optimizers. First, I learn with RAdam, by creating checkpoints before overfitting I ensure that I have an excellent warmed up model. Then I load these models and train them with Adam to achieve even better performance. Unfortunately, there is no room for automatization: you find the smallest policy loss and start from the nearest checkpoint."
},
{
"code": null,
"e": 36219,
"s": 36015,
"text": "It results in better representation of the training distro, but the testing one is way worse. But this method of fine-tuning will be more useful for the TD3 algorithm. Which we are switching onto... Now!"
},
{
"code": null,
"e": 36325,
"s": 36219,
"text": "P.S. all models are available for downloading on the github page(including raw Radam and Adam fine-tuned)"
},
{
"code": null,
"e": 36544,
"s": 36325,
"text": "TD3 stands for Twin Delayed DDPG. Three is the number of improvements the authors of the paper propose. As I already stated, it is an extension of Deep Deterministic Policy Gradients. The differences are the following:"
},
{
"code": null,
"e": 36848,
"s": 36544,
"text": "Double Q Learning with no clip. We have two value networks in this algorithm. Also, instead of clipping the expected value, we take the smallest of target values. This simple trick drastically reduces the chance of policy agent exploiting and fooling the critic, because now it has to fool both of them."
},
{
"code": null,
"e": 37152,
"s": 36848,
"text": "Double Q Learning with no clip. We have two value networks in this algorithm. Also, instead of clipping the expected value, we take the smallest of target values. This simple trick drastically reduces the chance of policy agent exploiting and fooling the critic, because now it has to fool both of them."
},
{
"code": null,
"e": 37598,
"s": 37152,
"text": "#ddpgtarget_q_value = target_value_net(next_state, next_action)expected_value = reward + (1.0 - done) * gamma * target_q_valueexpected_value = torch.clamp(expected_value, min_value, max_value)#td3target_q_value1 = target_value_net1(next_state, next_action)target_q_value2 = target_value_net2(next_state, next_action)target_q_value = torch.min(target_q_value1, target_q_value2)expected_value = reward + (1.0 - done) * gamma * target_q_value"
},
{
"code": null,
"e": 37919,
"s": 37598,
"text": "2. Delayed Policy Updates. We update policy less frequently in comparison to values. For each three value update, we update the actor just once. This allows for better value estimation and also prevents actor fooling. P.S. it is not a hard concept and is super easy to implement. I used delayed policy updates with DDPG."
},
{
"code": null,
"e": 38170,
"s": 37919,
"text": "3. Action smoothing. TD3 adds noise to the target action, to make it harder for the policy to exploit Q-function errors by smoothing out Q along with changes in action. In my case, the noise is drawn from ~Normal(0, 0.1) and clipped to fit [-.3, .3]."
},
{
"code": null,
"e": 38349,
"s": 38170,
"text": "next_action = target_policy_net(next_state)noise = torch.normal(torch.zeros(next_action.size()), noise_std)noise = torch.clamp(noise, -noise_clip, noise_clip)next_action += noise"
},
{
"code": null,
"e": 38572,
"s": 38349,
"text": "The algorithm has pretty much the same parameters as the same as the DDPG (excluding min/max clip, adding noise params). All the code/dataset/pretrained models are on GitHub. TD3 is located under notes/1. Vanilla RL/2.ddpg"
},
{
"code": null,
"e": 38879,
"s": 38572,
"text": "Phew! We’ve made it! What you see is my final result for the On-Policy methods. Now let’s discuss the losses and other stuff. First off: value loss is growing. This phenomenon is reasonable because if we look at the values, they are not overfitting. In ddpg, they were increasing and then decreasing again."
},
{
"code": null,
"e": 39247,
"s": 38879,
"text": "The distances cosine distances in real and generated actions differ. It is something around ~0.6 is generated whereas the real ones are ~1. It can be increased by setting the noise std to a higher value. However, I consider it cheating because we add more noise. Alternatively, you can use another loss function in couple with policy loss to add more cosine diversity"
},
{
"code": null,
"e": 39573,
"s": 39247,
"text": "In one of my older commits, I implemented cosine and euclidian distance loss penalties with the new Pytorch JIT compiler. P.S. it returns the pairwise distance matrix, like the ones shown above. You can do whatever you want with this thing (i.e., compare variance, std, mean, KL) to make it look like one of the real actions."
},
{
"code": null,
"e": 40093,
"s": 39573,
"text": "@torch.jit.scriptdef torch_cdist_euc(x1, x2): x1_norm = x1.pow(2).sum(dim=-1, keepdim=True) x2_norm = x2.pow(2).sum(dim=-1, keepdim=True) res = torch.addmm(x2_norm.transpose(-2, -1), x1, x2.transpose(-2, -1), alpha=-2).add_(x1_norm) res = res.clamp_min_(1e-30).sqrt_() return res@torch.jit.scriptdef torch_cdist_cos(x1, x2): x1_norm = x1 / x1.norm(dim=1, p=2).unsqueeze(1) x2_norm = x2 / x2.norm(dim=1, p=2).unsqueeze(1) res = 1 - torch.mm(x1_norm, x2_norm.transpose(0,1)) return res"
},
{
"code": null,
"e": 40252,
"s": 40093,
"text": "It’s time to test our algorithms. You can download all the pre-trained models and test them yourself. The file is under notes/results/1. Ranking/ (clickable)."
},
{
"code": null,
"e": 40602,
"s": 40252,
"text": "Below you will see examples of distance ranking. It supports scipy. spatial distances or your ones. In the notebook, I included the following: euclidean, cosine, correlation, Canberra, Minkowski, Chebyshev, Bray-Curtis, and city block (Manhatten). Cosine ranking allows for better language and genres diversity and looks very similar to correlation."
},
{
"code": null,
"e": 40684,
"s": 40602,
"text": "That is it! You can see all the ranking examples for both of the algorithms here."
},
{
"code": null,
"e": 41261,
"s": 40684,
"text": "So here we are. Congratulations if you have finally made it. It might seem like a simple project: just using the existing Higgsfield’s algorithm implementation for new data, but I had been working 6 hours a day for the last month to get it working, to figure out the parameters in DDPG, and to understand the depths of PyTorch although the article was the hardest part of it. I am already writing this conclusion, but I haven’t finished Restricted Boltzmann Machines in the comparison section yet. The repo is unpushed. I wonder how it had turned out... Did you understand it?"
},
{
"code": null,
"e": 41490,
"s": 41261,
"text": "TD3 implementation is promising. Moreover, the ranking works fine, although there is room for improvement. I am using O(n) algorithm. Highly recommend you check out the Milvus library if you want to use embeddings in production."
},
{
"code": null,
"e": 41694,
"s": 41490,
"text": "I am also yet to implement a web app. Already got a commit on my other repo with react and basic layout. Hopefully, it will be published soon. If not, you can do it yourself: all the models are released."
},
{
"code": null,
"e": 41767,
"s": 41694,
"text": "I honestly don’t have much else to say. I am passing 7131 words already."
},
{
"code": null,
"e": 41803,
"s": 41767,
"text": "Anyway here are some ideas from me:"
},
{
"code": null,
"e": 41945,
"s": 41803,
"text": "Because it is recommendation project, you could use top k ranking for action. Those ranking results can be used to help the learning process:"
},
{
"code": null,
"e": 42087,
"s": 41945,
"text": "Because it is recommendation project, you could use top k ranking for action. Those ranking results can be used to help the learning process:"
},
{
"code": null,
"e": 42218,
"s": 42087,
"text": "You could add another loss that would calculate distances between real ranked and generated actions. (Another loss for the critic)"
},
{
"code": null,
"e": 42331,
"s": 42218,
"text": "How different is the Value function for the ranked actions? Can it be further adjusted concerning the distances?"
},
{
"code": null,
"e": 42431,
"s": 42331,
"text": "2. Add yet another cosine/euclidean loss to the generated actions. The scripts are published above."
},
{
"code": null,
"e": 42582,
"s": 42431,
"text": "3. Implement a ranking network. It is an extension of the policy. It takes action as input and learns to generate real actions based on top k ranking."
},
{
"code": null,
"e": 42637,
"s": 42582,
"text": "If you happen to implement these, feel free to commit."
},
{
"code": null,
"e": 43210,
"s": 42637,
"text": "Medium: Ping Guo, 임한동[ 학부재학 / 기계공학부 ], Jacky Noah, Shady Hassab, Alexander Makeev, Shivam Akhauri, Diksha Garg, Siddharth Prabhu, Zohar Komarovsky, Hary Prasad, Panagiotis Kapros, Vishal Shrinivas, Yvette Li, Lxs Lxs, Nils Schluter, Ayush Kumar, Dean Soe, Cody Bushnell, Marcus Au, باربری تهران اتوبار تهران, Navi Xie, Sang Huynh, Simon Yu, Yuzhou Zhang, Hoglan Huang, Lambjed Ben, Axel Schwanke, Anirban Saha, Baris Can Tauris, Mingju He, Jean-Philippe Corbeil, Shoaib Hafiz — It was your follow that made me feel somewhat important for the community."
},
{
"code": null,
"e": 43651,
"s": 43210,
"text": "GitHub: navy-xie, KnightofK9, tomatatto, lystahi, jungi21cc, nutorbit, davidjiangt, kiminh, hb1500, YerinMin, Saleh-Hassan, ImranRolo, limtete, erikson92, miladfa7, sudongtan, Belobobr, noaRricky, q710245300, andrebola, chenmingxia, ashdtu, dindanovitasari, kk-hainq, bazitur, youyiandyou, Vi-Sri, sanjmen, YvetteLi — You believed in my project back before it was implemented. Those starts begiventh by thee motivated me to keep on working."
},
{
"code": null,
"e": 43820,
"s": 43651,
"text": "DeepLearningSchool (www.dlschool.org) I wouldn’t be writing this article if it wasn’t for your excellent lessons and mentoring. Hope I make it to MIPT in the next year."
},
{
"code": null,
"e": 44309,
"s": 43820,
"text": "Feel free to tell about yourself. I started deep learning when I went to high school. Although, back then, I created countless GitHub projects of other thematics, that were by no means less ambitious. The only problem was that no one knew about it — not a single soul except for a couple of friends. If you are working hard on something, be sure to tell you about it. It’s other’s appreciation that keeps you moving forward. P.S. don’t write yet another Keras for preschoolers tutorial ;)"
},
{
"code": null,
"e": 44389,
"s": 44309,
"text": "Recently I have published a new article covering reinforce recommender systems:"
},
{
"code": null,
"e": 44412,
"s": 44389,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 44678,
"s": 44412,
"text": "Next article will address some problems with the fact that we have no exploration. It surely will take some time to make, but as I see it BCQ easily integrates with the DDPG. If you want to know more about RL applications with a static dataset here are these links:"
},
{
"code": null,
"e": 44726,
"s": 44678,
"text": "Arxiv article: https://arxiv.org/abs/1812.02900"
},
{
"code": null,
"e": 44770,
"s": 44726,
"text": "Pytorch Code: https://github.com/sfujim/BCQ"
},
{
"code": null,
"e": 44816,
"s": 44770,
"text": "Have some questions? The comments are open..."
},
{
"code": null,
"e": 44865,
"s": 44816,
"text": "GitHub repo: https://github.com/awarebayes/RecNN"
}
] |
How do I display an alert dialog on Android?
|
Before getting into alert dialog, we should know about what is alert dialog, Alert dialog is just like a pop-up where user can choose action by clicking "ok" or "cancel" button.
setView(View view) − It used to set custom view to alert dialog
setView(View view) − It used to set custom view to alert dialog
setTitle(CharSequence title) − It is used to set title to alert dialog
setTitle(CharSequence title) − It is used to set title to alert dialog
setMessage(CharSequence message) − It is simple call as content in alert box
setMessage(CharSequence message) − It is simple call as content in alert box
setIcon(int resId) − it is used to set icon for alert box
setIcon(int resId) − it is used to set icon for alert box
setButton(int whichButton, CharSequence text, Message msg) − It is used to set button for alert dialog as shown below example.
setButton(int whichButton, CharSequence text, Message msg) − It is used to set button for alert dialog as shown below example.
getListView() − it is used to get a list view which is used inside alert dialog.
getListView() − it is used to get a list view which is used inside alert dialog.
This example demonstrate about how to implement android alert dialog.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Click"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
alertDialog();
break;
}
}
private void alertDialog() {
AlertDialog.Builder dialog=new AlertDialog.Builder(this);
dialog.setMessage("Please Select any option");
dialog.setTitle("Dialog Box");
dialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
}
});
dialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"cancel is clicked",Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog=dialog.create();
alertDialog.show();
}
}
In the above code we have created a button when user click on button it will show an alert dialog box, user can select ok or cancel based on requirement.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Now click on above button it will show alert dialog as shown below
Now select yes/cancel button it will give an output as shown below
Click here to download the project code
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "Before getting into alert dialog, we should know about what is alert dialog, Alert dialog is just like a pop-up where user can choose action by clicking \"ok\" or \"cancel\" button."
},
{
"code": null,
"e": 1304,
"s": 1240,
"text": "setView(View view) − It used to set custom view to alert dialog"
},
{
"code": null,
"e": 1368,
"s": 1304,
"text": "setView(View view) − It used to set custom view to alert dialog"
},
{
"code": null,
"e": 1439,
"s": 1368,
"text": "setTitle(CharSequence title) − It is used to set title to alert dialog"
},
{
"code": null,
"e": 1510,
"s": 1439,
"text": "setTitle(CharSequence title) − It is used to set title to alert dialog"
},
{
"code": null,
"e": 1587,
"s": 1510,
"text": "setMessage(CharSequence message) − It is simple call as content in alert box"
},
{
"code": null,
"e": 1664,
"s": 1587,
"text": "setMessage(CharSequence message) − It is simple call as content in alert box"
},
{
"code": null,
"e": 1722,
"s": 1664,
"text": "setIcon(int resId) − it is used to set icon for alert box"
},
{
"code": null,
"e": 1780,
"s": 1722,
"text": "setIcon(int resId) − it is used to set icon for alert box"
},
{
"code": null,
"e": 1907,
"s": 1780,
"text": "setButton(int whichButton, CharSequence text, Message msg) − It is used to set button for alert dialog as shown below example."
},
{
"code": null,
"e": 2034,
"s": 1907,
"text": "setButton(int whichButton, CharSequence text, Message msg) − It is used to set button for alert dialog as shown below example."
},
{
"code": null,
"e": 2115,
"s": 2034,
"text": "getListView() − it is used to get a list view which is used inside alert dialog."
},
{
"code": null,
"e": 2196,
"s": 2115,
"text": "getListView() − it is used to get a list view which is used inside alert dialog."
},
{
"code": null,
"e": 2266,
"s": 2196,
"text": "This example demonstrate about how to implement android alert dialog."
},
{
"code": null,
"e": 2395,
"s": 2266,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 2460,
"s": 2395,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3261,
"s": 2460,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\nxmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 3318,
"s": 3261,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4942,
"s": 3318,
"text": "package com.example.andy.myapplication;\nimport android.content.DialogInterface;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Switch;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button=findViewById(R.id.button);\n button.setOnClickListener(this);\n }\n @Override\n public void onClick(View v) {\n switch (v.getId()){\n case R.id.button:\n alertDialog();\n break;\n }\n }\n private void alertDialog() {\n AlertDialog.Builder dialog=new AlertDialog.Builder(this);\n dialog.setMessage(\"Please Select any option\");\n dialog.setTitle(\"Dialog Box\");\n dialog.setPositiveButton(\"YES\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog,\n int which) {\n Toast.makeText(getApplicationContext(),\"Yes is clicked\",Toast.LENGTH_LONG).show();\n }\n });\n dialog.setNegativeButton(\"cancel\",new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n Toast.makeText(getApplicationContext(),\"cancel is clicked\",Toast.LENGTH_LONG).show();\n }\n });\n AlertDialog alertDialog=dialog.create();\n alertDialog.show();\n }\n}"
},
{
"code": null,
"e": 5096,
"s": 4942,
"text": "In the above code we have created a button when user click on button it will show an alert dialog box, user can select ok or cancel based on requirement."
},
{
"code": null,
"e": 5442,
"s": 5096,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 5509,
"s": 5442,
"text": "Now click on above button it will show alert dialog as shown below"
},
{
"code": null,
"e": 5576,
"s": 5509,
"text": "Now select yes/cancel button it will give an output as shown below"
},
{
"code": null,
"e": 5616,
"s": 5576,
"text": "Click here to download the project code"
}
] |
AI Chatbot with NLP: Speech Recognition + Transformers | by Mauro Di Pietro | Towards Data Science
|
In this article, I will show how to leverage pre-trained tools to build a Chatbot that uses Artificial Intelligence and Speech Recognition, so a talking AI.
NLP (Natural Language Processing) is the field of artificial intelligence that studies the interactions between computers and human languages, in particular how to program computers to process and analyze large amounts of natural language data. NLP research has always been focused on making chatbots smarter and smarter.
Chatbots are software applications used to conduct automatic chat conversations via text or text-to-speech, imitating the interaction with a human agent. The very first one was ELIZA (1966) that used pattern matching and substitution methodology to simulate a textual conversation (it couldn’t either listen or speak). Currently the most advanced on the market is Amazon ALEXA, an intelligent personal assistant that understands the user’s voice and talks back.
In this tutorial, I will show how to build a conversational Chatbot using Speech Recognition APIs and pre-trained Transformer models. I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example.
In particular, I will go through:
Setup the environment
Speech Recognition with Google APIs
Language model with Transformers
First of all, we need to install the following libraries:
# for speech to textpip install SpeechRecognition #(3.8.1)# for text to speechpip install gTTS #(2.2.3)# for language modelpip install transformers #(4.11.3)pip install tensorflow #(2.6.0, or pytorch)
We are going to need also some other common packages like:
import numpy as np
Let’s start by creating an empty class that we will enrich step by step. In order to test the Chatbot we need to initialize it and run the whole script, I’ll name my bot “Maya”:
# Build the AIclass ChatBot(): def __init__(self, name): print("--- starting up", name, "---") self.name = name# Run the AIif __name__ == "__main__": ai = ChatBot(name="maya")
Speech recognition is an interdisciplinary subfield of NLP that develops methodologies and technologies to enable the recognition and translation of spoken language into text by computers. The first speech recognition systems (1950) could understand numbers but not words, IBM Shoebox (1960) was the first one to understand and respond to few English words.
Today, the most used systems are Google’s APIs and an easy way to use them is through the SpeechRecognition library:
import speech_recognition as srdef speech_to_text(self): recognizer = sr.Recognizer() with sr.Microphone() as mic: recognizer.adjust_for_ambient_noise(mic, duration=1) print("listening...") audio = recognizer.listen(mic) try: self.text = recognizer.recognize_google(audio) print("me --> ", self.text) except: print("me --> ERROR")
That is the first NLP function of our Chatbot class performing the speech-to-text task. Basically, it gives the ability to listen and understand your voice by transforming the audio signal into text. You can test it by running and trying to say something:
# Run the AIif __name__ == "__main__": ai = ChatBot(name="maya") while True: ai.speech_to_text()
Now we need to give the AI the ability to respond back. To put it in another way, we want the Chatbot to understand the input, produce an output, and speak it up. Let’s add a new function to the class:
def wake_up(self, text): return True if self.name in text.lower() else False
The wake_up method makes sure the AI responds when you say its name. For example, I shall activate my Chatbot by saying “Hey Maya”.
Once the Chatbot hears its name it will say something back, therefore it needs to perform a text-to-speech task. I’m going to use the Google Text-to-Speech library (gtts) to save an mp3 file on the file system which can be easily played with the library OS.
from gtts import gTTSimport os@staticmethoddef text_to_speech(text): print("ai --> ", text) speaker = gTTS(text=text, lang="en", slow=False) speaker.save("res.mp3") os.system("afplay res.mp3") #macbook->afplay | windows->start os.remove("res.mp3")
You can test those two new functions like this:
# Run the AIif __name__ == "__main__": ai = ChatBot(name="maya") while True: ai.speech_to_text() ## wake up if ai.wake_up(ai.text) is True: res = "Hello I am Maya the AI, what can I do for you?" ai.text_to_speech(res)
We can also program the bot to react to some specific commands, just like any other virtual assistant (Siri, Alexa, Cortana, ...). For example, I want my AI to tell me the time when I ask for it and to respond nicely when I thank her (“her”, yes I already love her). So I’m going to add this function to the Chatbot class:
import datetime@staticmethoddef action_time(): return datetime.datetime.now().time().strftime('%H:%M')
and run the script:
# Run the AIif __name__ == "__main__":ai = ChatBot(name="maya")while True: ai.speech_to_text() ## wake up if ai.wake_up(ai.text) is True: res = "Hello I am Maya the AI, what can I do for you?" ## action time elif "time" in ai.text: res = ai.action_time() ## respond politely elif any(i in ai.text for i in ["thank","thanks"]): res = np.random.choice( ["you're welcome!","anytime!", "no problem!","cool!", "I'm here if you need me!","peace out!"]) ai.text_to_speech(res)
So far we’ve used Speech Recognition techniques to talk to our Chatbot, but the bot is still pretty dummy as it can’t respond to anything that is not predetermined. It’s time to put real Artificial Intelligence inside our Chatbot, i.e. a machine learning model trained for NLP.
I will use a Transformer Language Model, a new modeling technique presented by Google (2017) that replaces traditional sequence-to-sequence models (like LSTM) with Attention mechanisms. These language models can perform any NLP task because they dynamically understand contexts. The most famous models are Google’s BERT and OpenAI’s GPT, with billions of parameters.
The main package for these models is transformers by HuggingFace. It’s a popular tool that provides pre-trained models useful for a variety of NLP tasks. Specifically, the one I’m going to use is DialogGPT, a GPT model trained by Microsoft on millions of conversations extracted from Reddit.
import transformersnlp = transformers.pipeline("conversational", model="microsoft/DialoGPT-medium")
Let’s try it out:
input_text = "hello!"nlp(transformers.Conversation(input_text))
Please note that the current version of the library gives a warning when you don’t specify the pad_token_id (as you can see from the image above). In order to avoid this, you can just add it as a parameter:
nlp(transformers.Conversation(input_text), pad_token_id=50256)
Moreover, the pipeline outputs the whole conversation (as you can see from the image above), so I’m gonna turn the whole output into a string and extract the chatbot’s response only.
chat = nlp(transformers.Conversation(ai.text), pad_token_id=50256)res = str(chat)res = res[res.find("bot >> ")+6:].strip()
Finally, we’re ready to run the Chatbot and have a fun conversation with our AI. Here’s the full code:
Great! The bot can both perform some specific tasks like a virtual assistant (i.e. saying the time when asked) and have casual conversations. And if you think that Artificial Intelligence is here to stay, she agrees:
This article has been a tutorial to demonstrate how to build a conversational Chatbot that listens and replies like a human. I used Speech Recognition tools to perform speech-to-text and text-to-speech tasks, and I leveraged pre-trained Transformers language models to give the bot some Artificial Intelligence. Now you can build your own Chatbot, maybe including more virtual assistant tasks like searching things on Wikipedia or playing videos on Youtube.
I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects.
👉 Let’s Connect 👈
This article is part of the series NLP with Python, see also:
|
[
{
"code": null,
"e": 329,
"s": 172,
"text": "In this article, I will show how to leverage pre-trained tools to build a Chatbot that uses Artificial Intelligence and Speech Recognition, so a talking AI."
},
{
"code": null,
"e": 651,
"s": 329,
"text": "NLP (Natural Language Processing) is the field of artificial intelligence that studies the interactions between computers and human languages, in particular how to program computers to process and analyze large amounts of natural language data. NLP research has always been focused on making chatbots smarter and smarter."
},
{
"code": null,
"e": 1113,
"s": 651,
"text": "Chatbots are software applications used to conduct automatic chat conversations via text or text-to-speech, imitating the interaction with a human agent. The very first one was ELIZA (1966) that used pattern matching and substitution methodology to simulate a textual conversation (it couldn’t either listen or speak). Currently the most advanced on the market is Amazon ALEXA, an intelligent personal assistant that understands the user’s voice and talks back."
},
{
"code": null,
"e": 1450,
"s": 1113,
"text": "In this tutorial, I will show how to build a conversational Chatbot using Speech Recognition APIs and pre-trained Transformer models. I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example."
},
{
"code": null,
"e": 1484,
"s": 1450,
"text": "In particular, I will go through:"
},
{
"code": null,
"e": 1506,
"s": 1484,
"text": "Setup the environment"
},
{
"code": null,
"e": 1542,
"s": 1506,
"text": "Speech Recognition with Google APIs"
},
{
"code": null,
"e": 1575,
"s": 1542,
"text": "Language model with Transformers"
},
{
"code": null,
"e": 1633,
"s": 1575,
"text": "First of all, we need to install the following libraries:"
},
{
"code": null,
"e": 1837,
"s": 1633,
"text": "# for speech to textpip install SpeechRecognition #(3.8.1)# for text to speechpip install gTTS #(2.2.3)# for language modelpip install transformers #(4.11.3)pip install tensorflow #(2.6.0, or pytorch)"
},
{
"code": null,
"e": 1896,
"s": 1837,
"text": "We are going to need also some other common packages like:"
},
{
"code": null,
"e": 1915,
"s": 1896,
"text": "import numpy as np"
},
{
"code": null,
"e": 2093,
"s": 1915,
"text": "Let’s start by creating an empty class that we will enrich step by step. In order to test the Chatbot we need to initialize it and run the whole script, I’ll name my bot “Maya”:"
},
{
"code": null,
"e": 2289,
"s": 2093,
"text": "# Build the AIclass ChatBot(): def __init__(self, name): print(\"--- starting up\", name, \"---\") self.name = name# Run the AIif __name__ == \"__main__\": ai = ChatBot(name=\"maya\")"
},
{
"code": null,
"e": 2647,
"s": 2289,
"text": "Speech recognition is an interdisciplinary subfield of NLP that develops methodologies and technologies to enable the recognition and translation of spoken language into text by computers. The first speech recognition systems (1950) could understand numbers but not words, IBM Shoebox (1960) was the first one to understand and respond to few English words."
},
{
"code": null,
"e": 2764,
"s": 2647,
"text": "Today, the most used systems are Google’s APIs and an easy way to use them is through the SpeechRecognition library:"
},
{
"code": null,
"e": 3168,
"s": 2764,
"text": "import speech_recognition as srdef speech_to_text(self): recognizer = sr.Recognizer() with sr.Microphone() as mic: recognizer.adjust_for_ambient_noise(mic, duration=1) print(\"listening...\") audio = recognizer.listen(mic) try: self.text = recognizer.recognize_google(audio) print(\"me --> \", self.text) except: print(\"me --> ERROR\")"
},
{
"code": null,
"e": 3424,
"s": 3168,
"text": "That is the first NLP function of our Chatbot class performing the speech-to-text task. Basically, it gives the ability to listen and understand your voice by transforming the audio signal into text. You can test it by running and trying to say something:"
},
{
"code": null,
"e": 3537,
"s": 3424,
"text": "# Run the AIif __name__ == \"__main__\": ai = ChatBot(name=\"maya\") while True: ai.speech_to_text()"
},
{
"code": null,
"e": 3739,
"s": 3537,
"text": "Now we need to give the AI the ability to respond back. To put it in another way, we want the Chatbot to understand the input, produce an output, and speak it up. Let’s add a new function to the class:"
},
{
"code": null,
"e": 3819,
"s": 3739,
"text": "def wake_up(self, text): return True if self.name in text.lower() else False"
},
{
"code": null,
"e": 3951,
"s": 3819,
"text": "The wake_up method makes sure the AI responds when you say its name. For example, I shall activate my Chatbot by saying “Hey Maya”."
},
{
"code": null,
"e": 4209,
"s": 3951,
"text": "Once the Chatbot hears its name it will say something back, therefore it needs to perform a text-to-speech task. I’m going to use the Google Text-to-Speech library (gtts) to save an mp3 file on the file system which can be easily played with the library OS."
},
{
"code": null,
"e": 4473,
"s": 4209,
"text": "from gtts import gTTSimport os@staticmethoddef text_to_speech(text): print(\"ai --> \", text) speaker = gTTS(text=text, lang=\"en\", slow=False) speaker.save(\"res.mp3\") os.system(\"afplay res.mp3\") #macbook->afplay | windows->start os.remove(\"res.mp3\")"
},
{
"code": null,
"e": 4521,
"s": 4473,
"text": "You can test those two new functions like this:"
},
{
"code": null,
"e": 4809,
"s": 4521,
"text": "# Run the AIif __name__ == \"__main__\": ai = ChatBot(name=\"maya\") while True: ai.speech_to_text() ## wake up if ai.wake_up(ai.text) is True: res = \"Hello I am Maya the AI, what can I do for you?\" ai.text_to_speech(res)"
},
{
"code": null,
"e": 5132,
"s": 4809,
"text": "We can also program the bot to react to some specific commands, just like any other virtual assistant (Siri, Alexa, Cortana, ...). For example, I want my AI to tell me the time when I ask for it and to respond nicely when I thank her (“her”, yes I already love her). So I’m going to add this function to the Chatbot class:"
},
{
"code": null,
"e": 5238,
"s": 5132,
"text": "import datetime@staticmethoddef action_time(): return datetime.datetime.now().time().strftime('%H:%M')"
},
{
"code": null,
"e": 5258,
"s": 5238,
"text": "and run the script:"
},
{
"code": null,
"e": 5900,
"s": 5258,
"text": "# Run the AIif __name__ == \"__main__\":ai = ChatBot(name=\"maya\")while True: ai.speech_to_text() ## wake up if ai.wake_up(ai.text) is True: res = \"Hello I am Maya the AI, what can I do for you?\" ## action time elif \"time\" in ai.text: res = ai.action_time() ## respond politely elif any(i in ai.text for i in [\"thank\",\"thanks\"]): res = np.random.choice( [\"you're welcome!\",\"anytime!\", \"no problem!\",\"cool!\", \"I'm here if you need me!\",\"peace out!\"]) ai.text_to_speech(res)"
},
{
"code": null,
"e": 6178,
"s": 5900,
"text": "So far we’ve used Speech Recognition techniques to talk to our Chatbot, but the bot is still pretty dummy as it can’t respond to anything that is not predetermined. It’s time to put real Artificial Intelligence inside our Chatbot, i.e. a machine learning model trained for NLP."
},
{
"code": null,
"e": 6545,
"s": 6178,
"text": "I will use a Transformer Language Model, a new modeling technique presented by Google (2017) that replaces traditional sequence-to-sequence models (like LSTM) with Attention mechanisms. These language models can perform any NLP task because they dynamically understand contexts. The most famous models are Google’s BERT and OpenAI’s GPT, with billions of parameters."
},
{
"code": null,
"e": 6837,
"s": 6545,
"text": "The main package for these models is transformers by HuggingFace. It’s a popular tool that provides pre-trained models useful for a variety of NLP tasks. Specifically, the one I’m going to use is DialogGPT, a GPT model trained by Microsoft on millions of conversations extracted from Reddit."
},
{
"code": null,
"e": 6965,
"s": 6837,
"text": "import transformersnlp = transformers.pipeline(\"conversational\", model=\"microsoft/DialoGPT-medium\")"
},
{
"code": null,
"e": 6983,
"s": 6965,
"text": "Let’s try it out:"
},
{
"code": null,
"e": 7047,
"s": 6983,
"text": "input_text = \"hello!\"nlp(transformers.Conversation(input_text))"
},
{
"code": null,
"e": 7254,
"s": 7047,
"text": "Please note that the current version of the library gives a warning when you don’t specify the pad_token_id (as you can see from the image above). In order to avoid this, you can just add it as a parameter:"
},
{
"code": null,
"e": 7317,
"s": 7254,
"text": "nlp(transformers.Conversation(input_text), pad_token_id=50256)"
},
{
"code": null,
"e": 7500,
"s": 7317,
"text": "Moreover, the pipeline outputs the whole conversation (as you can see from the image above), so I’m gonna turn the whole output into a string and extract the chatbot’s response only."
},
{
"code": null,
"e": 7623,
"s": 7500,
"text": "chat = nlp(transformers.Conversation(ai.text), pad_token_id=50256)res = str(chat)res = res[res.find(\"bot >> \")+6:].strip()"
},
{
"code": null,
"e": 7726,
"s": 7623,
"text": "Finally, we’re ready to run the Chatbot and have a fun conversation with our AI. Here’s the full code:"
},
{
"code": null,
"e": 7943,
"s": 7726,
"text": "Great! The bot can both perform some specific tasks like a virtual assistant (i.e. saying the time when asked) and have casual conversations. And if you think that Artificial Intelligence is here to stay, she agrees:"
},
{
"code": null,
"e": 8401,
"s": 7943,
"text": "This article has been a tutorial to demonstrate how to build a conversational Chatbot that listens and replies like a human. I used Speech Recognition tools to perform speech-to-text and text-to-speech tasks, and I leveraged pre-trained Transformers language models to give the bot some Artificial Intelligence. Now you can build your own Chatbot, maybe including more virtual assistant tasks like searching things on Wikipedia or playing videos on Youtube."
},
{
"code": null,
"e": 8519,
"s": 8401,
"text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects."
},
{
"code": null,
"e": 8537,
"s": 8519,
"text": "👉 Let’s Connect 👈"
}
] |
Android | App to Add Two Numbers - GeeksforGeeks
|
22 Sep, 2021
Below are the steps for Creating a Simple Android Application to Add Two Numbers
STEP-1: First of all go to the xml file
STEP-2: Now go to the text and write the code for adding 3 textview,2 textedit and Button and Assign ID to each component. Assign margin top, left, right for the location.
STEP-3: Now, open up the activity java file.
STEP-4: Declare few variables and the values entered in the Text Views can be read by using an id which we have set in the XML code above.
STEP-5: Add the click listener to the Add button.
STEP-6: When the Add button has been clicked, add the values and store it into the sum variable.
STEP-7: To show the output in the result text view, set the sum in the textview.
Complete code of layout xml file and java file is given below.
activity_main.xml
MainActivity.java
<!--The activity_main.xml is a layout file an XML-based layout is a file that defines the different widgets to be used in the UI and the relations between those widgets and their containers. --> <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:layout_editor_absoluteY="81dp"> <!-- Text view for result view--> <TextView android:id="@+id/textView_answer" android:layout_width="100dp" android:layout_height="25dp" android:layout_marginLeft="130dp" android:layout_marginTop="300dp" android:text="0" android:textSize="20dp" android:textStyle="bold" /> <!--take the input first number--> <EditText android:id="@+id/editText_first_no" android:layout_width="150dp" android:layout_height="40dp" android:layout_marginLeft="200dp" android:layout_marginTop="40dp" android:inputType="number" /> <!-- for message input first number--> <TextView android:id="@+id/textView_first_no" android:layout_width="150dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_marginTop="50dp" android:text="First number" android:textSize="20dp" /> <!--view message --> <TextView android:id="@+id/textView_second_no" android:layout_width="150dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_marginTop="100dp" android:text="Second number" android:textSize="20dp" /> <!-- take input for second number --> <EditText android:id="@+id/editText_second_no" android:layout_width="150dp" android:layout_height="40dp" android:layout_marginLeft="200dp" android:layout_marginTop="90dp" android:inputType="number" tools:ignore="MissingConstraints" /> <!-- button for run add logic and view result --> <Button android:id="@+id/add_button" android:layout_width="100dp" android:layout_height="50dp" android:layout_marginLeft="110dp" android:layout_marginTop="200dp" android:text="ADD" /> </RelativeLayout>
// Each new activity has its own layout and Java files, // here we build the logic for adding two number package org.geeksforgeeks.addtwonumbers; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // define the global variable // variable number1, number2 for input input number // Add_button, result textView EditText number1; EditText number2; Button Add_button; TextView result; int ans=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component which id is assign in xml file number1=(EditText) findViewById(R.id.editText_first_no); number2=(EditText) findViewById(R.id.editText_second_no); Add_button=(Button) findViewById(R.id.add_button); result = (TextView) findViewById(R.id.textView_answer); // Add_button add clicklistener Add_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // num1 or num2 double type // get data which is in edittext, convert it to string // using parse Double convert it to Double type double num1 = Double.parseDouble(number1.getText().toString()); double num2 = Double.parseDouble(number2.getText().toString()); // add both number and store it to sum double sum = num1 + num2; // set it ot result textview result.setText(Double.toString(sum)); } }); }}
After Complete layout xml file it will be shown as given below
Output:
Note: Similarly, Android App to subtract, multiply and divide numbers can be made by making minor changes in the Java and XML code.
vartika02
sweetyty
android
Articles
GBlog
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
Mutex vs Semaphore
Understanding "extern" keyword in C
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Top 10 Front End Developer Skills That You Need in 2022
Socket Programming in C/C++
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies
|
[
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 24349,
"s": 24268,
"text": "Below are the steps for Creating a Simple Android Application to Add Two Numbers"
},
{
"code": null,
"e": 24389,
"s": 24349,
"text": "STEP-1: First of all go to the xml file"
},
{
"code": null,
"e": 24561,
"s": 24389,
"text": "STEP-2: Now go to the text and write the code for adding 3 textview,2 textedit and Button and Assign ID to each component. Assign margin top, left, right for the location."
},
{
"code": null,
"e": 24606,
"s": 24561,
"text": "STEP-3: Now, open up the activity java file."
},
{
"code": null,
"e": 24745,
"s": 24606,
"text": "STEP-4: Declare few variables and the values entered in the Text Views can be read by using an id which we have set in the XML code above."
},
{
"code": null,
"e": 24795,
"s": 24745,
"text": "STEP-5: Add the click listener to the Add button."
},
{
"code": null,
"e": 24892,
"s": 24795,
"text": "STEP-6: When the Add button has been clicked, add the values and store it into the sum variable."
},
{
"code": null,
"e": 24973,
"s": 24892,
"text": "STEP-7: To show the output in the result text view, set the sum in the textview."
},
{
"code": null,
"e": 25036,
"s": 24973,
"text": "Complete code of layout xml file and java file is given below."
},
{
"code": null,
"e": 25054,
"s": 25036,
"text": "activity_main.xml"
},
{
"code": null,
"e": 25072,
"s": 25054,
"text": "MainActivity.java"
},
{
"code": "<!--The activity_main.xml is a layout file an XML-based layout is a file that defines the different widgets to be used in the UI and the relations between those widgets and their containers. --> <?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:layout_editor_absoluteY=\"81dp\"> <!-- Text view for result view--> <TextView android:id=\"@+id/textView_answer\" android:layout_width=\"100dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"130dp\" android:layout_marginTop=\"300dp\" android:text=\"0\" android:textSize=\"20dp\" android:textStyle=\"bold\" /> <!--take the input first number--> <EditText android:id=\"@+id/editText_first_no\" android:layout_width=\"150dp\" android:layout_height=\"40dp\" android:layout_marginLeft=\"200dp\" android:layout_marginTop=\"40dp\" android:inputType=\"number\" /> <!-- for message input first number--> <TextView android:id=\"@+id/textView_first_no\" android:layout_width=\"150dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"50dp\" android:text=\"First number\" android:textSize=\"20dp\" /> <!--view message --> <TextView android:id=\"@+id/textView_second_no\" android:layout_width=\"150dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"100dp\" android:text=\"Second number\" android:textSize=\"20dp\" /> <!-- take input for second number --> <EditText android:id=\"@+id/editText_second_no\" android:layout_width=\"150dp\" android:layout_height=\"40dp\" android:layout_marginLeft=\"200dp\" android:layout_marginTop=\"90dp\" android:inputType=\"number\" tools:ignore=\"MissingConstraints\" /> <!-- button for run add logic and view result --> <Button android:id=\"@+id/add_button\" android:layout_width=\"100dp\" android:layout_height=\"50dp\" android:layout_marginLeft=\"110dp\" android:layout_marginTop=\"200dp\" android:text=\"ADD\" /> </RelativeLayout>",
"e": 27522,
"s": 25072,
"text": null
},
{
"code": "// Each new activity has its own layout and Java files, // here we build the logic for adding two number package org.geeksforgeeks.addtwonumbers; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // define the global variable // variable number1, number2 for input input number // Add_button, result textView EditText number1; EditText number2; Button Add_button; TextView result; int ans=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component which id is assign in xml file number1=(EditText) findViewById(R.id.editText_first_no); number2=(EditText) findViewById(R.id.editText_second_no); Add_button=(Button) findViewById(R.id.add_button); result = (TextView) findViewById(R.id.textView_answer); // Add_button add clicklistener Add_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // num1 or num2 double type // get data which is in edittext, convert it to string // using parse Double convert it to Double type double num1 = Double.parseDouble(number1.getText().toString()); double num2 = Double.parseDouble(number2.getText().toString()); // add both number and store it to sum double sum = num1 + num2; // set it ot result textview result.setText(Double.toString(sum)); } }); }}",
"e": 29336,
"s": 27522,
"text": null
},
{
"code": null,
"e": 29399,
"s": 29336,
"text": "After Complete layout xml file it will be shown as given below"
},
{
"code": null,
"e": 29407,
"s": 29399,
"text": "Output:"
},
{
"code": null,
"e": 29539,
"s": 29407,
"text": "Note: Similarly, Android App to subtract, multiply and divide numbers can be made by making minor changes in the Java and XML code."
},
{
"code": null,
"e": 29549,
"s": 29539,
"text": "vartika02"
},
{
"code": null,
"e": 29558,
"s": 29549,
"text": "sweetyty"
},
{
"code": null,
"e": 29566,
"s": 29558,
"text": "android"
},
{
"code": null,
"e": 29575,
"s": 29566,
"text": "Articles"
},
{
"code": null,
"e": 29581,
"s": 29575,
"text": "GBlog"
},
{
"code": null,
"e": 29595,
"s": 29581,
"text": "Java Programs"
},
{
"code": null,
"e": 29693,
"s": 29595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29702,
"s": 29693,
"text": "Comments"
},
{
"code": null,
"e": 29715,
"s": 29702,
"text": "Old Comments"
},
{
"code": null,
"e": 29768,
"s": 29715,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 29805,
"s": 29768,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 29824,
"s": 29805,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 29860,
"s": 29824,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 29914,
"s": 29860,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 29988,
"s": 29914,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30044,
"s": 29988,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30072,
"s": 30044,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30097,
"s": 30072,
"text": "DSA Sheet by Love Babbar"
}
] |
Create and Read QR code using Python | by Abhijith Chandradas | Towards Data Science
|
QR codes are machine readable two dimensional pixelated barcodes which can be used to store a variety of information. QR in QR code stands for Quick Response.QR code was invented by a Japanese engineer Masahiro Hara from automobile manufacturer Denso Wave in the year 1994 to track the movement of car parts.QR Code has increased in popularity in the later 2010s with improvement in optical capabilities of mobile phones and their wide adoption. Nowadays, QR codes are being used for wide variety of applications like, make online payments, check hotel menu, share wifi password, obtain price and other details of products etc. QR Codes have become so popular that now every new smartphone comes with in built QR code reader.
In this article we will learn how to read and generate QR Code using python.
Install QR Code module We will be using qrcode package for generating QR code. The first step is installing the package using pip command.
pip install qrcode
Full documentation of the package can be accessed in PYPI homepage of the package.
A simple qr code can be generated by using the make function of qrcode and passing the data as argument.The below code produces a QR code which reads ‘Hello World.’
#Import Libraryimport qrcode#Generate QR Codeimg=qrcode.make('Hello World')img.save('hello.png')
You can use your smart phone to read the above code.
Caution: Do not use your phone to read random QR codes as it may contain malicious code/links.
QR code can be customized using QRCode object which has the following parameters:
i. version: There are 40 versions of QR code which controls the size of the code.1 being the smallest and 40 being the largest. Version 1 will create a 21X21 matrix QR Code.
ii. error_correction:This parameter controls the Error Correction used for the QR code. This varies from 7% to 30% error correction as below.ERROR_CORRECT_L: up to 7%ERROR_CORRECT_M: up to 15%ERROR_CORRECT_Q: up to 25%ERROR_CORRECT_H: up to 30%
iii. box_size:This parameter controls the number of pixels in each box of the QR code
iv. border:This parameter controls the thickness of the border. The default border is 4 pixels thick.
The QRCode object has the following functions which can be used to create the QR Code.
i. add dataThe content of the QR code can be passed as an argument to this function.
ii. makeIf you are not sure about which version of QR code to use, the version can be set automatically by : a. setting version parameter to None and b. seting fit parameter of make to True.
iii. make imageThis function generates the QR code. It can also be used to set the fill color and background color of the QR code using fill_color and back_color arguments.
The following code generates a QR code which points towards my medium profile.
qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,)qr.add_data("https://abhijithchandradas.medium.com/")qr.make(fit=True)img = qr.make_image(fill_color="red", back_color="black")img.save("medium.png")
We will use OpenCV to read QR code. If the package is not installed, it can be installed as below:
pip install cv2
QR code can be decoded using detectAndDecode function of QRCodeDetector object of OpenCV.
import cv2img=cv2.imread("medium.png")det=cv2.QRCodeDetector()val, pts, st_code=det.detectAndDecode(img)print(val)Output:https://abhijithchandradas.medium.com/
The detectAndDecode function returns the content of the QR code, coordinates of the corners of the box and binarized QR code.You can refer OpenCV QRCodeDetector class reference for more information on reading QR code using OpenCV.
Code for the tutorial is available in my GitHub Repo.
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
|
[
{
"code": null,
"e": 898,
"s": 172,
"text": "QR codes are machine readable two dimensional pixelated barcodes which can be used to store a variety of information. QR in QR code stands for Quick Response.QR code was invented by a Japanese engineer Masahiro Hara from automobile manufacturer Denso Wave in the year 1994 to track the movement of car parts.QR Code has increased in popularity in the later 2010s with improvement in optical capabilities of mobile phones and their wide adoption. Nowadays, QR codes are being used for wide variety of applications like, make online payments, check hotel menu, share wifi password, obtain price and other details of products etc. QR Codes have become so popular that now every new smartphone comes with in built QR code reader."
},
{
"code": null,
"e": 975,
"s": 898,
"text": "In this article we will learn how to read and generate QR Code using python."
},
{
"code": null,
"e": 1114,
"s": 975,
"text": "Install QR Code module We will be using qrcode package for generating QR code. The first step is installing the package using pip command."
},
{
"code": null,
"e": 1133,
"s": 1114,
"text": "pip install qrcode"
},
{
"code": null,
"e": 1216,
"s": 1133,
"text": "Full documentation of the package can be accessed in PYPI homepage of the package."
},
{
"code": null,
"e": 1381,
"s": 1216,
"text": "A simple qr code can be generated by using the make function of qrcode and passing the data as argument.The below code produces a QR code which reads ‘Hello World.’"
},
{
"code": null,
"e": 1478,
"s": 1381,
"text": "#Import Libraryimport qrcode#Generate QR Codeimg=qrcode.make('Hello World')img.save('hello.png')"
},
{
"code": null,
"e": 1531,
"s": 1478,
"text": "You can use your smart phone to read the above code."
},
{
"code": null,
"e": 1626,
"s": 1531,
"text": "Caution: Do not use your phone to read random QR codes as it may contain malicious code/links."
},
{
"code": null,
"e": 1708,
"s": 1626,
"text": "QR code can be customized using QRCode object which has the following parameters:"
},
{
"code": null,
"e": 1882,
"s": 1708,
"text": "i. version: There are 40 versions of QR code which controls the size of the code.1 being the smallest and 40 being the largest. Version 1 will create a 21X21 matrix QR Code."
},
{
"code": null,
"e": 2127,
"s": 1882,
"text": "ii. error_correction:This parameter controls the Error Correction used for the QR code. This varies from 7% to 30% error correction as below.ERROR_CORRECT_L: up to 7%ERROR_CORRECT_M: up to 15%ERROR_CORRECT_Q: up to 25%ERROR_CORRECT_H: up to 30%"
},
{
"code": null,
"e": 2213,
"s": 2127,
"text": "iii. box_size:This parameter controls the number of pixels in each box of the QR code"
},
{
"code": null,
"e": 2315,
"s": 2213,
"text": "iv. border:This parameter controls the thickness of the border. The default border is 4 pixels thick."
},
{
"code": null,
"e": 2402,
"s": 2315,
"text": "The QRCode object has the following functions which can be used to create the QR Code."
},
{
"code": null,
"e": 2487,
"s": 2402,
"text": "i. add dataThe content of the QR code can be passed as an argument to this function."
},
{
"code": null,
"e": 2678,
"s": 2487,
"text": "ii. makeIf you are not sure about which version of QR code to use, the version can be set automatically by : a. setting version parameter to None and b. seting fit parameter of make to True."
},
{
"code": null,
"e": 2851,
"s": 2678,
"text": "iii. make imageThis function generates the QR code. It can also be used to set the fill color and background color of the QR code using fill_color and back_color arguments."
},
{
"code": null,
"e": 2930,
"s": 2851,
"text": "The following code generates a QR code which points towards my medium profile."
},
{
"code": null,
"e": 3197,
"s": 2930,
"text": "qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,)qr.add_data(\"https://abhijithchandradas.medium.com/\")qr.make(fit=True)img = qr.make_image(fill_color=\"red\", back_color=\"black\")img.save(\"medium.png\")"
},
{
"code": null,
"e": 3296,
"s": 3197,
"text": "We will use OpenCV to read QR code. If the package is not installed, it can be installed as below:"
},
{
"code": null,
"e": 3312,
"s": 3296,
"text": "pip install cv2"
},
{
"code": null,
"e": 3402,
"s": 3312,
"text": "QR code can be decoded using detectAndDecode function of QRCodeDetector object of OpenCV."
},
{
"code": null,
"e": 3562,
"s": 3402,
"text": "import cv2img=cv2.imread(\"medium.png\")det=cv2.QRCodeDetector()val, pts, st_code=det.detectAndDecode(img)print(val)Output:https://abhijithchandradas.medium.com/"
},
{
"code": null,
"e": 3793,
"s": 3562,
"text": "The detectAndDecode function returns the content of the QR code, coordinates of the corners of the box and binarized QR code.You can refer OpenCV QRCodeDetector class reference for more information on reading QR code using OpenCV."
},
{
"code": null,
"e": 3847,
"s": 3793,
"text": "Code for the tutorial is available in my GitHub Repo."
}
] |
Git Pull Branch from GitHub
|
Now continue working on our new branch in our local Git.
Lets pull from our GitHub repository again so that our code is up-to-date:
git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 851 bytes | 9.00 KiB/s, done.
From https://github.com/w3schools-test/hello-world
* [new branch] html-skeleton -> origin/html-skeleton
Already up to date.
Now our main branch is up todate. And we can see that there is a new
branch
available on GitHub.
Do a quick status check:
git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
And confirm which branches we have, and where we are working at the moment:
git branch
* master
So, we do not have the new branch on our local Git. But
we know it is available on
GitHub. So we can use the -a option to see all local and remote branches:
git branch -a
* master
remotes/origin/html-skeleton
remotes/origin/master
Note: branch -r is for remote branches only.
We see that the branch html-skeleton is available remotely, but not on our local git. Lets check it out:
git checkout html-skeleton
Switched to a new branch 'html-skeleton'
Branch 'html-skeleton' set up to track remote branch 'html-skeleton' from 'origin'.
And check if it is all up to date:
git pull
Already up to date.
Which branches do we have now, and where are we working from?
git branch
* html-skeleton
master
Now, open your favourite editor and confirm that the changes from the GitHub branch carried over.
That is how you pull a GitHub branch to your local Git.
List all local and remote branches of the current Git.
git
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.
|
[
{
"code": null,
"e": 57,
"s": 0,
"text": "Now continue working on our new branch in our local Git."
},
{
"code": null,
"e": 132,
"s": 57,
"text": "Lets pull from our GitHub repository again so that our code is up-to-date:"
},
{
"code": null,
"e": 522,
"s": 132,
"text": "git pull\nremote: Enumerating objects: 5, done.\nremote: Counting objects: 100% (5/5), done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0\nUnpacking objects: 100% (3/3), 851 bytes | 9.00 KiB/s, done.\nFrom https://github.com/w3schools-test/hello-world\n * [new branch] html-skeleton -> origin/html-skeleton\nAlready up to date."
},
{
"code": null,
"e": 621,
"s": 522,
"text": "Now our main branch is up todate. And we can see that there is a new \nbranch \navailable on GitHub."
},
{
"code": null,
"e": 646,
"s": 621,
"text": "Do a quick status check:"
},
{
"code": null,
"e": 761,
"s": 646,
"text": "git status\nOn branch master\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean"
},
{
"code": null,
"e": 837,
"s": 761,
"text": "And confirm which branches we have, and where we are working at the moment:"
},
{
"code": null,
"e": 857,
"s": 837,
"text": "git branch\n* master"
},
{
"code": null,
"e": 1016,
"s": 857,
"text": "So, we do not have the new branch on our local Git. But \nwe know it is available on \nGitHub. So we can use the -a option to see all local and remote branches:"
},
{
"code": null,
"e": 1094,
"s": 1016,
"text": "git branch -a\n* master\n remotes/origin/html-skeleton\n remotes/origin/master"
},
{
"code": null,
"e": 1139,
"s": 1094,
"text": "Note: branch -r is for remote branches only."
},
{
"code": null,
"e": 1244,
"s": 1139,
"text": "We see that the branch html-skeleton is available remotely, but not on our local git. Lets check it out:"
},
{
"code": null,
"e": 1396,
"s": 1244,
"text": "git checkout html-skeleton\nSwitched to a new branch 'html-skeleton'\nBranch 'html-skeleton' set up to track remote branch 'html-skeleton' from 'origin'."
},
{
"code": null,
"e": 1431,
"s": 1396,
"text": "And check if it is all up to date:"
},
{
"code": null,
"e": 1460,
"s": 1431,
"text": "git pull\nAlready up to date."
},
{
"code": null,
"e": 1522,
"s": 1460,
"text": "Which branches do we have now, and where are we working from?"
},
{
"code": null,
"e": 1558,
"s": 1522,
"text": "git branch\n* html-skeleton\n master"
},
{
"code": null,
"e": 1656,
"s": 1558,
"text": "Now, open your favourite editor and confirm that the changes from the GitHub branch carried over."
},
{
"code": null,
"e": 1712,
"s": 1656,
"text": "That is how you pull a GitHub branch to your local Git."
},
{
"code": null,
"e": 1767,
"s": 1712,
"text": "List all local and remote branches of the current Git."
},
{
"code": null,
"e": 1774,
"s": 1767,
"text": "git \n"
},
{
"code": null,
"e": 1794,
"s": 1774,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 1827,
"s": 1794,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1869,
"s": 1827,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1976,
"s": 1869,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1995,
"s": 1976,
"text": "help@w3schools.com"
}
] |
Find the first repeating element in an array of integers - GeeksforGeeks
|
10 Feb, 2022
Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest.
Examples:
Input: arr[] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 [5 is the first element that repeats]
Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
Output: 6 [6 is the first element that repeats]
A Simple Solution is to use two nested loops. The outer loop picks an element one by one, the inner loop checks whether the element is repeated or not. Once we find an element that repeats, we break the loops and print the element. Time Complexity of this solution is O(n2)
We can Use Sorting to solve the problem in O(nLogn) time. Following are detailed steps. 1) Copy the given array to an auxiliary array temp[]. 2) Sort the temp array using a O(nLogn) time sorting algorithm. 3) Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find an element that occurs more than once, we return the element. This step can be done in O(nLogn) time.We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from right to left and update the minimum index whenever we find an element that has been visited on right side. Thanks to Mohammad Shahid for suggesting this solution.
Following is the implementation of this idea.
C++
Java
Python3
C#
Javascript
/* C++ program to find first repeating element in arr[] */#include<bits/stdc++.h>using namespace std; // This function prints the first repeating element in arr[]void printFirstRepeating(int arr[], int n){ // Initialize index of first repeating element int min = -1; // Creates an empty hashset set<int> myset; // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in hash set, update min if (myset.find(arr[i]) != myset.end()) min = i; else // Else add element to hash set myset.insert(arr[i]); } // Print the result if (min != -1) cout << "The first repeating element is " << arr[min]; else cout << "There are no repeating elements";} // Driver method to test above methodint main(){ int arr[] = {10, 5, 3, 4, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n);}//This article is contributed by Chhavi
/* Java program to find first repeating element in arr[] */import java.util.*; class Main{ // This function prints the first repeating element in arr[] static void printFirstRepeating(int arr[]) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Traverse the input array from right to left for (int i=arr.length-1; i>=0; i--) { // If element is already in hash set, update min if (set.contains(arr[i])) min = i; else // Else add element to hash set set.add(arr[i]); } // Print the result if (min != -1) System.out.println("The first repeating element is " + arr[min]); else System.out.println("There are no repeating elements"); } // Driver method to test above method public static void main (String[] args) throws java.lang.Exception { int arr[] = {10, 5, 3, 4, 3, 5, 6}; printFirstRepeating(arr); }}
# Python3 program to find first repeating# element in arr[] # This function prints the first repeating# element in arr[]def printFirstRepeating(arr, n): # Initialize index of first repeating element Min = -1 # Creates an empty hashset myset = dict() # Traverse the input array from right to left for i in range(n - 1, -1, -1): # If element is already in hash set, # update Min if arr[i] in myset.keys(): Min = i else: # Else add element to hash set myset[arr[i]] = 1 # Print the result if (Min != -1): print("The first repeating element is", arr[Min]) else: print("There are no repeating elements") # Driver Codearr = [10, 5, 3, 4, 3, 5, 6] n = len(arr)printFirstRepeating(arr, n) # This code is contributed by Mohit kumar 29
using System;using System.Collections.Generic; /* C# program to find first repeating element in arr[] */ public class GFG{ // This function prints the first repeating element in arr[] public static void printFirstRepeating(int[] arr) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array from right to left for (int i = arr.Length - 1; i >= 0; i--) { // If element is already in hash set, update min if (set.Contains(arr[i])) { min = i; } else // Else add element to hash set { set.Add(arr[i]); } } // Print the result if (min != -1) { Console.WriteLine("The first repeating element is " + arr[min]); } else { Console.WriteLine("There are no repeating elements"); } } // Driver method to test above method public static void Main(string[] args) { int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6}; printFirstRepeating(arr); }} // This code is contributed by Shrikant13
<script> // Javascript program to find first// repeating element in arr[] // This function prints the first// repeating element in arr[]function printFirstRepeating(arr){ // Initialize index of first // repeating element let min = -1; // Creates an empty hashset let set = new Set(); // Traverse the input array from right to left for(let i = arr.length - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.has(arr[i])) min = i; // Else add element to hash set else set.add(arr[i]); } // Print the result if (min != -1) document.write("The first repeating element is " + arr[min]); else document.write("There are no repeating elements");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ]; printFirstRepeating(arr); // This code is contributed by unknown2108 </script>
The first repeating element is 5
Another Approach:If you want to do this without using any additional data structure. The problem can also be solved using array only. See the method below.
C++
Java
Python3
C#
Javascript
/* C++ program to find firstrepeating element in arr[] */#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]void printFirstRepeating(int arr[], int n){ // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int a[max + 1] = {}; // Store 1 in array b // if element is duplicate // initialized by 0 int b[max + 1] = {}; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]]) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) cout << "No repeating element found" << endl; else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] && min > a[i] && b[i]) min = a[i]; cout << arr[min-1]; } cout << endl;} // Driver method to test above methodint main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n);}
/* Java program to find firstrepeating element in arr[] */public class GFG{ // This function prints the // first repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int[] a = new int[max + 1]; // Store 1 in array b // if element is duplicate // initialized by 0 int[] b = new int[max + 1]; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) System.out.println("No repeating element found"); else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] != 0 && min > a[i] && b[i] != 0) min = a[i]; System.out.print(arr[min-1]); } System.out.println(); } // Driver code public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; printFirstRepeating(arr, n); }} // This code is contributed by divyesh072019
# Python3 program to find first # repeating element in arr[] # This function prints the # first repeating element in arr[]def printFirstRepeating(arr, n): # This will set k=1, if any # repeating element found k = 0 # max = maximum from (all elements & n) max = n for i in range(n): if (max < arr[i]): max = arr[i] # Array a is for storing # 1st time occurrence of element # initialized by 0 a = [0 for i in range(max + 1)] # Store 1 in array b # if element is duplicate # initialized by 0 b = [0 for i in range(max + 1)] for i in range(n): # Duplicate element found if (a[arr[i]]): b[arr[i]] = 1 k = 1 continue else: # Storing 1st occurrence of arr[i] a[arr[i]] = i+1 if (k == 0): print("No repeating element found") else: min = max + 1 for i in range(max + 1): # Trace array a & find repeating # element with min index if (a[i] and (min > (a[i])) and b[i]): min = a[i] print(arr[min-1]) # Driver codearr = [ 10, 5, 3, 4, 3, 5, 6 ]n = len(arr) printFirstRepeating(arr, n) # This code is contributed by avanitrachhadiya2155
/* C# program to find firstrepeating element in arr[] */using System;class GFG{ // This function prints the // first repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int[] a = new int[max + 1]; // Store 1 in array b // if element is duplicate // initialized by 0 int[] b = new int[max + 1]; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) Console.WriteLine("No repeating element found"); else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if ((a[i] != 0) && min > a[i] && (b[i] != 0)) min = a[i]; Console.Write(arr[min-1]); } Console.WriteLine(); } // Driver code static void Main() { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; printFirstRepeating(arr, n); }} // This code is contributed by divyeshrabadiya07.
<script>/* javascript program to find firstrepeating element in arr */ // This function prints the // first repeating element in arr function printFirstRepeating(arr , n) { // This will set k=1, if any // repeating element found var k = 0; // max = maximum from (all elements & n) var max = n; for (i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 var a = Array(max + 1).fill(0); // Store 1 in array b // if element is duplicate // initialized by 0 var b = Array(max + 1).fill(0); for (var i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) document.write("No repeating element found"); else { var min = max + 1; // trace array a & find repeating element // with min index for (i = 0; i < max + 1; i++) if (a[i] != 0 && min > a[i] && b[i] != 0) min = a[i]; document.write(arr[min-1]); } document.write("<br/>"); } // Driver code var arr = [ 10, 5, 3, 4, 3, 5, 6 ]; var n = arr.length; printFirstRepeating(arr, n); // This code is contributed by todaysgaurav</script>
5
Time Complexity: O(n).
Another Approach By Using O(n) Auxiliary Space and O(n) Time Complexity:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int firstRepeated(int arr[], int n){ int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int temp[max + 1]; for (int i = 0; i < max + 1; i++) temp[i] = 0; for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found}int main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int index = firstRepeated( arr, n); // index Of 1st repeating number if (index != -1) { cout << "1st Repeating Number is " << arr[index]; } else { cout << "No Repeating Number Found"; } return 0;} // This code is contributed by gauravrajput1
/*package whatever //do not write package name here */ import java.io.*;class GFG { public static int firstRepeated(int[] arr, int n) { int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int temp[] = new int[max + 1]; // the idea is to use // temporary array as hashmap // Arrays.fill(temp, 0); for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; int index = firstRepeated( arr, arr.length); // index Of 1st repeating number if (index != -1) { System.out.println("1st Repeating Number is " + arr[index]); } else { System.out.println("No Repeating Number Found"); } }}
def firstRepeated(arr, n): max = 0; for x in range(n): if (arr[x] > max): max = arr[x]; temp = [0 for i in range(max + 1)]; # the idea is to use # temporary array as hashmap # Arrays.fill(temp, 0); for x in range(n): num = arr[x]; temp[num]+=1; for x in range(n): num = arr[x]; if (temp[num] > 1): return x; return -1; # if no repeating element found if __name__ == '__main__': arr = [ 10, 5, 3, 4, 3, 5, 6 ]; n = len(arr); index = firstRepeated(arr, len(arr)); # index Of 1st repeating number if (index != -1): print("1st Repeating Number is ", arr[index]); else: print("No Repeating Number Found"); # This code is contributed by gauravrajput1
/*package whatever //do not write package name here */using System;using System.Collections.Generic;public class GFG { public static int firstRepeated(int[] arr, int n) { int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int []temp = new int[max + 1]; // the idea is to use // temporary array as hashmap for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } // Driver code public static void Main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; int index = firstRepeated( arr, arr.Length); // index Of 1st repeating number if (index != -1) { Console.WriteLine("1st Repeating Number is " + arr[index]); } else { Console.WriteLine("No Repeating Number Found"); } }} // This code is contributed by gauravrajput1
<script> function firstRepeated(arr, n) { var max = 0; for (var x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } var temp = new Array(max + 1); // the idea is to use // temporary array as hashmap // Arrays.fill(temp, 0); for (var x = 0; x < n; x++) { var num = arr[x]; temp[num]++; } for (var x = 0; x < n; x++) { var num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } var arr = [ 10, 5, 3, 4, 3, 5, 6 ]; var n = arr.length; var index = firstRepeated( arr, arr.length); // index Of 1st repeating number if (index = 1) { document.write("1st Repeating Number is " + arr[index]); } else { document.write("No Repeating Number Found"); } // This code is contributed by shivanisinghss2110</script>
Another Approach Using Python inbuilt functions:
C++
Java
Python3
C#
Javascript
// C++ program to find first// repeating element in arr[]#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]string printFirstRepeating(vector<int> a) { for (int i = 0; i < a.size(); i++) { if (count(a.begin(), a.end(), a[i]) > 1) return to_string(a[i]); } return "there is no repetition number";} int main(){ // Driver code std::vector<int> arr{ 10, 5, 3, 4, 3, 5, 6 }; cout<<(printFirstRepeating(arr)); return 0;} // This code is contributed by Rajput-Ji
import java.util.Arrays;import java.util.Collections;import java.util.List; // Java program to find first// repeating element in arr[]class GFG{ // This function prints the // first repeating element in arr[] static String printFirstRepeating(List<Integer> a) { for (int i = 0; i < a.size(); i++) { if (Collections.frequency(a, a.get(i)) > 1) return String.valueOf(a.get(i)); } return "there is no repetition number"; } public static void main(String[] args) { // Driver code Integer[] arr = { 10, 5, 3, 4, 3, 5, 6 }; System.out.println(printFirstRepeating(Arrays.asList(arr))); }} // This code is contributed by shikhasingrajput
# Python3 program to find first# repeating element in arr[] # This function prints the# first repeating element in arr[]def printFirstRepeating(a, n): for i in range(len(a)): if a.count(a[i]) > 1: return a[i] return "there is no repetition number" # Driver codearr = [10, 5, 3, 4, 3, 5, 6]n = len(arr)print(printFirstRepeating(arr, n)) # This code is contributed by karthikeyakumarnallam
// C# program to find first// repeating element in arr[]using System;using System.Collections.Generic;class GFG{ // This function prints the first // repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // Initialize index of first // repeating element int min = -1; // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.Contains(arr[i])) min = i; // Else add element to hash set else set.Add(arr[i]); } // Print the result if (min != -1) Console.Write(arr[min]); else Console.Write("there is no repetition number"); } // Driver code public static void Main() { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; printFirstRepeating(arr, n); } } // This code is contributed by gfgking
<script> // Javascript program to find first// repeating element in arr[] // This function prints the first// repeating element in arr[]function printFirstRepeating(arr, n){ // Initialize index of first // repeating element let min = -1; // Creates an empty hashset let set = new Set(); // Traverse the input array from right to left for(let i = n - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.has(arr[i])) min = i; // Else add element to hash set else set.add(arr[i]); } // Print the result if (min != -1) document.write(arr[min]); else document.write("there is no repetition number");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ];let n = arr.length; printFirstRepeating(arr, n); // This code is contributed by splevel62.</script>
5
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
mohit kumar 29
rampaliwal49
avanitrachhadiya2155
karthikeyakumarnallam
divyeshrabadiya07
divyesh072019
sarthak8858
unknown2108
todaysgaurav
surindertarika1234
khushboogoyal499
GauravRajput1
simmytarika5
shivanisinghss2110
splevel62
shikhasingrajput
gfgking
Rajput-Ji
Amazon
Oracle
Arrays
Hash
Searching
Amazon
Oracle
Arrays
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 24395,
"s": 24367,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 24568,
"s": 24395,
"text": "Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest. "
},
{
"code": null,
"e": 24579,
"s": 24568,
"text": "Examples: "
},
{
"code": null,
"e": 24763,
"s": 24579,
"text": "Input: arr[] = {10, 5, 3, 4, 3, 5, 6}\nOutput: 5 [5 is the first element that repeats]\n\nInput: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}\nOutput: 6 [6 is the first element that repeats]"
},
{
"code": null,
"e": 25037,
"s": 24763,
"text": "A Simple Solution is to use two nested loops. The outer loop picks an element one by one, the inner loop checks whether the element is repeated or not. Once we find an element that repeats, we break the loops and print the element. Time Complexity of this solution is O(n2)"
},
{
"code": null,
"e": 25746,
"s": 25037,
"text": "We can Use Sorting to solve the problem in O(nLogn) time. Following are detailed steps. 1) Copy the given array to an auxiliary array temp[]. 2) Sort the temp array using a O(nLogn) time sorting algorithm. 3) Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find an element that occurs more than once, we return the element. This step can be done in O(nLogn) time.We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from right to left and update the minimum index whenever we find an element that has been visited on right side. Thanks to Mohammad Shahid for suggesting this solution."
},
{
"code": null,
"e": 25792,
"s": 25746,
"text": "Following is the implementation of this idea."
},
{
"code": null,
"e": 25796,
"s": 25792,
"text": "C++"
},
{
"code": null,
"e": 25801,
"s": 25796,
"text": "Java"
},
{
"code": null,
"e": 25809,
"s": 25801,
"text": "Python3"
},
{
"code": null,
"e": 25812,
"s": 25809,
"text": "C#"
},
{
"code": null,
"e": 25823,
"s": 25812,
"text": "Javascript"
},
{
"code": "/* C++ program to find first repeating element in arr[] */#include<bits/stdc++.h>using namespace std; // This function prints the first repeating element in arr[]void printFirstRepeating(int arr[], int n){ // Initialize index of first repeating element int min = -1; // Creates an empty hashset set<int> myset; // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in hash set, update min if (myset.find(arr[i]) != myset.end()) min = i; else // Else add element to hash set myset.insert(arr[i]); } // Print the result if (min != -1) cout << \"The first repeating element is \" << arr[min]; else cout << \"There are no repeating elements\";} // Driver method to test above methodint main(){ int arr[] = {10, 5, 3, 4, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n);}//This article is contributed by Chhavi",
"e": 26811,
"s": 25823,
"text": null
},
{
"code": "/* Java program to find first repeating element in arr[] */import java.util.*; class Main{ // This function prints the first repeating element in arr[] static void printFirstRepeating(int arr[]) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Traverse the input array from right to left for (int i=arr.length-1; i>=0; i--) { // If element is already in hash set, update min if (set.contains(arr[i])) min = i; else // Else add element to hash set set.add(arr[i]); } // Print the result if (min != -1) System.out.println(\"The first repeating element is \" + arr[min]); else System.out.println(\"There are no repeating elements\"); } // Driver method to test above method public static void main (String[] args) throws java.lang.Exception { int arr[] = {10, 5, 3, 4, 3, 5, 6}; printFirstRepeating(arr); }}",
"e": 27900,
"s": 26811,
"text": null
},
{
"code": "# Python3 program to find first repeating# element in arr[] # This function prints the first repeating# element in arr[]def printFirstRepeating(arr, n): # Initialize index of first repeating element Min = -1 # Creates an empty hashset myset = dict() # Traverse the input array from right to left for i in range(n - 1, -1, -1): # If element is already in hash set, # update Min if arr[i] in myset.keys(): Min = i else: # Else add element to hash set myset[arr[i]] = 1 # Print the result if (Min != -1): print(\"The first repeating element is\", arr[Min]) else: print(\"There are no repeating elements\") # Driver Codearr = [10, 5, 3, 4, 3, 5, 6] n = len(arr)printFirstRepeating(arr, n) # This code is contributed by Mohit kumar 29",
"e": 28768,
"s": 27900,
"text": null
},
{
"code": "using System;using System.Collections.Generic; /* C# program to find first repeating element in arr[] */ public class GFG{ // This function prints the first repeating element in arr[] public static void printFirstRepeating(int[] arr) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array from right to left for (int i = arr.Length - 1; i >= 0; i--) { // If element is already in hash set, update min if (set.Contains(arr[i])) { min = i; } else // Else add element to hash set { set.Add(arr[i]); } } // Print the result if (min != -1) { Console.WriteLine(\"The first repeating element is \" + arr[min]); } else { Console.WriteLine(\"There are no repeating elements\"); } } // Driver method to test above method public static void Main(string[] args) { int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6}; printFirstRepeating(arr); }} // This code is contributed by Shrikant13",
"e": 30010,
"s": 28768,
"text": null
},
{
"code": "<script> // Javascript program to find first// repeating element in arr[] // This function prints the first// repeating element in arr[]function printFirstRepeating(arr){ // Initialize index of first // repeating element let min = -1; // Creates an empty hashset let set = new Set(); // Traverse the input array from right to left for(let i = arr.length - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.has(arr[i])) min = i; // Else add element to hash set else set.add(arr[i]); } // Print the result if (min != -1) document.write(\"The first repeating element is \" + arr[min]); else document.write(\"There are no repeating elements\");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ]; printFirstRepeating(arr); // This code is contributed by unknown2108 </script>",
"e": 30968,
"s": 30010,
"text": null
},
{
"code": null,
"e": 31004,
"s": 30971,
"text": "The first repeating element is 5"
},
{
"code": null,
"e": 31163,
"s": 31006,
"text": "Another Approach:If you want to do this without using any additional data structure. The problem can also be solved using array only. See the method below. "
},
{
"code": null,
"e": 31169,
"s": 31165,
"text": "C++"
},
{
"code": null,
"e": 31174,
"s": 31169,
"text": "Java"
},
{
"code": null,
"e": 31182,
"s": 31174,
"text": "Python3"
},
{
"code": null,
"e": 31185,
"s": 31182,
"text": "C#"
},
{
"code": null,
"e": 31196,
"s": 31185,
"text": "Javascript"
},
{
"code": "/* C++ program to find firstrepeating element in arr[] */#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]void printFirstRepeating(int arr[], int n){ // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int a[max + 1] = {}; // Store 1 in array b // if element is duplicate // initialized by 0 int b[max + 1] = {}; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]]) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) cout << \"No repeating element found\" << endl; else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] && min > a[i] && b[i]) min = a[i]; cout << arr[min-1]; } cout << endl;} // Driver method to test above methodint main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n);}",
"e": 32632,
"s": 31196,
"text": null
},
{
"code": "/* Java program to find firstrepeating element in arr[] */public class GFG{ // This function prints the // first repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int[] a = new int[max + 1]; // Store 1 in array b // if element is duplicate // initialized by 0 int[] b = new int[max + 1]; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) System.out.println(\"No repeating element found\"); else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] != 0 && min > a[i] && b[i] != 0) min = a[i]; System.out.print(arr[min-1]); } System.out.println(); } // Driver code public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; printFirstRepeating(arr, n); }} // This code is contributed by divyesh072019",
"e": 34078,
"s": 32632,
"text": null
},
{
"code": "# Python3 program to find first # repeating element in arr[] # This function prints the # first repeating element in arr[]def printFirstRepeating(arr, n): # This will set k=1, if any # repeating element found k = 0 # max = maximum from (all elements & n) max = n for i in range(n): if (max < arr[i]): max = arr[i] # Array a is for storing # 1st time occurrence of element # initialized by 0 a = [0 for i in range(max + 1)] # Store 1 in array b # if element is duplicate # initialized by 0 b = [0 for i in range(max + 1)] for i in range(n): # Duplicate element found if (a[arr[i]]): b[arr[i]] = 1 k = 1 continue else: # Storing 1st occurrence of arr[i] a[arr[i]] = i+1 if (k == 0): print(\"No repeating element found\") else: min = max + 1 for i in range(max + 1): # Trace array a & find repeating # element with min index if (a[i] and (min > (a[i])) and b[i]): min = a[i] print(arr[min-1]) # Driver codearr = [ 10, 5, 3, 4, 3, 5, 6 ]n = len(arr) printFirstRepeating(arr, n) # This code is contributed by avanitrachhadiya2155",
"e": 35377,
"s": 34078,
"text": null
},
{
"code": "/* C# program to find firstrepeating element in arr[] */using System;class GFG{ // This function prints the // first repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int[] a = new int[max + 1]; // Store 1 in array b // if element is duplicate // initialized by 0 int[] b = new int[max + 1]; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) Console.WriteLine(\"No repeating element found\"); else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if ((a[i] != 0) && min > a[i] && (b[i] != 0)) min = a[i]; Console.Write(arr[min-1]); } Console.WriteLine(); } // Driver code static void Main() { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; printFirstRepeating(arr, n); }} // This code is contributed by divyeshrabadiya07.",
"e": 37107,
"s": 35377,
"text": null
},
{
"code": "<script>/* javascript program to find firstrepeating element in arr */ // This function prints the // first repeating element in arr function printFirstRepeating(arr , n) { // This will set k=1, if any // repeating element found var k = 0; // max = maximum from (all elements & n) var max = n; for (i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 var a = Array(max + 1).fill(0); // Store 1 in array b // if element is duplicate // initialized by 0 var b = Array(max + 1).fill(0); for (var i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]] != 0) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i+1; } if (k == 0) document.write(\"No repeating element found\"); else { var min = max + 1; // trace array a & find repeating element // with min index for (i = 0; i < max + 1; i++) if (a[i] != 0 && min > a[i] && b[i] != 0) min = a[i]; document.write(arr[min-1]); } document.write(\"<br/>\"); } // Driver code var arr = [ 10, 5, 3, 4, 3, 5, 6 ]; var n = arr.length; printFirstRepeating(arr, n); // This code is contributed by todaysgaurav</script>",
"e": 38708,
"s": 37107,
"text": null
},
{
"code": null,
"e": 38710,
"s": 38708,
"text": "5"
},
{
"code": null,
"e": 38733,
"s": 38710,
"text": "Time Complexity: O(n)."
},
{
"code": null,
"e": 38806,
"s": 38733,
"text": "Another Approach By Using O(n) Auxiliary Space and O(n) Time Complexity:"
},
{
"code": null,
"e": 38810,
"s": 38806,
"text": "C++"
},
{
"code": null,
"e": 38815,
"s": 38810,
"text": "Java"
},
{
"code": null,
"e": 38823,
"s": 38815,
"text": "Python3"
},
{
"code": null,
"e": 38826,
"s": 38823,
"text": "C#"
},
{
"code": null,
"e": 38837,
"s": 38826,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int firstRepeated(int arr[], int n){ int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int temp[max + 1]; for (int i = 0; i < max + 1; i++) temp[i] = 0; for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found}int main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int index = firstRepeated( arr, n); // index Of 1st repeating number if (index != -1) { cout << \"1st Repeating Number is \" << arr[index]; } else { cout << \"No Repeating Number Found\"; } return 0;} // This code is contributed by gauravrajput1",
"e": 39746,
"s": 38837,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;class GFG { public static int firstRepeated(int[] arr, int n) { int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int temp[] = new int[max + 1]; // the idea is to use // temporary array as hashmap // Arrays.fill(temp, 0); for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; int index = firstRepeated( arr, arr.length); // index Of 1st repeating number if (index != -1) { System.out.println(\"1st Repeating Number is \" + arr[index]); } else { System.out.println(\"No Repeating Number Found\"); } }}",
"e": 40947,
"s": 39746,
"text": null
},
{
"code": "def firstRepeated(arr, n): max = 0; for x in range(n): if (arr[x] > max): max = arr[x]; temp = [0 for i in range(max + 1)]; # the idea is to use # temporary array as hashmap # Arrays.fill(temp, 0); for x in range(n): num = arr[x]; temp[num]+=1; for x in range(n): num = arr[x]; if (temp[num] > 1): return x; return -1; # if no repeating element found if __name__ == '__main__': arr = [ 10, 5, 3, 4, 3, 5, 6 ]; n = len(arr); index = firstRepeated(arr, len(arr)); # index Of 1st repeating number if (index != -1): print(\"1st Repeating Number is \", arr[index]); else: print(\"No Repeating Number Found\"); # This code is contributed by gauravrajput1",
"e": 41759,
"s": 40947,
"text": null
},
{
"code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic;public class GFG { public static int firstRepeated(int[] arr, int n) { int max = 0; for (int x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } int []temp = new int[max + 1]; // the idea is to use // temporary array as hashmap for (int x = 0; x < n; x++) { int num = arr[x]; temp[num]++; } for (int x = 0; x < n; x++) { int num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } // Driver code public static void Main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; int index = firstRepeated( arr, arr.Length); // index Of 1st repeating number if (index != -1) { Console.WriteLine(\"1st Repeating Number is \" + arr[index]); } else { Console.WriteLine(\"No Repeating Number Found\"); } }} // This code is contributed by gauravrajput1",
"e": 42826,
"s": 41759,
"text": null
},
{
"code": "<script> function firstRepeated(arr, n) { var max = 0; for (var x = 0; x < n; x++) { if (arr[x] > max) { max = arr[x]; } } var temp = new Array(max + 1); // the idea is to use // temporary array as hashmap // Arrays.fill(temp, 0); for (var x = 0; x < n; x++) { var num = arr[x]; temp[num]++; } for (var x = 0; x < n; x++) { var num = arr[x]; if (temp[num] > 1) { return x; } } return -1; // if no repeating element found } var arr = [ 10, 5, 3, 4, 3, 5, 6 ]; var n = arr.length; var index = firstRepeated( arr, arr.length); // index Of 1st repeating number if (index = 1) { document.write(\"1st Repeating Number is \" + arr[index]); } else { document.write(\"No Repeating Number Found\"); } // This code is contributed by shivanisinghss2110</script>",
"e": 43924,
"s": 42826,
"text": null
},
{
"code": null,
"e": 43974,
"s": 43924,
"text": "Another Approach Using Python inbuilt functions: "
},
{
"code": null,
"e": 43978,
"s": 43974,
"text": "C++"
},
{
"code": null,
"e": 43983,
"s": 43978,
"text": "Java"
},
{
"code": null,
"e": 43991,
"s": 43983,
"text": "Python3"
},
{
"code": null,
"e": 43994,
"s": 43991,
"text": "C#"
},
{
"code": null,
"e": 44005,
"s": 43994,
"text": "Javascript"
},
{
"code": "// C++ program to find first// repeating element in arr[]#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]string printFirstRepeating(vector<int> a) { for (int i = 0; i < a.size(); i++) { if (count(a.begin(), a.end(), a[i]) > 1) return to_string(a[i]); } return \"there is no repetition number\";} int main(){ // Driver code std::vector<int> arr{ 10, 5, 3, 4, 3, 5, 6 }; cout<<(printFirstRepeating(arr)); return 0;} // This code is contributed by Rajput-Ji",
"e": 44534,
"s": 44005,
"text": null
},
{
"code": "import java.util.Arrays;import java.util.Collections;import java.util.List; // Java program to find first// repeating element in arr[]class GFG{ // This function prints the // first repeating element in arr[] static String printFirstRepeating(List<Integer> a) { for (int i = 0; i < a.size(); i++) { if (Collections.frequency(a, a.get(i)) > 1) return String.valueOf(a.get(i)); } return \"there is no repetition number\"; } public static void main(String[] args) { // Driver code Integer[] arr = { 10, 5, 3, 4, 3, 5, 6 }; System.out.println(printFirstRepeating(Arrays.asList(arr))); }} // This code is contributed by shikhasingrajput",
"e": 45256,
"s": 44534,
"text": null
},
{
"code": "# Python3 program to find first# repeating element in arr[] # This function prints the# first repeating element in arr[]def printFirstRepeating(a, n): for i in range(len(a)): if a.count(a[i]) > 1: return a[i] return \"there is no repetition number\" # Driver codearr = [10, 5, 3, 4, 3, 5, 6]n = len(arr)print(printFirstRepeating(arr, n)) # This code is contributed by karthikeyakumarnallam",
"e": 45669,
"s": 45256,
"text": null
},
{
"code": "// C# program to find first// repeating element in arr[]using System;using System.Collections.Generic;class GFG{ // This function prints the first // repeating element in arr[] static void printFirstRepeating(int[] arr, int n) { // Initialize index of first // repeating element int min = -1; // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.Contains(arr[i])) min = i; // Else add element to hash set else set.Add(arr[i]); } // Print the result if (min != -1) Console.Write(arr[min]); else Console.Write(\"there is no repetition number\"); } // Driver code public static void Main() { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; printFirstRepeating(arr, n); } } // This code is contributed by gfgking",
"e": 46654,
"s": 45669,
"text": null
},
{
"code": "<script> // Javascript program to find first// repeating element in arr[] // This function prints the first// repeating element in arr[]function printFirstRepeating(arr, n){ // Initialize index of first // repeating element let min = -1; // Creates an empty hashset let set = new Set(); // Traverse the input array from right to left for(let i = n - 1; i >= 0; i--) { // If element is already in // hash set, update min if (set.has(arr[i])) min = i; // Else add element to hash set else set.add(arr[i]); } // Print the result if (min != -1) document.write(arr[min]); else document.write(\"there is no repetition number\");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ];let n = arr.length; printFirstRepeating(arr, n); // This code is contributed by splevel62.</script>",
"e": 47558,
"s": 46654,
"text": null
},
{
"code": null,
"e": 47560,
"s": 47558,
"text": "5"
},
{
"code": null,
"e": 47685,
"s": 47560,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 47697,
"s": 47685,
"text": "shrikanth13"
},
{
"code": null,
"e": 47712,
"s": 47697,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 47725,
"s": 47712,
"text": "rampaliwal49"
},
{
"code": null,
"e": 47746,
"s": 47725,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 47768,
"s": 47746,
"text": "karthikeyakumarnallam"
},
{
"code": null,
"e": 47786,
"s": 47768,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 47800,
"s": 47786,
"text": "divyesh072019"
},
{
"code": null,
"e": 47812,
"s": 47800,
"text": "sarthak8858"
},
{
"code": null,
"e": 47824,
"s": 47812,
"text": "unknown2108"
},
{
"code": null,
"e": 47837,
"s": 47824,
"text": "todaysgaurav"
},
{
"code": null,
"e": 47856,
"s": 47837,
"text": "surindertarika1234"
},
{
"code": null,
"e": 47873,
"s": 47856,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 47887,
"s": 47873,
"text": "GauravRajput1"
},
{
"code": null,
"e": 47900,
"s": 47887,
"text": "simmytarika5"
},
{
"code": null,
"e": 47919,
"s": 47900,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 47929,
"s": 47919,
"text": "splevel62"
},
{
"code": null,
"e": 47946,
"s": 47929,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 47954,
"s": 47946,
"text": "gfgking"
},
{
"code": null,
"e": 47964,
"s": 47954,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 47971,
"s": 47964,
"text": "Amazon"
},
{
"code": null,
"e": 47978,
"s": 47971,
"text": "Oracle"
},
{
"code": null,
"e": 47985,
"s": 47978,
"text": "Arrays"
},
{
"code": null,
"e": 47990,
"s": 47985,
"text": "Hash"
},
{
"code": null,
"e": 48000,
"s": 47990,
"text": "Searching"
},
{
"code": null,
"e": 48007,
"s": 48000,
"text": "Amazon"
},
{
"code": null,
"e": 48014,
"s": 48007,
"text": "Oracle"
},
{
"code": null,
"e": 48021,
"s": 48014,
"text": "Arrays"
},
{
"code": null,
"e": 48031,
"s": 48021,
"text": "Searching"
},
{
"code": null,
"e": 48036,
"s": 48031,
"text": "Hash"
},
{
"code": null,
"e": 48134,
"s": 48036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48143,
"s": 48134,
"text": "Comments"
},
{
"code": null,
"e": 48156,
"s": 48143,
"text": "Old Comments"
},
{
"code": null,
"e": 48204,
"s": 48156,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 48248,
"s": 48204,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 48271,
"s": 48248,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 48303,
"s": 48271,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 48317,
"s": 48303,
"text": "Linear Search"
},
{
"code": null,
"e": 48402,
"s": 48317,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 48438,
"s": 48402,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 48469,
"s": 48438,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 48496,
"s": 48469,
"text": "Count pairs with given sum"
}
] |
Difference between exit() and break in C/C++ - GeeksforGeeks
|
02 Dec, 2021
In this article, the topic is to understand the difference between exit() and break.
exit():
When a user wants to exit a program from this function is used.
It is a void return type function that calls all functions registered at the exit and terminates the program.
File buffers are flushed, streams are closed, and temporary files are deleted and hence memory is freed.
syntax:
void exit(int status);
The parameters used are as follows:
break():
This function is generally used to come out of a loop at the instant.
When a break statement is executed it transfers the control to the statements that follow the switch or loop.
syntax:
break;
Program 1:
Below is a C program demonstrating the use of break:
C++
C
// C++ program to demonstrate the use// of break statement#include <iostream>using namespace std; // Driver Codeint main(){ // Local variable definition int a = 10; // While loop execution while (a < 20) { cout <<"value of a:"<< a<< endl; a++; // terminate the loop using // break statement if (a > 15) { break; } } cout <<"The break statement executed" " when when the value " " became "<< a; return 0;} //this code is contributed by shivanisinghss2110
// C program to demonstrate the use// of break statement#include <stdio.h> // Driver Codeint main(){ // Local variable definition int a = 10; // While loop execution while (a < 20) { printf("value of a: %d\n", a); a++; // terminate the loop using // break statement if (a > 15) { break; } } printf("The break statement executed" " when when the value " " became %d\n", a); return 0;}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
The break statement executed when when the value became 16
Explanation: In the above code, break terminates the while loop when the if the condition is satisfied and the code hereafter while loop will be executed after breaking the loop.
Program 2:
Below is C program demonstrating the use of exit():
C++
C
// C++ program to demonstrate the// use of exit()#include <iostream>using namespace std; // Driver Codeint main(){ for (int i = 1; i < 5; i++) { if (i == 3) exit(0); cout <<"i = "<< i << "\n"; } for (int j = 9; j > 0; j--) { if (j == 5) cout <<"j = "<< j; } return 0;} // This code is contributed by shivanisinghss2110
// C program to demonstrate the// use of exit()#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ for (int i = 1; i < 5; i++) { if (i == 3) exit(0); printf("i = %d \t", i); } printf("\n"); for (int j = 9; j > 0; j--) { if (j == 5) printf("j = %d \t", j); } return 0;}
i = 1 i = 2
Explanation: In the above code, after the exit function is executed, the program gets terminated and no code after that gets executed.
simmytarika5
shivanisinghss2110
saimthis1997
C Basics
exit
C Language
C Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 24317,
"s": 24232,
"text": "In this article, the topic is to understand the difference between exit() and break."
},
{
"code": null,
"e": 24325,
"s": 24317,
"text": "exit():"
},
{
"code": null,
"e": 24389,
"s": 24325,
"text": "When a user wants to exit a program from this function is used."
},
{
"code": null,
"e": 24499,
"s": 24389,
"text": "It is a void return type function that calls all functions registered at the exit and terminates the program."
},
{
"code": null,
"e": 24604,
"s": 24499,
"text": "File buffers are flushed, streams are closed, and temporary files are deleted and hence memory is freed."
},
{
"code": null,
"e": 24613,
"s": 24604,
"text": "syntax: "
},
{
"code": null,
"e": 24636,
"s": 24613,
"text": "void exit(int status);"
},
{
"code": null,
"e": 24672,
"s": 24636,
"text": "The parameters used are as follows:"
},
{
"code": null,
"e": 24681,
"s": 24672,
"text": "break():"
},
{
"code": null,
"e": 24751,
"s": 24681,
"text": "This function is generally used to come out of a loop at the instant."
},
{
"code": null,
"e": 24861,
"s": 24751,
"text": "When a break statement is executed it transfers the control to the statements that follow the switch or loop."
},
{
"code": null,
"e": 24869,
"s": 24861,
"text": "syntax:"
},
{
"code": null,
"e": 24876,
"s": 24869,
"text": "break;"
},
{
"code": null,
"e": 24887,
"s": 24876,
"text": "Program 1:"
},
{
"code": null,
"e": 24940,
"s": 24887,
"text": "Below is a C program demonstrating the use of break:"
},
{
"code": null,
"e": 24944,
"s": 24940,
"text": "C++"
},
{
"code": null,
"e": 24946,
"s": 24944,
"text": "C"
},
{
"code": "// C++ program to demonstrate the use// of break statement#include <iostream>using namespace std; // Driver Codeint main(){ // Local variable definition int a = 10; // While loop execution while (a < 20) { cout <<\"value of a:\"<< a<< endl; a++; // terminate the loop using // break statement if (a > 15) { break; } } cout <<\"The break statement executed\" \" when when the value \" \" became \"<< a; return 0;} //this code is contributed by shivanisinghss2110",
"e": 25499,
"s": 24946,
"text": null
},
{
"code": "// C program to demonstrate the use// of break statement#include <stdio.h> // Driver Codeint main(){ // Local variable definition int a = 10; // While loop execution while (a < 20) { printf(\"value of a: %d\\n\", a); a++; // terminate the loop using // break statement if (a > 15) { break; } } printf(\"The break statement executed\" \" when when the value \" \" became %d\\n\", a); return 0;}",
"e": 25992,
"s": 25499,
"text": null
},
{
"code": null,
"e": 26142,
"s": 25992,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nThe break statement executed when when the value became 16"
},
{
"code": null,
"e": 26323,
"s": 26144,
"text": "Explanation: In the above code, break terminates the while loop when the if the condition is satisfied and the code hereafter while loop will be executed after breaking the loop."
},
{
"code": null,
"e": 26334,
"s": 26323,
"text": "Program 2:"
},
{
"code": null,
"e": 26388,
"s": 26334,
"text": "Below is C program demonstrating the use of exit(): "
},
{
"code": null,
"e": 26392,
"s": 26388,
"text": "C++"
},
{
"code": null,
"e": 26394,
"s": 26392,
"text": "C"
},
{
"code": "// C++ program to demonstrate the// use of exit()#include <iostream>using namespace std; // Driver Codeint main(){ for (int i = 1; i < 5; i++) { if (i == 3) exit(0); cout <<\"i = \"<< i << \"\\n\"; } for (int j = 9; j > 0; j--) { if (j == 5) cout <<\"j = \"<< j; } return 0;} // This code is contributed by shivanisinghss2110",
"e": 26779,
"s": 26394,
"text": null
},
{
"code": "// C program to demonstrate the// use of exit()#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ for (int i = 1; i < 5; i++) { if (i == 3) exit(0); printf(\"i = %d \\t\", i); } printf(\"\\n\"); for (int j = 9; j > 0; j--) { if (j == 5) printf(\"j = %d \\t\", j); } return 0;}",
"e": 27124,
"s": 26779,
"text": null
},
{
"code": null,
"e": 27140,
"s": 27124,
"text": "i = 1 i = 2"
},
{
"code": null,
"e": 27277,
"s": 27142,
"text": "Explanation: In the above code, after the exit function is executed, the program gets terminated and no code after that gets executed."
},
{
"code": null,
"e": 27292,
"s": 27279,
"text": "simmytarika5"
},
{
"code": null,
"e": 27311,
"s": 27292,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 27324,
"s": 27311,
"text": "saimthis1997"
},
{
"code": null,
"e": 27333,
"s": 27324,
"text": "C Basics"
},
{
"code": null,
"e": 27338,
"s": 27333,
"text": "exit"
},
{
"code": null,
"e": 27349,
"s": 27338,
"text": "C Language"
},
{
"code": null,
"e": 27360,
"s": 27349,
"text": "C Programs"
},
{
"code": null,
"e": 27379,
"s": 27360,
"text": "Difference Between"
},
{
"code": null,
"e": 27477,
"s": 27379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27515,
"s": 27477,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27535,
"s": 27515,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27561,
"s": 27535,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27583,
"s": 27561,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27624,
"s": 27583,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27637,
"s": 27624,
"text": "Strings in C"
},
{
"code": null,
"e": 27678,
"s": 27637,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27716,
"s": 27678,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27757,
"s": 27716,
"text": "C Program to read contents of Whole File"
}
] |
Circular Fillable Loader in Android with Seekbar - GeeksforGeeks
|
30 Apr, 2021
Circular Fillable Loader is an outstanding way of showing the ProgressBar in any Android app while loading. Display ProgressBar in another form is one of the best ways to increase the user experience. You can get to see these customize loaders in most of the apps. In this article, we are going to see how to implement Circular Fillable Loader in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
A unique way of representing a ProgressBar in Android.
Using a Circular Fillable Loader increases the user experience.
Gives animated look to our progress bar.
Attributes
Description
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency in build.gradle(Module:app) file
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.mikhaellopez:circularfillableloaders:1.3.2’
Step 3: Create a new State Progress Bar in your activity_main.xml file
Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingTop="16dp" android:paddingRight="16dp" android:paddingBottom="16dp" tools:context=".MainActivity"> <!--Circular Fallible Loader--> <com.mikhaellopez.circularfillableloaders.CircularFillableLoaders android:id="@+id/circularFillableLoaders" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:src="@drawable/ic_baseline_android_24" app:cfl_border="true" app:cfl_border_width="12dp" app:cfl_progress="80" app:cfl_wave_amplitude="0.06" app:cfl_wave_color="@color/purple_200" /> <!--Seek bar to increase fallible part--> <SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/circularFillableLoaders" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.SeekBar; import androidx.appcompat.app.AppCompatActivity; import com.mikhaellopez.circularfillableloaders.CircularFillableLoaders; public class MainActivity extends AppCompatActivity { // Variables Declared CircularFillableLoaders circularFillableLoaders; SeekBar seekBar; int progress = 80; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Code for implementing Circular Fallible Loader circularFillableLoaders = (CircularFillableLoaders) findViewById(R.id.circularFillableLoaders); // Set Progress circularFillableLoaders.setProgress(progress); seekBar = findViewById(R.id.seekBar); seekBar.setProgress(progress); seekBar.setMax(100); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { // Set Progress circularFillableLoaders.setProgress(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }}
Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.
Output:
Here we are going to implement the wave loading view. Here we are manually increasing the value of progress and the wave height is increasing. But It can also be used as a timer to set.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘me.itangqi.waveloadingview:library:0.3.5’
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="20dp" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <me.itangqi.waveloadingview.WaveLoadingView android:id="@+id/waveLoadingView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:wlv_borderColor="@color/colorAccent" app:wlv_borderWidth="3dp" app:wlv_progressValue="40" app:wlv_round_rectangle="true" app:wlv_shapeType="circle" app:wlv_titleCenter="Center Title" app:wlv_titleCenterColor="@android:color/white" app:wlv_titleCenterSize="24sp" app:wlv_titleCenterStrokeColor="@android:color/holo_blue_dark" app:wlv_titleCenterStrokeWidth="3dp" app:wlv_triangle_direction="north" app:wlv_waveAmplitude="70" app:wlv_waveColor="@color/colorAccent" /> <SeekBar android:id="@+id/seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" /> </LinearLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.SeekBar; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { me.itangqi.waveloadingview.WaveLoadingView loadingView; SeekBar seekBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing the layout seekBar = findViewById(R.id.seekbar); loadingView = findViewById(R.id.waveLoadingView); // changing the progress value according the value changed in seekbar seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { loadingView.setProgressValue(progress); String title = String.valueOf(progress); loadingView.setBottomTitle(""); loadingView.setCenterTitle(""); loadingView.setTopTitle(""); if (progress < 50) { // if progress is 50 then set bottom // title as progress value loadingView.setBottomTitle(title); } else if (progress == 50) { // if progress is 50 then set center // title as progress value loadingView.setCenterTitle(title); } else { // if progress is 50 then set top // title as progress value loadingView.setTopTitle(title); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }}
Output:
annianni
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25246,
"s": 24725,
"text": "Circular Fillable Loader is an outstanding way of showing the ProgressBar in any Android app while loading. Display ProgressBar in another form is one of the best ways to increase the user experience. You can get to see these customize loaders in most of the apps. In this article, we are going to see how to implement Circular Fillable Loader in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25301,
"s": 25246,
"text": "A unique way of representing a ProgressBar in Android."
},
{
"code": null,
"e": 25365,
"s": 25301,
"text": "Using a Circular Fillable Loader increases the user experience."
},
{
"code": null,
"e": 25406,
"s": 25365,
"text": "Gives animated look to our progress bar."
},
{
"code": null,
"e": 25417,
"s": 25406,
"text": "Attributes"
},
{
"code": null,
"e": 25429,
"s": 25417,
"text": "Description"
},
{
"code": null,
"e": 25458,
"s": 25429,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25620,
"s": 25458,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25676,
"s": 25620,
"text": "Step 2: Add dependency in build.gradle(Module:app) file"
},
{
"code": null,
"e": 25795,
"s": 25676,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 25859,
"s": 25795,
"text": "implementation ‘com.mikhaellopez:circularfillableloaders:1.3.2’"
},
{
"code": null,
"e": 25930,
"s": 25859,
"text": "Step 3: Create a new State Progress Bar in your activity_main.xml file"
},
{
"code": null,
"e": 26051,
"s": 25930,
"text": "Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 26055,
"s": 26051,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingLeft=\"16dp\" android:paddingTop=\"16dp\" android:paddingRight=\"16dp\" android:paddingBottom=\"16dp\" tools:context=\".MainActivity\"> <!--Circular Fallible Loader--> <com.mikhaellopez.circularfillableloaders.CircularFillableLoaders android:id=\"@+id/circularFillableLoaders\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerInParent=\"true\" android:src=\"@drawable/ic_baseline_android_24\" app:cfl_border=\"true\" app:cfl_border_width=\"12dp\" app:cfl_progress=\"80\" app:cfl_wave_amplitude=\"0.06\" app:cfl_wave_color=\"@color/purple_200\" /> <!--Seek bar to increase fallible part--> <SeekBar android:id=\"@+id/seekBar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/circularFillableLoaders\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"40dp\" /> </RelativeLayout>",
"e": 27362,
"s": 26055,
"text": null
},
{
"code": null,
"e": 27410,
"s": 27362,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 27600,
"s": 27410,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27605,
"s": 27600,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.SeekBar; import androidx.appcompat.app.AppCompatActivity; import com.mikhaellopez.circularfillableloaders.CircularFillableLoaders; public class MainActivity extends AppCompatActivity { // Variables Declared CircularFillableLoaders circularFillableLoaders; SeekBar seekBar; int progress = 80; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Code for implementing Circular Fallible Loader circularFillableLoaders = (CircularFillableLoaders) findViewById(R.id.circularFillableLoaders); // Set Progress circularFillableLoaders.setProgress(progress); seekBar = findViewById(R.id.seekBar); seekBar.setProgress(progress); seekBar.setMax(100); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { // Set Progress circularFillableLoaders.setProgress(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }}",
"e": 29008,
"s": 27605,
"text": null
},
{
"code": null,
"e": 29139,
"s": 29008,
"text": "Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below."
},
{
"code": null,
"e": 29147,
"s": 29139,
"text": "Output:"
},
{
"code": null,
"e": 29333,
"s": 29147,
"text": "Here we are going to implement the wave loading view. Here we are manually increasing the value of progress and the wave height is increasing. But It can also be used as a timer to set."
},
{
"code": null,
"e": 29362,
"s": 29333,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 29524,
"s": 29362,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 29547,
"s": 29524,
"text": "Step 2: Add dependency"
},
{
"code": null,
"e": 29666,
"s": 29547,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 29724,
"s": 29666,
"text": "implementation ‘me.itangqi.waveloadingview:library:0.3.5’"
},
{
"code": null,
"e": 29772,
"s": 29724,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29915,
"s": 29772,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 29919,
"s": 29915,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"20dp\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <me.itangqi.waveloadingview.WaveLoadingView android:id=\"@+id/waveLoadingView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:wlv_borderColor=\"@color/colorAccent\" app:wlv_borderWidth=\"3dp\" app:wlv_progressValue=\"40\" app:wlv_round_rectangle=\"true\" app:wlv_shapeType=\"circle\" app:wlv_titleCenter=\"Center Title\" app:wlv_titleCenterColor=\"@android:color/white\" app:wlv_titleCenterSize=\"24sp\" app:wlv_titleCenterStrokeColor=\"@android:color/holo_blue_dark\" app:wlv_titleCenterStrokeWidth=\"3dp\" app:wlv_triangle_direction=\"north\" app:wlv_waveAmplitude=\"70\" app:wlv_waveColor=\"@color/colorAccent\" /> <SeekBar android:id=\"@+id/seekbar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:max=\"100\" /> </LinearLayout>",
"e": 31269,
"s": 29919,
"text": null
},
{
"code": null,
"e": 31317,
"s": 31269,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 31507,
"s": 31317,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 31512,
"s": 31507,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.SeekBar; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { me.itangqi.waveloadingview.WaveLoadingView loadingView; SeekBar seekBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing the layout seekBar = findViewById(R.id.seekbar); loadingView = findViewById(R.id.waveLoadingView); // changing the progress value according the value changed in seekbar seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { loadingView.setProgressValue(progress); String title = String.valueOf(progress); loadingView.setBottomTitle(\"\"); loadingView.setCenterTitle(\"\"); loadingView.setTopTitle(\"\"); if (progress < 50) { // if progress is 50 then set bottom // title as progress value loadingView.setBottomTitle(title); } else if (progress == 50) { // if progress is 50 then set center // title as progress value loadingView.setCenterTitle(title); } else { // if progress is 50 then set top // title as progress value loadingView.setTopTitle(title); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }}",
"e": 33408,
"s": 31512,
"text": null
},
{
"code": null,
"e": 33416,
"s": 33408,
"text": "Output:"
},
{
"code": null,
"e": 33425,
"s": 33416,
"text": "annianni"
},
{
"code": null,
"e": 33433,
"s": 33425,
"text": "android"
},
{
"code": null,
"e": 33457,
"s": 33433,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33465,
"s": 33457,
"text": "Android"
},
{
"code": null,
"e": 33470,
"s": 33465,
"text": "Java"
},
{
"code": null,
"e": 33489,
"s": 33470,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33494,
"s": 33489,
"text": "Java"
},
{
"code": null,
"e": 33502,
"s": 33494,
"text": "Android"
},
{
"code": null,
"e": 33600,
"s": 33502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33609,
"s": 33600,
"text": "Comments"
},
{
"code": null,
"e": 33622,
"s": 33609,
"text": "Old Comments"
},
{
"code": null,
"e": 33661,
"s": 33622,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33711,
"s": 33661,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 33762,
"s": 33711,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 33800,
"s": 33762,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 33842,
"s": 33800,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33857,
"s": 33842,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33901,
"s": 33857,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33923,
"s": 33901,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33948,
"s": 33923,
"text": "Reverse a string in Java"
}
] |
RxJava - Conditional Operators
|
Following are the operators which evaluates one or multiple Observables or items emitted.
All
Evaluates all items emitted to meet given criteria.
Amb
Emits all items from the first Observable only given multiple Observables.
Contains
Checks if an Observable emits a particular item or not.
DefaultIfEmpty
Emits default item if Observable do not emit anything.
SequenceEqual
Checks if two Observables emit the same sequence of items.
SkipUntil
Discards items emitted by first Observable until a second Observable emits an item.
SkipWhile
Discard items emitted by an Observable until a given condition becomes false.
TakeUntil
Discards items emitted by an Observable after a second Observable emits an item or terminates.
TakeWhile
Discard items emitted by an Observable after a specified condition becomes false.
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import io.reactivex.Observable;
//Using defaultIfEmpty operator to operate on an Observable
public class ObservableTester {
public static void main(String[] args) {
final StringBuilder result = new StringBuilder();
Observable.empty()
.defaultIfEmpty("No Data")
.subscribe(s -> result.append(s));
System.out.println(result);
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
final StringBuilder result1 = new StringBuilder();
Observable.fromArray(letters)
.firstElement()
.defaultIfEmpty("No data")
.subscribe(s -> result1.append(s));
System.out.println(result1);
}
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java
Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester
It should produce the following output −
No Data
a
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2491,
"s": 2401,
"text": "Following are the operators which evaluates one or multiple Observables or items emitted."
},
{
"code": null,
"e": 2495,
"s": 2491,
"text": "All"
},
{
"code": null,
"e": 2547,
"s": 2495,
"text": "Evaluates all items emitted to meet given criteria."
},
{
"code": null,
"e": 2551,
"s": 2547,
"text": "Amb"
},
{
"code": null,
"e": 2626,
"s": 2551,
"text": "Emits all items from the first Observable only given multiple Observables."
},
{
"code": null,
"e": 2635,
"s": 2626,
"text": "Contains"
},
{
"code": null,
"e": 2691,
"s": 2635,
"text": "Checks if an Observable emits a particular item or not."
},
{
"code": null,
"e": 2706,
"s": 2691,
"text": "DefaultIfEmpty"
},
{
"code": null,
"e": 2761,
"s": 2706,
"text": "Emits default item if Observable do not emit anything."
},
{
"code": null,
"e": 2775,
"s": 2761,
"text": "SequenceEqual"
},
{
"code": null,
"e": 2834,
"s": 2775,
"text": "Checks if two Observables emit the same sequence of items."
},
{
"code": null,
"e": 2844,
"s": 2834,
"text": "SkipUntil"
},
{
"code": null,
"e": 2928,
"s": 2844,
"text": "Discards items emitted by first Observable until a second Observable emits an item."
},
{
"code": null,
"e": 2938,
"s": 2928,
"text": "SkipWhile"
},
{
"code": null,
"e": 3016,
"s": 2938,
"text": "Discard items emitted by an Observable until a given condition becomes false."
},
{
"code": null,
"e": 3026,
"s": 3016,
"text": "TakeUntil"
},
{
"code": null,
"e": 3121,
"s": 3026,
"text": "Discards items emitted by an Observable after a second Observable emits an item or terminates."
},
{
"code": null,
"e": 3131,
"s": 3121,
"text": "TakeWhile"
},
{
"code": null,
"e": 3213,
"s": 3131,
"text": "Discard items emitted by an Observable after a specified condition becomes false."
},
{
"code": null,
"e": 3301,
"s": 3213,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> RxJava."
},
{
"code": null,
"e": 3960,
"s": 3301,
"text": "import io.reactivex.Observable;\n//Using defaultIfEmpty operator to operate on an Observable\npublic class ObservableTester {\n public static void main(String[] args) { \n final StringBuilder result = new StringBuilder();\n Observable.empty()\n .defaultIfEmpty(\"No Data\")\n .subscribe(s -> result.append(s));\n System.out.println(result);\n String[] letters = {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"};\n final StringBuilder result1 = new StringBuilder();\n Observable.fromArray(letters)\n .firstElement()\n .defaultIfEmpty(\"No data\") \n .subscribe(s -> result1.append(s));\n System.out.println(result1);\n }\n}"
},
{
"code": null,
"e": 4012,
"s": 3960,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 4051,
"s": 4012,
"text": "C:\\RxJava>javac ObservableTester.java\n"
},
{
"code": null,
"e": 4093,
"s": 4051,
"text": "Now run the ObservableTester as follows −"
},
{
"code": null,
"e": 4126,
"s": 4093,
"text": "C:\\RxJava>java ObservableTester\n"
},
{
"code": null,
"e": 4167,
"s": 4126,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 4178,
"s": 4167,
"text": "No Data\na\n"
},
{
"code": null,
"e": 4185,
"s": 4178,
"text": " Print"
},
{
"code": null,
"e": 4196,
"s": 4185,
"text": " Add Notes"
}
] |
Print alternate elements of an array | Practice | GeeksforGeeks
|
You are given an array A of size N. You need to print elements of A in alternate order (starting from index 0).
Example 1:
Input:
N = 4
A[] = {1, 2, 3, 4}
​Output:
1 3
Example 2:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
​Output:
1 3 5
Your Task:
Since this is a function problem, you just need to complete the provided function void print(int ar[],int n)
Constraints:
1 <= N <= 105
1 <= Ai <= 105
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
0
sumittripathi16 hours ago
class GfG{ public static void print(int arr[], int n) { // your code here for(int i=0;i<n;i=i+2) { System.out.print(arr[i]+" "); } }}
0
sharmahariom342884 days ago
C Solution:
void print(int ar[], int n)
{
int x;
for (x = 0; x < n; x = x + 2)
{
printf("%d ", ar[x]);
}
}
0
tanmeetsinghreel1 week ago
//Python3
def printAl(arr,n): for i in range(0,n,2): print(arr[i],end=" ")
0
mugadahemanth2 weeks ago
for(int i=0;i<n;i+=2) { printf("%d ",ar[i]); }
+1
payalchaudhary4422 weeks ago
//JAVA CODE :
public static void print(int arr[], int n) {
for(int i=0; i<arr.length; i+=2){ System.out.print(arr[i] +" "); }
}}
0
jaideepkaur00112 weeks ago
#include<iostream>using namespace std;
int main() { int i,n; // int arr[i]; cout<<"Enter size of an array: "; cin>>n; int arr[n]; for(i=0;i<n;i++) { cout<<"Enter elements of an array "<<i<<" :"; cin>>arr[i]; } cout<<"Alternate elements of an array"; for(i=0;i<n;i+=2) { cout<<arr[i]<<"\n"; } return 0; }
0
sakshi69192 weeks ago
int n = arr.length; for(int i=0; i<n; i+=2) { System.out.print(arr[i]);
}
0
tusharbadakh1892 weeks ago
for(int i=0;i<arr.length ;i++) { if(i%2==0) System.out.print(arr[i]+" ");}
+1
rsbly7300952 weeks ago
class Solution { print(arr,n){ let arr1 = []; for(let i = 0;i<n; i+=2) { arr1.push(arr[i]); } console.log(arr1.join(' ')); }}
0
pradhanprasanta792 weeks ago
C#int[] array = { 1, 4, 5, -1, 6, -4, -5, 13, 10 }; for(int i=0;i<=array.Length;i+=2){ Console.WriteLine( array[i]); }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 350,
"s": 238,
"text": "You are given an array A of size N. You need to print elements of A in alternate order (starting from index 0)."
},
{
"code": null,
"e": 361,
"s": 350,
"text": "Example 1:"
},
{
"code": null,
"e": 410,
"s": 361,
"text": "Input:\nN = 4\nA[] = {1, 2, 3, 4}\n​Output:\n1 3\n"
},
{
"code": null,
"e": 421,
"s": 410,
"text": "Example 2:"
},
{
"code": null,
"e": 475,
"s": 421,
"text": "Input:\nN = 5\nA[] = {1, 2, 3, 4, 5}\n​Output:\n1 3 5\n"
},
{
"code": null,
"e": 595,
"s": 475,
"text": "Your Task:\nSince this is a function problem, you just need to complete the provided function void print(int ar[],int n)"
},
{
"code": null,
"e": 637,
"s": 595,
"text": "Constraints:\n1 <= N <= 105\n1 <= Ai <= 105"
},
{
"code": null,
"e": 699,
"s": 637,
"text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 701,
"s": 699,
"text": "0"
},
{
"code": null,
"e": 727,
"s": 701,
"text": "sumittripathi16 hours ago"
},
{
"code": null,
"e": 901,
"s": 727,
"text": "class GfG{ public static void print(int arr[], int n) { // your code here for(int i=0;i<n;i=i+2) { System.out.print(arr[i]+\" \"); } }}"
},
{
"code": null,
"e": 903,
"s": 901,
"text": "0"
},
{
"code": null,
"e": 931,
"s": 903,
"text": "sharmahariom342884 days ago"
},
{
"code": null,
"e": 943,
"s": 931,
"text": "C Solution:"
},
{
"code": null,
"e": 1064,
"s": 945,
"text": "void print(int ar[], int n)\n{\n int x;\n for (x = 0; x < n; x = x + 2)\n {\n printf(\"%d \", ar[x]);\n }\n}"
},
{
"code": null,
"e": 1066,
"s": 1064,
"text": "0"
},
{
"code": null,
"e": 1093,
"s": 1066,
"text": "tanmeetsinghreel1 week ago"
},
{
"code": null,
"e": 1103,
"s": 1093,
"text": "//Python3"
},
{
"code": null,
"e": 1176,
"s": 1103,
"text": "def printAl(arr,n): for i in range(0,n,2): print(arr[i],end=\" \")"
},
{
"code": null,
"e": 1178,
"s": 1176,
"text": "0"
},
{
"code": null,
"e": 1203,
"s": 1178,
"text": "mugadahemanth2 weeks ago"
},
{
"code": null,
"e": 1260,
"s": 1203,
"text": "for(int i=0;i<n;i+=2) { printf(\"%d \",ar[i]); }"
},
{
"code": null,
"e": 1263,
"s": 1260,
"text": "+1"
},
{
"code": null,
"e": 1292,
"s": 1263,
"text": "payalchaudhary4422 weeks ago"
},
{
"code": null,
"e": 1306,
"s": 1292,
"text": "//JAVA CODE :"
},
{
"code": null,
"e": 1353,
"s": 1306,
"text": " public static void print(int arr[], int n) {"
},
{
"code": null,
"e": 1436,
"s": 1353,
"text": " for(int i=0; i<arr.length; i+=2){ System.out.print(arr[i] +\" \"); }"
},
{
"code": null,
"e": 1439,
"s": 1436,
"text": "}}"
},
{
"code": null,
"e": 1443,
"s": 1441,
"text": "0"
},
{
"code": null,
"e": 1470,
"s": 1443,
"text": "jaideepkaur00112 weeks ago"
},
{
"code": null,
"e": 1509,
"s": 1470,
"text": "#include<iostream>using namespace std;"
},
{
"code": null,
"e": 1918,
"s": 1509,
"text": "int main() { int i,n; // int arr[i]; cout<<\"Enter size of an array: \"; cin>>n; int arr[n]; for(i=0;i<n;i++) { cout<<\"Enter elements of an array \"<<i<<\" :\"; cin>>arr[i]; } cout<<\"Alternate elements of an array\"; for(i=0;i<n;i+=2) { cout<<arr[i]<<\"\\n\"; } return 0; } "
},
{
"code": null,
"e": 1920,
"s": 1918,
"text": "0"
},
{
"code": null,
"e": 1942,
"s": 1920,
"text": "sakshi69192 weeks ago"
},
{
"code": null,
"e": 2043,
"s": 1942,
"text": "int n = arr.length; for(int i=0; i<n; i+=2) { System.out.print(arr[i]);"
},
{
"code": null,
"e": 2045,
"s": 2043,
"text": "}"
},
{
"code": null,
"e": 2047,
"s": 2045,
"text": "0"
},
{
"code": null,
"e": 2074,
"s": 2047,
"text": "tusharbadakh1892 weeks ago"
},
{
"code": null,
"e": 2150,
"s": 2074,
"text": "for(int i=0;i<arr.length ;i++) { if(i%2==0) System.out.print(arr[i]+\" \");}"
},
{
"code": null,
"e": 2153,
"s": 2150,
"text": "+1"
},
{
"code": null,
"e": 2176,
"s": 2153,
"text": "rsbly7300952 weeks ago"
},
{
"code": null,
"e": 2323,
"s": 2176,
"text": "class Solution { print(arr,n){ let arr1 = []; for(let i = 0;i<n; i+=2) { arr1.push(arr[i]); } console.log(arr1.join(' ')); }}"
},
{
"code": null,
"e": 2325,
"s": 2323,
"text": "0"
},
{
"code": null,
"e": 2354,
"s": 2325,
"text": "pradhanprasanta792 weeks ago"
},
{
"code": null,
"e": 2498,
"s": 2354,
"text": "C#int[] array = { 1, 4, 5, -1, 6, -4, -5, 13, 10 }; for(int i=0;i<=array.Length;i+=2){ Console.WriteLine( array[i]); }"
},
{
"code": null,
"e": 2644,
"s": 2498,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 2680,
"s": 2644,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2690,
"s": 2680,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2700,
"s": 2690,
"text": "\nContest\n"
},
{
"code": null,
"e": 2763,
"s": 2700,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2911,
"s": 2763,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3119,
"s": 2911,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3225,
"s": 3119,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Batch Script - SHUTDOWN
|
This batch command shuts down a computer, or logs off the current user.
shutdown
@echo off
shutdown
If the user executing the batch files has the relevant rights, the computer will be shutdown.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2241,
"s": 2169,
"text": "This batch command shuts down a computer, or logs off the current user."
},
{
"code": null,
"e": 2251,
"s": 2241,
"text": "shutdown\n"
},
{
"code": null,
"e": 2271,
"s": 2251,
"text": "@echo off \nshutdown"
},
{
"code": null,
"e": 2365,
"s": 2271,
"text": "If the user executing the batch files has the relevant rights, the computer will be shutdown."
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": " Print"
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": " Add Notes"
}
] |
Analysis of Variance — ANOVA with Python | Towards Data Science
|
In a series of weekly articles, I will cover some important statistics topics with a twist.
The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more.
At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week.
Articles published so far:
Bernoulli and Binomial Random Variables with Python
From Binomial to Geometric and Poisson Random Variables with Python
Sampling Distribution of a Sample Proportion with Python
Confidence Intervals with Python
Significance Tests with Python
Two-sample Inference for the Difference Between Groups with Python
Inference for Categorical Data
Advanced Regression
Analysis of Variance — ANOVA
As usual, the code is available on my GitHub.
Once again, we are working with the salaries of Data Scientists. In this case, we are not interested in predicting the salary based on some independent feature. We are focused on understanding if there is a difference in the mean of the salaries between 3 groups of Data Scientists with distinct backgrounds: the first are samples from graduates from Computer Science, the second from Economics, and the third from Informatics Engineering (notice that the salary unit is 10,000€).
import pandas as pdimport numpy as npfrom scipy.stats import fdf = pd.DataFrame.from_dict({'g1': [5,9,10,12,8,8,9], 'g2': [5,4, 4, 5,5,4,8], 'g3': [9,8, 5, 6,7,7,6]})df
The first step to perform an ANOVA test is to calculate the SST (total sum of squares), the SSW (total sum of squares within), and the SSB (total sum of squares between), and the corresponding degrees of freedom. They calculated as following:
SST is the sum of the squared distance between each data point and the mean of the dataset. The degrees of freedom, in this case, is the number of groups m times the number of data points n in each group, and then we subtract 1, i.e., m•n -1.
SSW is the sum of the squared distance between each data point and the respective group mean. The degrees of freedom is the number of groups times the number of data points minus 1, i.e., m•(n -1).
SSB is the sum of the squared distance between each group mean and the mean of the dataset for each data point. The degrees of freedom is the number of groups minus 1, i.e., m -1.
m = df.shape[1]n = df.shape[0]SST = np.sum(np.sum((df - np.mean(np.mean(df)))**2))SST98.57142857142858df_sst = m*n-1df_sst20SSW = np.sum(np.sum((df - np.mean(df))**2))SSW50.28571428571429df_ssw = m*(n-1)df_ssw18SSB = np.sum(np.sum((np.tile(np.mean(df), (3,1)) - np.mean(np.mean(df)))**2))SSB20.6938775510204df_ssb = m-1df_ssb2
Let’s define our hypothesis test. Our null hypothesis is the scenario where the background does not make a difference. In contrast, our alternative hypothesis states that background makes a difference in the salary of a Data Scientist.
As usual, we will assume that our null hypothesis is true and figure out the probability of getting a statistic as extreme or more extreme than the one we get from the data observed. For that, we will use an F-statistic, which is basically a ratio of two chi-square statistics. It is actually the ratio of two of the metrics calculated above divided by their respective degrees of freedom:
The idea is that if the numerator is significantly larger than the denominator, this should make us believe that there is a difference between the true populations' means. Conversely, if the denominator is significantly larger, it means that the variation within each sample is a bigger percentage of the total variation when compared with the variation between the samples. Thus, any difference we could observe in the means is probably just a result of random chance.
F = (SSB/df_ssb)/(SSW/df_ssw)F3.703733766233764f.ppf(0.95, dfn=df_ssb, dfd=df_ssw)3.554557145661787
Now, we can calculate our p-value. Let’s use a significance level of 0.1.
p_value = (1 - f.cdf(F, dfn=df_ssb, dfd=df_ssw))*2p_value0.08991458167840971if p_value<0.1: print('Reject H_0')else: print('Accept H_0')Reject H_0
We see that the p-value is smaller than the significance level, which makes us reject the null hypothesis. There is enough evidence to accept a difference between the populations’ means that does not come from chance alone or from the variance within each group. With that said, we can conclude that the salary of a Data Scientist is different depending on the graduation background.
This article covered analysis of variance (ANOVA), a collection of methods for comparing multiple means across different groups. We also introduced a new statistic, called F-statistic, which we used to conduct a hypothesis test on the difference of means of our groups.
This is the final article of this series on “College Statistics with Python.” I hope that you enjoyed it!
Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?
Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?
data = {'Intercept': [200.312, 92.618], 'Battery': [7.546,4.798]}df = pd.DataFrame.from_dict(data, columns=['Coef', 'SE Coef'], orient='index')df
t = (df['Coef'][1]-0)/df['SE Coef'][1]t1.5727386411004585
2. Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?
Rui should reject H_0, i.e., the data suggest a linear relationship between age and the number of kilometers walked yesterday.
|
[
{
"code": null,
"e": 263,
"s": 171,
"text": "In a series of weekly articles, I will cover some important statistics topics with a twist."
},
{
"code": null,
"e": 563,
"s": 263,
"text": "The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more."
},
{
"code": null,
"e": 705,
"s": 563,
"text": "At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week."
},
{
"code": null,
"e": 732,
"s": 705,
"text": "Articles published so far:"
},
{
"code": null,
"e": 784,
"s": 732,
"text": "Bernoulli and Binomial Random Variables with Python"
},
{
"code": null,
"e": 852,
"s": 784,
"text": "From Binomial to Geometric and Poisson Random Variables with Python"
},
{
"code": null,
"e": 909,
"s": 852,
"text": "Sampling Distribution of a Sample Proportion with Python"
},
{
"code": null,
"e": 942,
"s": 909,
"text": "Confidence Intervals with Python"
},
{
"code": null,
"e": 973,
"s": 942,
"text": "Significance Tests with Python"
},
{
"code": null,
"e": 1040,
"s": 973,
"text": "Two-sample Inference for the Difference Between Groups with Python"
},
{
"code": null,
"e": 1071,
"s": 1040,
"text": "Inference for Categorical Data"
},
{
"code": null,
"e": 1091,
"s": 1071,
"text": "Advanced Regression"
},
{
"code": null,
"e": 1120,
"s": 1091,
"text": "Analysis of Variance — ANOVA"
},
{
"code": null,
"e": 1166,
"s": 1120,
"text": "As usual, the code is available on my GitHub."
},
{
"code": null,
"e": 1647,
"s": 1166,
"text": "Once again, we are working with the salaries of Data Scientists. In this case, we are not interested in predicting the salary based on some independent feature. We are focused on understanding if there is a difference in the mean of the salaries between 3 groups of Data Scientists with distinct backgrounds: the first are samples from graduates from Computer Science, the second from Economics, and the third from Informatics Engineering (notice that the salary unit is 10,000€)."
},
{
"code": null,
"e": 1864,
"s": 1647,
"text": "import pandas as pdimport numpy as npfrom scipy.stats import fdf = pd.DataFrame.from_dict({'g1': [5,9,10,12,8,8,9], 'g2': [5,4, 4, 5,5,4,8], 'g3': [9,8, 5, 6,7,7,6]})df"
},
{
"code": null,
"e": 2107,
"s": 1864,
"text": "The first step to perform an ANOVA test is to calculate the SST (total sum of squares), the SSW (total sum of squares within), and the SSB (total sum of squares between), and the corresponding degrees of freedom. They calculated as following:"
},
{
"code": null,
"e": 2350,
"s": 2107,
"text": "SST is the sum of the squared distance between each data point and the mean of the dataset. The degrees of freedom, in this case, is the number of groups m times the number of data points n in each group, and then we subtract 1, i.e., m•n -1."
},
{
"code": null,
"e": 2548,
"s": 2350,
"text": "SSW is the sum of the squared distance between each data point and the respective group mean. The degrees of freedom is the number of groups times the number of data points minus 1, i.e., m•(n -1)."
},
{
"code": null,
"e": 2728,
"s": 2548,
"text": "SSB is the sum of the squared distance between each group mean and the mean of the dataset for each data point. The degrees of freedom is the number of groups minus 1, i.e., m -1."
},
{
"code": null,
"e": 3055,
"s": 2728,
"text": "m = df.shape[1]n = df.shape[0]SST = np.sum(np.sum((df - np.mean(np.mean(df)))**2))SST98.57142857142858df_sst = m*n-1df_sst20SSW = np.sum(np.sum((df - np.mean(df))**2))SSW50.28571428571429df_ssw = m*(n-1)df_ssw18SSB = np.sum(np.sum((np.tile(np.mean(df), (3,1)) - np.mean(np.mean(df)))**2))SSB20.6938775510204df_ssb = m-1df_ssb2"
},
{
"code": null,
"e": 3291,
"s": 3055,
"text": "Let’s define our hypothesis test. Our null hypothesis is the scenario where the background does not make a difference. In contrast, our alternative hypothesis states that background makes a difference in the salary of a Data Scientist."
},
{
"code": null,
"e": 3681,
"s": 3291,
"text": "As usual, we will assume that our null hypothesis is true and figure out the probability of getting a statistic as extreme or more extreme than the one we get from the data observed. For that, we will use an F-statistic, which is basically a ratio of two chi-square statistics. It is actually the ratio of two of the metrics calculated above divided by their respective degrees of freedom:"
},
{
"code": null,
"e": 4151,
"s": 3681,
"text": "The idea is that if the numerator is significantly larger than the denominator, this should make us believe that there is a difference between the true populations' means. Conversely, if the denominator is significantly larger, it means that the variation within each sample is a bigger percentage of the total variation when compared with the variation between the samples. Thus, any difference we could observe in the means is probably just a result of random chance."
},
{
"code": null,
"e": 4251,
"s": 4151,
"text": "F = (SSB/df_ssb)/(SSW/df_ssw)F3.703733766233764f.ppf(0.95, dfn=df_ssb, dfd=df_ssw)3.554557145661787"
},
{
"code": null,
"e": 4325,
"s": 4251,
"text": "Now, we can calculate our p-value. Let’s use a significance level of 0.1."
},
{
"code": null,
"e": 4478,
"s": 4325,
"text": "p_value = (1 - f.cdf(F, dfn=df_ssb, dfd=df_ssw))*2p_value0.08991458167840971if p_value<0.1: print('Reject H_0')else: print('Accept H_0')Reject H_0"
},
{
"code": null,
"e": 4862,
"s": 4478,
"text": "We see that the p-value is smaller than the significance level, which makes us reject the null hypothesis. There is enough evidence to accept a difference between the populations’ means that does not come from chance alone or from the variance within each group. With that said, we can conclude that the salary of a Data Scientist is different depending on the graduation background."
},
{
"code": null,
"e": 5132,
"s": 4862,
"text": "This article covered analysis of variance (ANOVA), a collection of methods for comparing multiple means across different groups. We also introduced a new statistic, called F-statistic, which we used to conduct a hypothesis test on the difference of means of our groups."
},
{
"code": null,
"e": 5238,
"s": 5132,
"text": "This is the final article of this series on “College Statistics with Python.” I hope that you enjoyed it!"
},
{
"code": null,
"e": 5451,
"s": 5238,
"text": "Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?"
},
{
"code": null,
"e": 5664,
"s": 5451,
"text": "Márcia collected data on the battery life and price of a random sample of Portable Computers. Based on the data presented below, what is the test statistic for the null hypothesis that the population slope is 0?"
},
{
"code": null,
"e": 5822,
"s": 5664,
"text": "data = {'Intercept': [200.312, 92.618], 'Battery': [7.546,4.798]}df = pd.DataFrame.from_dict(data, columns=['Coef', 'SE Coef'], orient='index')df"
},
{
"code": null,
"e": 5880,
"s": 5822,
"text": "t = (df['Coef'][1]-0)/df['SE Coef'][1]t1.5727386411004585"
},
{
"code": null,
"e": 6316,
"s": 5880,
"text": "2. Rui obtained a random sample of colleagues at work and noticed a positive linear relationship between their ages and the number of kilometers they said they walked yesterday. A 95% confidence interval for the slope of the regression line was (15.4, 155.2). Rui wants to use this interval to test H_0: β=0 vs. H_1: β ≠ 0 at the 5% significance level. Assume that all conditions for inference have been met. What should Rui conclude?"
}
] |
Is vs As operator keyword in C# - GeeksforGeeks
|
21 Jan, 2019
The difference between is and as operators are as follows:
The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types.
The is operator is of boolean type whereas as operator is not of boolean type.
The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type.
The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.
The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference and boxing conversions
Example of is operator:
// C# program to illustrate the// use of is operator keywordusing System; // taking a classpublic class P { } // taking a class// derived from Ppublic class P1 : P { } // taking a classpublic class P2 { } // Driver Classpublic class GFG { // Main Method public static void Main() { // creating an instance // of class P P o1 = new P(); // creating an instance // of class P1 P1 o2 = new P1(); // checking whether 'o1' // is of type 'P' Console.WriteLine(o1 is P); // checking whether 'o1' is // of type Object class // (Base class for all classes) Console.WriteLine(o1 is Object); // checking whether 'o2' // is of type 'P1' Console.WriteLine(o2 is P1); // checking whether 'o2' is // of type Object class // (Base class for all classes) Console.WriteLine(o2 is Object); // checking whether 'o2' // is of type 'P' // it will return true as P1 // is derived from P Console.WriteLine(o2 is P1); // checking whether o1 // is of type P2 // it will return false Console.WriteLine(o1 is P2); // checking whether o2 // is of type P2 // it will return false Console.WriteLine(o2 is P2); }}
Output:
True
True
True
True
True
False
False
Example of as operator:
// C# program to illustrate the// concept of 'as' operatorusing System; // Classesclass Y { }class Z { } class GFG { // Main method static void Main() { // creating and initializing object array object[] o = new object[5]; o[0] = new Y(); o[1] = new Z(); o[2] = "Hello"; o[3] = 4759.0; o[4] = null; for (int q = 0; q < o.Length; ++q) { // using as operator string str1 = o[q] as string; Console.Write("{0}:", q); // checking for the result if (str1 != null) { Console.WriteLine("'" + str1 + "'"); } else { Console.WriteLine("Is is not a string"); } } }}
Output:
0:Is is not a string
1:Is is not a string
2:'Hello'
3:Is is not a string
4:Is is not a string
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
HashSet in C# with Examples
C# | Replace() Method
|
[
{
"code": null,
"e": 23889,
"s": 23861,
"text": "\n21 Jan, 2019"
},
{
"code": null,
"e": 23948,
"s": 23889,
"text": "The difference between is and as operators are as follows:"
},
{
"code": null,
"e": 24160,
"s": 23948,
"text": "The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types."
},
{
"code": null,
"e": 24239,
"s": 24160,
"text": "The is operator is of boolean type whereas as operator is not of boolean type."
},
{
"code": null,
"e": 24393,
"s": 24239,
"text": "The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type."
},
{
"code": null,
"e": 24534,
"s": 24393,
"text": "The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible."
},
{
"code": null,
"e": 24691,
"s": 24534,
"text": "The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference and boxing conversions"
},
{
"code": null,
"e": 24715,
"s": 24691,
"text": "Example of is operator:"
},
{
"code": "// C# program to illustrate the// use of is operator keywordusing System; // taking a classpublic class P { } // taking a class// derived from Ppublic class P1 : P { } // taking a classpublic class P2 { } // Driver Classpublic class GFG { // Main Method public static void Main() { // creating an instance // of class P P o1 = new P(); // creating an instance // of class P1 P1 o2 = new P1(); // checking whether 'o1' // is of type 'P' Console.WriteLine(o1 is P); // checking whether 'o1' is // of type Object class // (Base class for all classes) Console.WriteLine(o1 is Object); // checking whether 'o2' // is of type 'P1' Console.WriteLine(o2 is P1); // checking whether 'o2' is // of type Object class // (Base class for all classes) Console.WriteLine(o2 is Object); // checking whether 'o2' // is of type 'P' // it will return true as P1 // is derived from P Console.WriteLine(o2 is P1); // checking whether o1 // is of type P2 // it will return false Console.WriteLine(o1 is P2); // checking whether o2 // is of type P2 // it will return false Console.WriteLine(o2 is P2); }}",
"e": 26064,
"s": 24715,
"text": null
},
{
"code": null,
"e": 26072,
"s": 26064,
"text": "Output:"
},
{
"code": null,
"e": 26110,
"s": 26072,
"text": "True\nTrue\nTrue\nTrue\nTrue\nFalse\nFalse\n"
},
{
"code": null,
"e": 26134,
"s": 26110,
"text": "Example of as operator:"
},
{
"code": "// C# program to illustrate the// concept of 'as' operatorusing System; // Classesclass Y { }class Z { } class GFG { // Main method static void Main() { // creating and initializing object array object[] o = new object[5]; o[0] = new Y(); o[1] = new Z(); o[2] = \"Hello\"; o[3] = 4759.0; o[4] = null; for (int q = 0; q < o.Length; ++q) { // using as operator string str1 = o[q] as string; Console.Write(\"{0}:\", q); // checking for the result if (str1 != null) { Console.WriteLine(\"'\" + str1 + \"'\"); } else { Console.WriteLine(\"Is is not a string\"); } } }}",
"e": 26895,
"s": 26134,
"text": null
},
{
"code": null,
"e": 26903,
"s": 26895,
"text": "Output:"
},
{
"code": null,
"e": 26998,
"s": 26903,
"text": "0:Is is not a string\n1:Is is not a string\n2:'Hello'\n3:Is is not a string\n4:Is is not a string\n"
},
{
"code": null,
"e": 27013,
"s": 26998,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 27016,
"s": 27013,
"text": "C#"
},
{
"code": null,
"e": 27114,
"s": 27016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27142,
"s": 27114,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27160,
"s": 27142,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27206,
"s": 27160,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27221,
"s": 27206,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27261,
"s": 27221,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27284,
"s": 27261,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27315,
"s": 27284,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27337,
"s": 27315,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27365,
"s": 27337,
"text": "HashSet in C# with Examples"
}
] |
Gerrit - Prepare Push Change Set to Gerrit
|
You need to review the changes in Gerrit before merging them into the master. The changes can be synchronized that have occurred in the master. Use the following command within the branch that you have been working on.
$ git pull --rebase origin master
The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master.
The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master.
When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review.
When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review.
Git pull --rebase is often used when changes do not deserve a separate branch.
Git pull --rebase is often used when changes do not deserve a separate branch.
Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase.
Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase.
First, run the command as git pull origin master as shown in the following screenshot.
Now use the command as git rebase master to rebase the commits as shown in the following screenshot.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2457,
"s": 2238,
"text": "You need to review the changes in Gerrit before merging them into the master. The changes can be synchronized that have occurred in the master. Use the following command within the branch that you have been working on."
},
{
"code": null,
"e": 2492,
"s": 2457,
"text": "$ git pull --rebase origin master\n"
},
{
"code": null,
"e": 2612,
"s": 2492,
"text": "The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master."
},
{
"code": null,
"e": 2732,
"s": 2612,
"text": "The above command will fetch the changes or commits from the remote branch and rebase the commits on top of the master."
},
{
"code": null,
"e": 2843,
"s": 2732,
"text": "When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review."
},
{
"code": null,
"e": 2954,
"s": 2843,
"text": "When you are done with the changes and rebased the commits, you can push your change set to Gerrit for review."
},
{
"code": null,
"e": 3033,
"s": 2954,
"text": "Git pull --rebase is often used when changes do not deserve a separate branch."
},
{
"code": null,
"e": 3112,
"s": 3033,
"text": "Git pull --rebase is often used when changes do not deserve a separate branch."
},
{
"code": null,
"e": 3239,
"s": 3112,
"text": "Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase."
},
{
"code": null,
"e": 3366,
"s": 3239,
"text": "Git pull is a combination of git fetch and git merge; where as git pull --rebase is a combination of git fetch and git rebase."
},
{
"code": null,
"e": 3453,
"s": 3366,
"text": "First, run the command as git pull origin master as shown in the following screenshot."
},
{
"code": null,
"e": 3554,
"s": 3453,
"text": "Now use the command as git rebase master to rebase the commits as shown in the following screenshot."
},
{
"code": null,
"e": 3561,
"s": 3554,
"text": " Print"
},
{
"code": null,
"e": 3572,
"s": 3561,
"text": " Add Notes"
}
] |
BigDecimal stripTrailingZeros() Method in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.
Syntax:
public BigDecimal stripTrailingZeros()
Parameter: This method does not accepts any parameter.
Return value: This method returns a numerical value equal to the BigDecimal with all the trailing zeros being removed.
Examples:
Input: 785.000
Output: 785
Input: 125500000
Output: 1.255E+8
Below programs illustrate the working of the above mentioned method:Program 1:
// Program to demonstrate stripTrailingZeros() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("785.000"); BigDecimal b2 = new BigDecimal("125500"); // Assigning the result of stripTrailingZeros method // to BigDecimal objects b3, b4 BigDecimal b3 = b1.stripTrailingZeros(); BigDecimal b4 = b2.stripTrailingZeros(); // print b3, b4 values System.out.println(b1 + " after removing trailing zeros " + b3); System.out.println(b2 + " after removing trailing zeros " + b4); }}
785.000 after removing trailing zeros 785
125500 after removing trailing zeros 1.255E+5
Program 2:
// Program to demonstrate stripTrailingZeros() method of BigDecimal import java.math.*; public class gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("785.00000"); BigDecimal b2 = new BigDecimal("125500000"); // Assigning the result of stripTrailingZeros method // to BigDecimal objects b3, b4 BigDecimal b3 = b1.stripTrailingZeros(); BigDecimal b4 = b2.stripTrailingZeros(); // Printing b3, b4 values System.out.println(b1 + " after removing trailing zeros " + b3); System.out.println(b2 + " after removing trailing zeros " + b4); }}
785.00000 after removing trailing zeros 785
125500000 after removing trailing zeros 1.255E+8
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#stripTrailingZeros()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24230,
"s": 23948,
"text": "The java.math.BigDecimal.stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value."
},
{
"code": null,
"e": 24238,
"s": 24230,
"text": "Syntax:"
},
{
"code": null,
"e": 24278,
"s": 24238,
"text": "public BigDecimal stripTrailingZeros()\n"
},
{
"code": null,
"e": 24333,
"s": 24278,
"text": "Parameter: This method does not accepts any parameter."
},
{
"code": null,
"e": 24452,
"s": 24333,
"text": "Return value: This method returns a numerical value equal to the BigDecimal with all the trailing zeros being removed."
},
{
"code": null,
"e": 24462,
"s": 24452,
"text": "Examples:"
},
{
"code": null,
"e": 24524,
"s": 24462,
"text": "Input: 785.000\nOutput: 785\n\nInput: 125500000\nOutput: 1.255E+8"
},
{
"code": null,
"e": 24603,
"s": 24524,
"text": "Below programs illustrate the working of the above mentioned method:Program 1:"
},
{
"code": "// Program to demonstrate stripTrailingZeros() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"785.000\"); BigDecimal b2 = new BigDecimal(\"125500\"); // Assigning the result of stripTrailingZeros method // to BigDecimal objects b3, b4 BigDecimal b3 = b1.stripTrailingZeros(); BigDecimal b4 = b2.stripTrailingZeros(); // print b3, b4 values System.out.println(b1 + \" after removing trailing zeros \" + b3); System.out.println(b2 + \" after removing trailing zeros \" + b4); }}",
"e": 25242,
"s": 24603,
"text": null
},
{
"code": null,
"e": 25331,
"s": 25242,
"text": "785.000 after removing trailing zeros 785\n125500 after removing trailing zeros 1.255E+5\n"
},
{
"code": null,
"e": 25342,
"s": 25331,
"text": "Program 2:"
},
{
"code": "// Program to demonstrate stripTrailingZeros() method of BigDecimal import java.math.*; public class gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"785.00000\"); BigDecimal b2 = new BigDecimal(\"125500000\"); // Assigning the result of stripTrailingZeros method // to BigDecimal objects b3, b4 BigDecimal b3 = b1.stripTrailingZeros(); BigDecimal b4 = b2.stripTrailingZeros(); // Printing b3, b4 values System.out.println(b1 + \" after removing trailing zeros \" + b3); System.out.println(b2 + \" after removing trailing zeros \" + b4); }}",
"e": 25991,
"s": 25342,
"text": null
},
{
"code": null,
"e": 26085,
"s": 25991,
"text": "785.00000 after removing trailing zeros 785\n125500000 after removing trailing zeros 1.255E+8\n"
},
{
"code": null,
"e": 26185,
"s": 26085,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#stripTrailingZeros()"
},
{
"code": null,
"e": 26201,
"s": 26185,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 26216,
"s": 26201,
"text": "Java-Functions"
},
{
"code": null,
"e": 26226,
"s": 26216,
"text": "java-math"
},
{
"code": null,
"e": 26244,
"s": 26226,
"text": "Java-math-package"
},
{
"code": null,
"e": 26249,
"s": 26244,
"text": "Java"
},
{
"code": null,
"e": 26254,
"s": 26249,
"text": "Java"
},
{
"code": null,
"e": 26352,
"s": 26254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26361,
"s": 26352,
"text": "Comments"
},
{
"code": null,
"e": 26374,
"s": 26361,
"text": "Old Comments"
},
{
"code": null,
"e": 26420,
"s": 26374,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26441,
"s": 26420,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26456,
"s": 26441,
"text": "Stream In Java"
},
{
"code": null,
"e": 26473,
"s": 26456,
"text": "Generics in Java"
},
{
"code": null,
"e": 26492,
"s": 26473,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26522,
"s": 26492,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26565,
"s": 26522,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26594,
"s": 26565,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26610,
"s": 26594,
"text": "Strings in Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.